非同期サポート¶
Django has support for writing asynchronous ("async") views, along with an entirely async-enabled request stack if you are running under ASGI. Async views will still work under WSGI, but with a small per-request adaptation cost (see パフォーマンス), and without the ability to have efficient long-running requests.
Many parts of Django provide asynchronous APIs, including the ORM, the cache framework, authentication, sessions, and signals.
For other code, the sync_to_async() adapter is a low-cost bridge (see
パフォーマンス). A wide range of async-native Python libraries can
also be integrated.
非同期ビュー¶
どのようなビューでも、呼び出し可能オブジェクトでコルーチンを返すようにすれば、非同期として宣言できます。その際には、一般的に async def を使います。関数ベースのビューの場合、async def を用いてビュー全体を宣言します。クラスベースのビューの場合、get() と post() などのメソッドを async def で宣言します (__init__() でも as_view() でもないことに注意)。
注釈
Django は、あなたのビューが非同期かどうか確かめるために asgiref.sync.iscoroutinefunction を使います。もし、コルーチンを返すあなた独自のメソッドを実装する場合は、確実に asgiref.sync.markcoroutinefunction を用いて asgiref.sync.iscoroutinefunction が True を返すようにして下さい。
WSGI サーバーでは、非同期ビューは1回限りのイベントループで実行されます。つまり、非同期 HTTP リクエストなどの非同期機能を問題なく使用できるものの、非同期スタックのメリットは得られないことになります。
非同期スタックの主な利点とは、数百もの接続を Python のスレッドを使わずに処理できることです。これにより、低速ストリーミング、ロングポーリング、その他の便利なレスポンスタイプが使えます。
もしこれらを利用したい場合は、代わりに ASGI を使って Django をデプロイする必要があります。
注釈
A fully asynchronous request stack requires async middleware end-to-end. Where a piece of synchronous middleware sits between an ASGI server and an async view, Django adapts it by running it in its own thread; see パフォーマンス for the cost trade-off.
Django's bundled middleware supports both sync and async. Third-party middleware may not. To see which
middleware Django adapts, turn on debug logging for the django.request
logger and look for log messages about "Asynchronous handler adapted for
middleware ...".
ASGI モードと WSGI モードの両方で、コードを逐次的ではなく並行して実行するために、非同期サポートを安全に使用できます。これは、外部 API やデータストアを扱う際に特に便利です。
まだ同期的な Django の機能を呼び出したい場合、次のように sync_to_async() でラップする必要があります。
from asgiref.sync import sync_to_async
results = await sync_to_async(sync_function, thread_sensitive=True)(pk=123)
非同期ビューから、同期的な Django の機能を誤って呼び出そうとすると、Django の 非同期セーフティプロテクション が発動して、データが破損しないように保護されます。
デコレータ¶
以下のデコレータは、同期ビュー関数でも非同期ビュー関数でも使用できます。
conditional_page()xframe_options_deny()xframe_options_sameorigin()xframe_options_exempt()
例:
from django.views.decorators.cache import never_cache
@never_cache
def my_sync_view(request): ...
@never_cache
async def my_async_view(request): ...
クエリーと ORM¶
With some exceptions, Django can run ORM queries asynchronously:
async for author in Author.objects.filter(name__startswith="A"):
book = await author.books.afirst()
詳細については 非同期クエリ で参照できますが、簡単にまとめると次のようになります。
SQL クエリを発行するすべての
QuerySetメソッドには、aという接頭辞が付いた非同期版があります。async forは (values()とvalues_list()を含む) すべての QuerySet でサポートされている
Asynchronous model methods that use the database are also supported:
async def make_book(*args, **kwargs):
book = Book(...)
await book.asave(using="secondary")
async def make_book_with_tags(tags, *args, **kwargs):
book = await Book.objects.acreate(...)
await book.tags.aset(tags)
トランザクションは非同期モードではまだ機能しません。もしトランザクションの動作が必要なコードがある場合は、そのコードを1つの同期的な関数として書いて、sync_to_async() を使用して呼び出すことをおすすめします。
Persistent database connections, set
via the CONN_MAX_AGE setting, should also be disabled in async mode.
Instead, use your database backend's built-in connection pooling if available,
or investigate a third-party connection pooling option if required. As in
synchronous Django, concurrent requests in a single process share that pool, so
size it to the target in-flight query concurrency.
パフォーマンス¶
When running in a mode that does not match the view (e.g. an async view under WSGI, or a traditional sync view under ASGI), Django must emulate the other call style to allow your code to run. The per-call cost of this adaptation is small: tens of microseconds in the in-request ASGI path, where the running event loop is reused, and a few hundred microseconds in the cold-start path used by management commands, background tasks, and scripts. Against typical request times measured in milliseconds, this is rarely visible in itself, but can become so under GIL contention as the number of active threads grows.
If you find yourself wrapping individual rows or operations in a tight loop,
restructure your code so the loop runs inside a single sync_to_async()
(or async_to_sync()) crossing. The per-call cost of the context switch is
then spread across the whole loop and effectively disappears.
The same per-call adaptation cost applies to middleware. Django will attempt to minimize the number of context-switches between sync and async. If you have an ASGI server, but all your middleware and views are synchronous, it will switch just once, before it enters the middleware stack.
However, if you put synchronous middleware between an ASGI server and an asynchronous view, it will have to switch into sync mode for the middleware and then back to async mode for the view. Django will also hold the sync thread open for middleware exception propagation. For request/response views that hit the ORM and return, this is not usually a meaningful penalty. It matters most when you are using ASGI for high in-process concurrency over non-ORM I/O (for example upstream HTTP fan-out, server-sent events, or other long-lived requests), where the extra thread per request caps that concurrency.
自分のコード上での ASGI と WSGI の違いの影響を知るためには、自分自身でパフォーマンステストを行うべきです。場合によっては、純粋に同期的なコードベースを ASGI 上で実行した場合でも、性能が向上することがあります。これは、それでもリクエストハンドリングのコードはすべて非同期に実行されるためです。一般的には、ASGI モードを有効にする必要があるのは、プロジェクトに非同期のコードがあるときだけです。
切断をハンドリングする¶
長時間のリクエストの場合、ビューが応答を返す前にクライアントが切断することがあります。この場合、asyncio.CancelledErrorがビューで発生します。このエラーをキャッチし、クリーンアップが必要な場合にハンドリングできます:
async def my_view(request):
try:
# Do some work
...
except asyncio.CancelledError:
# Handle disconnect
raise
また、ストリーミングレスポンスでクライアントの切断をハンドリングする こともできます。
非同期安全性¶
- DJANGO_ALLOW_ASYNC_UNSAFE¶
Certain key parts of Django are not able to operate safely in an async environment, as they have global state that is not coroutine-aware. These parts of Django are classified as "async-unsafe", and are protected from execution in an async environment. The synchronous API of the ORM is the main example, but there are other parts that are also protected in this way.
実行中のイベントループ があるスレッドからこれらのパーツを実行しようとすると、 SynchronousOnlyOperation エラーが発生します。このエラーは、非同期関数の内部でなくても発生することに注意してください。 sync_to_async() などを使わずに、非同期関数から直接同期関数を呼び出した場合にも発生します。これは、コードが同期コードとして宣言されていなくても、アクティブなイベントループを持つスレッドで実行されているためです。
このエラーが発生した場合は、問題のコードを非同期コンテキストから呼び出さないように修正する必要があります。代わりに、独自の同期関数それ自体の中で async-unsafe と通信するコードを書き、 asgiref.sync.sync_to_async() (または、自スレッド内で同期コードを実行するための他の方法) を使って呼び出します。
非同期コンテキストは、Django コードを実行している環境によって与えられる場合もあります。たとえば、Jupyter notebooks や IPython 対話シェルはともにアクティブなイベントループを透過的に提供してくれるため、非同期 API との対話がより簡単になります。
もし IPython shell を使用している場合は、次のコマンドでこのイベントループを無効化できます。
%autoawait off
これは IPython のプロンプトのコマンドです。これにより同期的なコードを SynchronousOnlyOperation エラーを起こさずに実行できるようになりますが、同時に、非同期 API を await することもできなくなります。イベントループを戻すには、次のコマンドを実行します。
%autoawait on
IPython 以外の環境にいる場合 (または、何らかの理由で IPython で autoawait がオフにできない場合)、コードが並行して実行される可能性は 確実に ないため、同期コードは 絶対に 非同期コンテキストから実行する必要があります。このとき、警告は DJANGO_ALLOW_ASYNC_UNSAFE 環境変数を任意の値に設定することで無効化できます。
警告
このオプションを有効にした上で、Djangoの async-unsafe パーツへ同時アクセスがあると、データが失われたり壊れたりする可能性があります。十分な注意を払い、本番環境では使用しないでください。
もし、これをPython内部から行いたい場合は、os.environ を使用してください。
import os
os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"
非同期アダプター関数¶
同期コードを非同期コンテキストから呼び出したり、その逆をするためには、呼び出しスタイルを調整する必要があります。このために asgiref.sync モジュールの async_to_sync() と sync_to_async() という2つのアダプター関数があります。これらは互換性を維持したまま呼び出しスタイル間を移行するために使われます。
これらのアダプター関数は Django で幅広く利用されています。asgiref パッケージ自体が Django プロジェクトの一部になっており、Django を pip でインストールしたときに自動的に依存関係としてインストールされます。
async_to_sync()¶
- async_to_sync(async_function, force_new_loop=False)¶
非同期関数を取り、それをラッピングした同期関数を返します。直接ラッパーとしてもデコレーターとしても使用できます。
from asgiref.sync import async_to_sync
async def get_data(): ...
sync_get_data = async_to_sync(get_data)
@async_to_sync
async def get_other_data(): ...
非同期関数は、もし存在すれば、現在のスレッドのイベントループの中で実行されます。現在のイベントループが存在しない場合、1つの非同期呼び出しのために専用の新しいイベントループが生成され、完了したら再び破棄されます。どちらの状況でも、非同期関数はコードが呼び出されたスレッドとは異なるスレッドで実行されます。
threadlocal とコンテキスト変数の値は双方向に境界を越えて保持されます。
async_to_sync() is essentially a more powerful version of the
asyncio.run() function in Python's standard library. As well as ensuring
threadlocals work, it also enables the thread_sensitive mode of
sync_to_async() when that wrapper is used below it. In the cold path
(no running event loop) it pays the cost of starting a fresh event loop, like
asyncio.run(); when an event loop is already running (the in-request ASGI
case), the running loop is reused and the cost drops accordingly.
sync_to_async()¶
- sync_to_async(sync_function, thread_sensitive=True)¶
同期関数を取り、それをラッピングした非同期関数を返します。直接ラッパーとしてもデコレーターとしても使用できます。
from asgiref.sync import sync_to_async
async_function = sync_to_async(sync_function, thread_sensitive=False)
async_function = sync_to_async(sensitive_sync_function, thread_sensitive=True)
@sync_to_async
def sync_function(): ...
threadlocal とコンテキスト変数の値は双方向に境界を越えて保持されます。
同期関数はすべてメインスレッド内で実行されることを想定して書かれる傾向があるため、sync_to_async() には2種類の threading モードがあります。
thread_sensitive=True(デフォルト): 同期関数は他のすべてのthread_sensitive関数と同じスレッド内で実行されます。もしメインスレッドが同期的でasync_to_sync()ラッパーを使用している場合、このスレッドはメインスレッドになるでしょう。thread_sensitive=False: 同期関数は、まったく新しいスレッドで実行されます。そのスレッドは、その後呼び出しが完了すると閉じられます。
thread-sensitive モードは極めて特別なモードで、すべての関数が同一スレッドで実行されるようにするためにたくさんの仕事を行います。ただし、メインスレッドで正しく動作するように、スタック内での async_to_sync() の使用に依存している ことに注意してください。もし asyncio.run() や類似のメソッドを使用した場合、thread-sensitive な関数は単一の共有スレッドでの実行にフォールバックしますが、これはメインスレッドではありません。
Django でこれが必要な理由は、多くのライブラリ、特にデータベースアダプターが、自分が作られたのと同一スレッド内でのアクセスを必要とするためです。また、既存の多くの Django コードも、すべてが同一スレッドで実行されることを想定しています。たとえば、ビュー内で後で使用するためにリクエストに何かを追加するミドルウェアです。
このコードによって潜在的な互換性の問題を引き起こす代わりに、私たちはこのモードを追加する選択をしました。これにより、既存のすべての Django の同期コードが同一スレッドで実行されるようになり、したがって、非同期モードと完全に互換になります。同期コードは、それを呼び出すすべての非同期コードとは常に 異なる スレッド内にあるため、生のデータベースハンドルや、その他 thread-sensitive な参照を渡すことは避ける必要があることに注意してください。
Within a single request, multiple thread_sensitive calls serialize on that
request's worker thread, but each request gets its own per-context worker, so
concurrent requests do not serialize against each other. This mirrors
Django's connection-per-thread model, and the same constraint applies in other
async database libraries, where concurrent queries on a single connection
serialize on a lock. To support more concurrent requests, increase the
connection pool size accordingly rather than disabling thread_sensitive.
実用的には、この制限は、sync_to_async() を呼び出すときにデータベースの connection オブジェクトの機能を渡してはならないことを意味します。もしそうした場合、スレッド安全性のチェックがトリガーされます:
# DJANGO_SETTINGS_MODULE=settings.py python -m asyncio
>>> import asyncio
>>> from asgiref.sync import sync_to_async
>>> from django.db import connection
>>> # In an async context so you cannot use the database directly:
>>> connection.cursor()
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from
an async context - use a thread or sync_to_async.
>>> # Nor can you pass resolved connection attributes across threads:
>>> await sync_to_async(connection.cursor)()
django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread
can only be used in that same thread. The object with alias 'default' was
created in thread id 4371465600 and this is thread id 6131478528.
代わりに、呼び出しコード内の connection オブジェクトに依存せずに、sync_to_async() で呼び出すことができるヘルパー関数内にすべてのデータベースアクセスをカプセル化する必要があります。