votes up 3

Async cannot be used with this combination of Python and Greenlet versions.

Package:
flask
github stars 56479
Exception Class:
RuntimeError

Raise code

pt ImportError:
            raise RuntimeError(
                "Install Flask with the 'async' extra in order to use async views."
            )

        # Check that Werkzeug isn't using its fallback ContextVar class.
        if ContextVar.__module__ == "werkzeug.local":
            raise RuntimeError(
                "Async cannot be used with this combination of Python "
                "and Greenlet versions."
            )

        return asgiref_async_to_sync(func)

    def make_response(self, rv: ResponseReturnValue) -> Response:
        """C """
😲 Agile task management is now easier than calling a taxi. #Tracklify

Ways to fix

votes up 3 votes down

This error is raised when running async functionality in flask 2 using python version 3.6.

Reproducing the error:

  • Installing python 3.6 (Linux)

sudo apt update

sudo apt install python3.6

  • Create a virtual env using python 3.6

mkdir flask_test

cd flask_test

pipenv --python 3.6

pipenv shell

  • Install necessary libraries

(flask_test) $ pipenv install Flask

(flask_test) $ pipenv install asgiref

  • Write the sample flask code and save it to flask_async.py

from flask import Flask
import asyncio


app = Flask(__name__)


async def load_user_from_database():
    """Mimics a long-running operation to load a user from an external database."""
    app.logger.info('Loading user from database...')
    await asyncio.sleep(1)


@app.before_request
async def add_drink():
    await load_user_from_database()

  • Run the flask using the following commands

(flask_test) $ export FLASK_APP=flask_async

(flask_test) $ flask run

Terminal output:

* Serving Flask app 'flask_async' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Now let's test it by going to http://127.0.0.1:5000/ on a browser.

When a request is made at the specified IP and Port the following error is thrown on the running terminal.

Traceback (most recent call last):
  File "/home/kellem/.local/share/virtualenvs/new_python-w4jh62jl/lib/python3.6/site-packages/flask/app.py", line 2070, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/kellem/.local/share/virtualenvs/new_python-w4jh62jl/lib/python3.6/site-packages/flask/app.py", line 1515, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/kellem/.local/share/virtualenvs/new_python-w4jh62jl/lib/python3.6/site-packages/flask/app.py", line 1511, in full_dispatch_request
    rv = self.preprocess_request()
  File "/home/kellem/.local/share/virtualenvs/new_python-w4jh62jl/lib/python3.6/site-packages/flask/app.py", line 1857, in preprocess_request
    rv = self.ensure_sync(func)()
  File "/home/kellem/.local/share/virtualenvs/new_python-w4jh62jl/lib/python3.6/site-packages/flask/app.py", line 1596, in ensure_sync
    return self.async_to_sync(func)
  File "/home/kellem/.local/share/virtualenvs/new_python-w4jh62jl/lib/python3.6/site-packages/flask/app.py", line 1624, in async_to_sync
    "Async cannot be used with this combination of Python "
RuntimeError: Async cannot be used with this combination of Python and Greenlet versions.
127.0.0.1 - - [21/Jul/2021 17:21:31] "GET / HTTP/1.1" 500 -

How to fix it:

The ContextVar class is used to declare and work with Context Variables and is introduced in python 3.7.1 acording to the python documentation Since the flask asyncio tasks require this class, an error is raised for python<3.7. Check this commit message.

In order to make this work, we have to update python to the latest version or any other version that is 3.7+ and run the flask app.

In my case I will run it on Python 3.8.10

mkdir flask_test_3.8

cd flask_test_3.8

pipenv --python 3.8

pipenv shell

  • Install necessary libraries

(flask_test_3.8) $ pipenv install Flask

(flask_test_3.8) $ pipenv install asgiref

  • Test it by going to http://127.0.0.1:5000/ on a browser.

Output:

* Serving Flask app 'flask_async' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [21/Jul/2021 17:39:38] "GET / HTTP/1.1" 404 -

The above output shows that even though it is 404 response, the code is perfectly working. It is not throwing any kind of error.

The 404 response is because of the an handled path, i.e "/".

Jul 21, 2021 kellemnegasi answer
kellemnegasi 22.6k

Add a possible fix

Please authorize to post fix