| 1 |
.. _async_compatibility: |
| 2 |
|
| 3 |
Async compatibility |
| 4 |
=================== |
| 5 |
|
| 6 |
Synchronous and asynchronous code are not directly compatible in that |
| 7 |
the functions must be called differently depending on the type. This |
| 8 |
limits what can be done, for example in how Quart interacts with Flask |
| 9 |
extensions and any effort to make Flask directly asynchronous. |
| 10 |
|
| 11 |
In my opinion it is much easier to start with an asynchronous codebase |
| 12 |
that calls synchronous code than vice versa in Python. I will try and |
| 13 |
reason why below. |
| 14 |
|
| 15 |
Calling sync code from async functions |
| 16 |
-------------------------------------- |
| 17 |
|
| 18 |
This is mostly easy in that you can either call, or via a simple wrapper |
| 19 |
await a synchronous function, |
| 20 |
|
| 21 |
.. code-block:: python |
| 22 |
|
| 23 |
async def example(): |
| 24 |
sync_call() |
| 25 |
await asyncio.coroutine(sync_call)() |
| 26 |
|
| 27 |
whilst this doesn't actually change the nature, the call is |
| 28 |
synchronous, it does work. |
| 29 |
|
| 30 |
Calling async code from sync functions |
| 31 |
-------------------------------------- |
| 32 |
|
| 33 |
This is where things get difficult, as it is only possible to create a |
| 34 |
single event loop. Hence this can only be used once, |
| 35 |
|
| 36 |
.. code-block:: python |
| 37 |
|
| 38 |
def example(): |
| 39 |
loop = asyncio.get_event_loop() |
| 40 |
loop.run_until_complete(async_call()) |
| 41 |
|
| 42 |
therefore if you are not at the very outer scope it isn't really |
| 43 |
possible to call asynchronous code from a synchronous function. |
| 44 |
|
| 45 |
This is problematic when dealing with Flask extensions as for example the |
| 46 |
extension may have something like, |
| 47 |
|
| 48 |
.. code-block:: python |
| 49 |
|
| 50 |
@app.route('/') |
| 51 |
def route(): |
| 52 |
data = request.form |
| 53 |
return render_template_string("{{ name }}", name=data['name']) |
| 54 |
|
| 55 |
whilst the route function can be wrapped with the |
| 56 |
``asyncio.coroutine`` function and hence awaited, there is no (easy?) |
| 57 |
way to insert the ``await`` before the ``request.form`` and |
| 58 |
``render_template`` calls. |
| 59 |
|
| 60 |
It is for this reason that Quart-Flask-Patch creates sync wrapped |
| 61 |
versions for the Flask extensions. The former adding synchronous |
| 62 |
request methods and the other providing synchronous functions. |
| 63 |
|
| 64 |
Quart monkey patches a ``sync_wait`` method onto the base event loop |
| 65 |
allowing for definitions such as, |
| 66 |
|
| 67 |
.. code-block:: python |
| 68 |
|
| 69 |
from quart.templating import render_template as quart_render_template |
| 70 |
|
| 71 |
def render_template(*args): |
| 72 |
return asyncio.sync_wait(quart_render_template(*args)) |