{"title":"非同期サポート","version":"3.0","locale":"ja","docname":"topics/async","url":"/ja/3.0/topics/async/","canonical":"https://djangodocs.dev/ja/3.0/topics/async/","summary":"Django は非同期 (\"async\") Python の試験的サポートをしていますが、ビューやミドルウェアの非同期サポートはなされていません。","html":"<h1>非同期サポート<a class=\"heading-anchor\" href=\"#asynchronous-support\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h1>\n<aside class=\"version-note version-added\" data-version=\"3.0\" role=\"note\">\n<p class=\"version-note-title\">New in Django 3.0</p></aside>\n<p>Django は非同期 (&quot;async&quot;) Python の試験的サポートをしていますが、ビューやミドルウェアの非同期サポートはなされていません。今後のリリースでサポートされる予定です。</p>\n<p>async エコシステムの他の部分のサポートは限定的です。つまり、 Django はネイティブで <span class=\"xref std std-doc\">ASGI</span> を話し、部分的に非同期安全性をサポートしています。</p>\n<section id=\"async-safety\">\n<span id=\"id1\"></span><h2>非同期安全性<a class=\"heading-anchor\" href=\"#async-safety\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Django の特定のキーパーツは、コルーチンが感知できないグローバルステートを持つため、非同期の環境では安全に操作できません。これらの Django のパーツは、&quot;async-unsafe&quot; として分類されており、非同期な環境での実行から保護されています。ORM は主な例ですが、この他にもこのように保護されているパーツがあります。</p>\n<p>If you try to run any of these parts from a thread where there is a <em>running\nevent loop</em>, you will get a\n<a class=\"reference internal\" href=\"/ja/3.0/ref/exceptions/#django.core.exceptions.SynchronousOnlyOperation\" title=\"django.core.exceptions.SynchronousOnlyOperation\"><code class=\"xref py py-exc docutils literal notranslate\">SynchronousOnlyOperation</code></a> error. Note that you\ndon't have to be inside an async function directly to have this error occur. If\nyou have called a synchronous function directly from an asynchronous function\nwithout going through something like <a class=\"reference internal\" href=\"#asgiref.sync.sync_to_async\" title=\"asgiref.sync.sync_to_async\"><code class=\"xref py py-func docutils literal notranslate\">sync_to_async()</code></a> or a threadpool,\nthen it can also occur, as your code is still running in an asynchronous\ncontext.</p>\n<p>If you encounter this error, you should fix your code to not call the offending\ncode from an async context; instead, write your code that talks to async-unsafe\nin its own, synchronous function, and call that using\n<a class=\"reference internal\" href=\"#asgiref.sync.sync_to_async\" title=\"asgiref.sync.sync_to_async\"><code class=\"xref py py-func docutils literal notranslate\">asgiref.sync.sync_to_async()</code></a>, or any other preferred way of running\nsynchronous code in its own thread.</p>\n<p>もしこのコードを <em>絶対に</em> 切実に非同期コンテキストから実行する必要がある場合 - 例えば、外部の環境に強制されていて、同時に実行される可能性が確実にない場合 (例:  <a class=\"reference external\" href=\"https://jupyter.org/\">Jupyter</a> notebook の中など)、環境変数 <code class=\"docutils literal notranslate\">DJANGO_ALLOW_ASYNC_UNSAFE</code> で警告を無効化できます。</p>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">警告</p>\n<p>このオプションを有効にした上で、Djangoの  async-unsafe パーツへ同時アクセスがあると、データが失われたり壊れたりする可能性があります。十分な注意を払い、本番環境では使用しないでください。</p>\n</aside>\n<p>もし、これをPython内部から行いたい場合は、 <code class=\"docutils literal notranslate\">os.environ</code>:: を使用してください。</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>os<span class=\"o\">.</span>environ<span class=\"p\">[</span><span class=\"s2\">&quot;DJANGO_ALLOW_ASYNC_UNSAFE&quot;</span><span class=\"p\">]</span> <span class=\"o\">=</span> <span class=\"s2\">&quot;true&quot;</span>\n</code></pre></div>\n</section>\n<section id=\"async-adapter-functions\">\n<h2>Async adapter functions<a class=\"heading-anchor\" href=\"#async-adapter-functions\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>It is necessary to adapt the calling style when calling synchronous code from\nan asynchronous context, or vice-versa. For this there are two adapter\nfunctions, made available from the <code class=\"docutils literal notranslate\">asgiref.sync</code> package:\n<a class=\"reference internal\" href=\"#asgiref.sync.async_to_sync\" title=\"asgiref.sync.async_to_sync\"><code class=\"xref py py-func docutils literal notranslate\">async_to_sync()</code></a> and <a class=\"reference internal\" href=\"#asgiref.sync.sync_to_async\" title=\"asgiref.sync.sync_to_async\"><code class=\"xref py py-func docutils literal notranslate\">sync_to_async()</code></a>. They are used to transition\nbetween sync and async calling styles while preserving compatibility.</p>\n<p>These adapter functions are widely used in Django. The <a class=\"reference external\" href=\"https://pypi.org/project/asgiref/\">asgiref</a> package\nitself is part of the Django project, and it is automatically installed as a\ndependency when you install Django with <code class=\"docutils literal notranslate\">pip</code>.</p>\n<section id=\"async-to-sync\">\n<h3><code class=\"docutils literal notranslate\">async_to_sync()</code><a class=\"heading-anchor\" href=\"#async-to-sync\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"asgiref.sync.async_to_sync\">\n<span class=\"sig-name descname\">async_to_sync</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">async_function</em>, <em class=\"sig-param\">force_new_loop<span class=\"o\">=</span><span class=\"default_value\">False</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#asgiref.sync.async_to_sync\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>Wraps an asynchronous function and returns a synchronous function in its place.\nCan be used as either a direct wrapper or a decorator:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">asgiref.sync</span> <span class=\"kn\">import</span> async_to_sync\n\nsync_function <span class=\"o\">=</span> async_to_sync<span class=\"p\">(</span>async_function<span class=\"p\">)</span>\n\n<span class=\"nd\">@async_to_sync</span>\n<span class=\"k\">async</span> <span class=\"k\">def</span> <span class=\"nf\">async_function</span><span class=\"p\">(</span><span class=\"o\">...</span><span class=\"p\">):</span>\n    <span class=\"o\">...</span>\n</code></pre></div>\n<p>The asynchronous function is run in the event loop for the current thread, if\none is present. If there is no current event loop, a new event loop is spun up\nspecifically for the async function and shut down again once it completes. In\neither situation, the async function will execute on a different thread to the\ncalling code.</p>\n<p>Threadlocals and contextvars values are preserved across the boundary in both\ndirections.</p>\n<p><a class=\"reference internal\" href=\"#asgiref.sync.async_to_sync\" title=\"asgiref.sync.async_to_sync\"><code class=\"xref py py-func docutils literal notranslate\">async_to_sync()</code></a> is essentially a more powerful version of the\n<a class=\"reference external\" href=\"https://docs.python.org/3/library/asyncio-runner.html#asyncio.run\" title=\"(in Python v3.14)\"><code class=\"xref py py-func docutils literal notranslate\">asyncio.run()</code></a> function available in Python's standard library. As well\nas ensuring threadlocals work, it also enables the <code class=\"docutils literal notranslate\">thread_sensitive</code> mode of\n<a class=\"reference internal\" href=\"#asgiref.sync.sync_to_async\" title=\"asgiref.sync.sync_to_async\"><code class=\"xref py py-func docutils literal notranslate\">sync_to_async()</code></a> when that wrapper is used below it.</p>\n</section>\n<section id=\"sync-to-async\">\n<h3><code class=\"docutils literal notranslate\">sync_to_async()</code><a class=\"heading-anchor\" href=\"#sync-to-async\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"asgiref.sync.sync_to_async\">\n<span class=\"sig-name descname\">sync_to_async</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">sync_function</em>, <em class=\"sig-param\">thread_sensitive<span class=\"o\">=</span><span class=\"default_value\">False</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#asgiref.sync.sync_to_async\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>Wraps a synchronous function and returns an asynchronous (awaitable) function\nin its place. Can be used as either a direct wrapper or a decorator:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">asgiref.sync</span> <span class=\"kn\">import</span> sync_to_async\n\nasync_function <span class=\"o\">=</span> sync_to_async<span class=\"p\">(</span>sync_function<span class=\"p\">)</span>\nasync_function <span class=\"o\">=</span> sync_to_async<span class=\"p\">(</span>sensitive_sync_function<span class=\"p\">,</span> thread_sensitive<span class=\"o\">=</span><span class=\"kc\">True</span><span class=\"p\">)</span>\n\n<span class=\"nd\">@sync_to_async</span>\n<span class=\"k\">def</span> <span class=\"nf\">sync_function</span><span class=\"p\">(</span><span class=\"o\">...</span><span class=\"p\">):</span>\n    <span class=\"o\">...</span>\n</code></pre></div>\n<p>Threadlocals and contextvars values are preserved across the boundary in both\ndirections.</p>\n<p>Synchronous functions tend to be written assuming they all run in the main\nthread, so <a class=\"reference internal\" href=\"#asgiref.sync.sync_to_async\" title=\"asgiref.sync.sync_to_async\"><code class=\"xref py py-func docutils literal notranslate\">sync_to_async()</code></a> has two threading modes:</p>\n<ul class=\"simple\">\n<li><p><code class=\"docutils literal notranslate\">thread_sensitive=False</code> (the default): the synchronous function will run\nin a brand new thread which is then closed once it completes.</p></li>\n<li><p><code class=\"docutils literal notranslate\">thread_sensitive=True</code>: the synchronous function will run in the same\nthread as all other <code class=\"docutils literal notranslate\">thread_sensitive</code> functions, and this will be the main\nthread, if the main thread is synchronous and you are using the\n<a class=\"reference internal\" href=\"#asgiref.sync.async_to_sync\" title=\"asgiref.sync.async_to_sync\"><code class=\"xref py py-func docutils literal notranslate\">async_to_sync()</code></a> wrapper.</p></li>\n</ul>\n<p>Thread-sensitive mode is quite special, and does a lot of work to run all\nfunctions in the same thread. Note, though, that it <em>relies on usage of</em>\n<a class=\"reference internal\" href=\"#asgiref.sync.async_to_sync\" title=\"asgiref.sync.async_to_sync\"><code class=\"xref py py-func docutils literal notranslate\">async_to_sync()</code></a> <em>above it in the stack</em> to correctly run things on the\nmain thread. If you use <code class=\"docutils literal notranslate\">asyncio.run()</code> (or other options instead), it will\nfall back to just running thread-sensitive functions in a single, shared thread\n(but not the main thread).</p>\n<p>The reason this is needed in Django is that many libraries, specifically\ndatabase adapters, require that they are accessed in the same thread that they\nwere created in, and a lot of existing Django code assumes it all runs in the\nsame thread (e.g. middleware adding things to a request for later use by a\nview).</p>\n<p>Rather than introduce potential compatibility issues with this code, we instead\nopted to add this mode so that all existing Django synchronous code runs in the\nsame thread and thus is fully compatible with asynchronous mode. Note, that\nsynchronous code will always be in a <em>different</em> thread to any async code that\nis calling it, so you should avoid passing raw database handles or other\nthread-sensitive references around in any new code you write.</p>\n</section>\n</section>","rootId":"asynchronous-support","toc":[{"title":"非同期安全性","anchor":"async-safety","children":[]},{"title":"Async adapter functions","anchor":"async-adapter-functions","children":[{"title":"async_to_sync()","anchor":"async-to-sync","children":[]},{"title":"sync_to_async()","anchor":"sync-to-async","children":[]}]}],"breadcrumbs":[{"docname":"topics/index","title":"Django を使う","url":"/ja/3.0/topics/"}],"prev":{"docname":"topics/external-packages","title":"External packages","url":"/ja/3.0/topics/external-packages/"},"next":{"docname":"howto/index","title":"「How-to」ガイド","url":"/ja/3.0/howto/"},"formats":{"html":"/ja/3.0/topics/async/","markdown":"/ja/3.0/topics/async.md","json":"/ja/3.0/topics/async.json"},"source":"https://github.com/django/django/blob/stable/3.0.x/docs/topics/async.txt","official":"https://docs.djangoproject.com/ja/3.0/topics/async/","inVersions":["6.1","6.0","5.2","5.1","5.0","4.2","4.1","4.0","3.2","3.1","3.0"],"inLocales":["en","zh-hans","fr","ja","id","pt-br","ko","es","el","pl"]}