{"title":"异步支持","version":"4.1","locale":"zh-hans","docname":"topics/async","url":"/zh-hans/4.1/topics/async/","canonical":"https://djangodocs.dev/zh-hans/4.1/topics/async/","summary":"Django 支持编写异步（“async”）视图，如果在 ASGI 下运行，还支持完全异步的请求堆栈。","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<p>Django 支持编写异步（“async”）视图，如果在 <a class=\"reference internal\" href=\"/zh-hans/4.1/howto/deployment/asgi/\"><span class=\"doc\">ASGI</span></a> 下运行，还支持完全异步的请求堆栈。异步视图仍然可以在 WSGI 下运行，但会有性能损失，并且不能有高效的长时间运行的请求。</p>\n<p>我们仍然在为 ORM 和 Django 的其他部分提供异步支持。你可以期待在未来的版本中看到这个功能。目前，你可以使用 <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> 适配器来和 Django 的同步部分进行交互。你还可以集成一系列的原生异步 Python 库。</p>\n<section id=\"async-views\">\n<h2>异步视图<a class=\"heading-anchor\" href=\"#async-views\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Any view can be declared async by making the callable part of it return a\ncoroutine - commonly, this is done using <code class=\"docutils literal notranslate\">async def</code>. For a function-based\nview, this means declaring the whole view using <code class=\"docutils literal notranslate\">async def</code>. For a\nclass-based view, this means declaring the HTTP method handlers, such as\n<code class=\"docutils literal notranslate\">get()</code> and <code class=\"docutils literal notranslate\">post()</code> as <code class=\"docutils literal notranslate\">async def</code> (not its <code class=\"docutils literal notranslate\">__init__()</code>, or\n<code class=\"docutils literal notranslate\">as_view()</code>).</p>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">Note</p>\n<p>Django 使用 <code class=\"docutils literal notranslate\">asyncio.iscoroutinefunction</code> 来测试视图是否为异步。如果你实现了自己的方法来返回协同程序，请确保你把视图的 <code class=\"docutils literal notranslate\">_is_coroutine</code> 属性设置为 <code class=\"docutils literal notranslate\">asyncio.coroutines._is_coroutine</code> ，这样函数将返回 <code class=\"docutils literal notranslate\">True</code>。</p>\n</aside>\n<p>WSGI 服务器下，异步视图将在其自有的一次性事件循环中运行。这意味着你可以放心使用异步特性（例如并发异步 HTTP 请求），但是你不会获得异步堆栈的好处。</p>\n<p>主要优点是无需使用 Python 线程就能服务数百个连接。这就允许你使用慢流（slow streaming）、长轮询和其他响应类型。</p>\n<p>如果你想使用这些特性，需要使用 <a class=\"reference internal\" href=\"/zh-hans/4.1/howto/deployment/asgi/\"><span class=\"doc\">ASGI</span></a> 来部署 Django。</p>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">Warning</p>\n<p>如果你的站点中没有 <em>非同步中间件</em>，那么你将得到完全异步请求栈的好处。如果有一个同步中间件，那么 Django 必须在每个请求中使用一个线程来安全地为它模拟一个同步环境。</p>\n<p>Middleware can be built to support <a class=\"reference internal\" href=\"/zh-hans/4.1/topics/http/middleware/#async-middleware\"><span class=\"std std-ref\">both sync and async</span></a> contexts. Some of Django's middleware is built like\nthis, but not all. To see what middleware Django has to adapt for, you can\nturn on debug logging for the <code class=\"docutils literal notranslate\">django.request</code> logger and look for log\nmessages about <em>&quot;Asynchronous handler adapted for middleware ...&quot;</em>.</p>\n</aside>\n<p>在 ASGI 和 WSGI 模式里，你可以始终安全地使用异步支持来并发运行代码而不是串行。这在处理外部 API 或数据存储时特别方便。</p>\n<p>If you want to call a part of Django that is still synchronous, you will need\nto wrap it in a <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> call. For example:</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\nresults <span class=\"o\">=</span> <span class=\"k\">await</span> sync_to_async<span class=\"p\">(</span>sync_function<span class=\"p\">,</span> thread_sensitive<span class=\"o\">=</span><span class=\"kc\">True</span><span class=\"p\">)(</span>pk<span class=\"o\">=</span><span class=\"mi\">123</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>If you accidentally try to call a part of Django that is synchronous-only\nfrom an async view, you will trigger Django's\n<a class=\"reference internal\" href=\"#async-safety\"><span class=\"std std-ref\">asynchronous safety protection</span></a> to protect your data from\ncorruption.</p>\n<section id=\"queries-the-orm\">\n<h3>Queries &amp; the ORM<a class=\"heading-anchor\" href=\"#queries-the-orm\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<aside class=\"version-note version-added\" data-version=\"4.1\" role=\"note\">\n<p class=\"version-note-title\">New in Django 4.1</p></aside>\n<p>With some exceptions, Django can run ORM queries asynchronously as well:</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=\"k\">async</span> <span class=\"k\">for</span> author <span class=\"ow\">in</span> Author<span class=\"o\">.</span>objects<span class=\"o\">.</span>filter<span class=\"p\">(</span>name__startswith<span class=\"o\">=</span><span class=\"s2\">&quot;A&quot;</span><span class=\"p\">):</span>\n    book <span class=\"o\">=</span> <span class=\"k\">await</span> author<span class=\"o\">.</span>books<span class=\"o\">.</span>afirst<span class=\"p\">()</span>\n</code></pre></div>\n<p>Detailed notes can be found in <a class=\"reference internal\" href=\"/zh-hans/4.1/topics/db/queries/#async-queries\"><span class=\"std std-ref\">Asynchronous queries</span></a>, but in short:</p>\n<ul class=\"simple\">\n<li><p>All <code class=\"docutils literal notranslate\">QuerySet</code> methods that cause an SQL query to occur have an\n<code class=\"docutils literal notranslate\">a</code>-prefixed asynchronous variant.</p></li>\n<li><p><code class=\"docutils literal notranslate\">async for</code> is supported on all QuerySets (including the output of\n<code class=\"docutils literal notranslate\">values()</code> and <code class=\"docutils literal notranslate\">values_list()</code>.)</p></li>\n</ul>\n<p>Transactions do not yet work in async mode. If you have a piece of code that\nneeds transactions behavior, we recommend you write that piece as a single\nsynchronous function and call it using <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>.</p>\n</section>\n<section id=\"performance\">\n<h3>性能<a class=\"heading-anchor\" href=\"#performance\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>在与视图不匹配的模式里运行时（比如在 WSGI 下的异步视图，在 ASGI 下的传统同步视图），Django 必须模拟其他调用方式来运行你的代码。这个上下文切换回导致大约 1 毫秒的小性能损失。</p>\n<p>这对中间件也是如此。Django 将尝试最小化同步和异步之间上下文切换的次数。如果你有一个 ASGI 服务器，但所有中间件和视图是同步的，那么在进入中间件堆栈之前，它将仅切换一次。</p>\n<p>但是，如果你把同步的中间件放在 ASGI 服务器和异步的视图之间，就必须为中间件切换到同步模式，然后再回到视图的异步模式。Django 还将保持同步线程的开放，以便中间件的异常传播。这可能在一开始并不明显，但增加每个请求一个线程的惩罚可以消除任何异步性能的优势。</p>\n<p>你应该执行性能测试来观察 ASGI 和 WSGI 对你的代码有什么影响。在一些案例中，即使对于 ASGI 下的纯同步代码库，性能也可能会有所提高，因为请求处理代码仍然全部异步执行。通常，只有当项目有异步代码时，才需要开启 ASGI 模式。</p>\n</section>\n</section>\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<dl class=\"std envvar\">\n<dt class=\"sig sig-object std\" id=\"envvar-DJANGO_ALLOW_ASYNC_UNSAFE\">\n<span class=\"sig-name descname\">DJANGO_ALLOW_ASYNC_UNSAFE</span><a class=\"heading-anchor\" href=\"#envvar-DJANGO_ALLOW_ASYNC_UNSAFE\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>Django 的一些关键部分不能在异步环境中安全运行，因为它们的全局状态不支持协同状态。这些部分被归类为&quot;异步不安全&quot;，并且受到保护，不能在异步环境中执行。ORM是主要的例子，但这里也有其他部分以这种方式受到保护。</p>\n<p>如果你试着从有运行事件循环的线程中运行这部分中的任何一个，你会得到一个 <a class=\"reference internal\" href=\"/zh-hans/4.1/ref/exceptions/#django.core.exceptions.SynchronousOnlyOperation\" title=\"django.core.exceptions.SynchronousOnlyOperation\"><code class=\"xref py py-exc docutils literal notranslate\">SynchronousOnlyOperation</code></a> 错误。注意，不用在异步函数内部就会得到这个错误。如果你从异步函数中调用一个同步函数，而没有使用 <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> 或类似方法，也会出现这个问题。这是因为你的代码仍然在具有活动事件循环的线程中运行，即使它可能没有被声明为异步代码。</p>\n<p>如果遇到这个错误，你应该修改你的代码，以免从异步上下文中调用有问题的代码。相反，你可以编写代码在同步函数中与不安全异步交流，并使用 <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> 调用（或在自己的线程中运行同步代码的任何其他方式）。</p>\n<p>在运行你的 Django 代码环境中你可以使用异步上下文语境。例如， <a class=\"reference external\" href=\"https://jupyter.org/\">Jupyter</a> 笔记本和 <a class=\"reference external\" href=\"https://ipython.org\">IPython</a> 互动环境都是明显地提供了一种激活事件循环，所以与异步 APIs 互动更容易。</p>\n<p>如果你正在使用 IPython 环境，你可以通过运行如下命令来禁用这种事件循环:</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=\"o\">%</span>autoawait off\n</code></pre></div>\n<p>作为IPython终端的命令。这会使你得以运行同步代码而不产生:exc:~django.core.exceptions.SynchronousOnlyOperation 错误。然而，你无法等候异步API。重新打开事件循环，请运行:</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=\"o\">%</span>autoawait on\n</code></pre></div>\n<p>If you're in an environment other than IPython (or you can't turn off\n<code class=\"docutils literal notranslate\">autoawait</code> in IPython for some reason), you are <em>certain</em> there is no chance\nof your code being run concurrently, and you <em>absolutely</em> need to run your sync\ncode from an async context, then you can disable the warning by setting the\n<span class=\"target\" id=\"index-0\"></span><a class=\"reference internal\" href=\"#envvar-DJANGO_ALLOW_ASYNC_UNSAFE\"><code class=\"xref std std-envvar docutils literal notranslate\">DJANGO_ALLOW_ASYNC_UNSAFE</code></a> environment variable to any value.</p>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">Warning</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><span class=\"kn\">import</span> <span class=\"nn\">os</span>\n\nos<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>异步适配函数<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>当从异步的上下文中调用同步的代码时，有必要适配调用风格，反之亦然。为此，有两个适配器功能，可从 <code class=\"docutils literal notranslate\">asgiref.sync</code> 模块中获取：<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> 和 <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> 。它们用于调用样式之间转换，同时保持兼容性。</p>\n<p>这些适配函数广泛应用于 Django。<a class=\"reference external\" href=\"https://pypi.org/project/asgiref/\">asgiref</a> 包本身就是 Django 项目的部分，并且它在当你用 <code class=\"docutils literal notranslate\">pip</code> 方式安装 Django 时，会作为依赖项目自动安装。</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>使用异步函数并返回包装它的同步函数。可用作直接包装器或装饰器：</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\n<span class=\"k\">async</span> <span class=\"k\">def</span> <span class=\"nf\">get_data</span><span class=\"p\">(</span><span class=\"o\">...</span><span class=\"p\">):</span>\n    <span class=\"o\">...</span>\n\nsync_get_data <span class=\"o\">=</span> async_to_sync<span class=\"p\">(</span>get_data<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\">get_other_data</span><span class=\"p\">(</span><span class=\"o\">...</span><span class=\"p\">):</span>\n    <span class=\"o\">...</span>\n</code></pre></div>\n<p>如果存在异步函数，那么它会在当前线程的事件循环中运行。如果没有当前事件循环，则会为单独异步调用专门启动一个新的事件循环，并且会在它完成后再次关闭。无论哪种情况，异步函数会在调用代码的不同线程上执行。</p>\n<p>Threadlocals 和 contextvars 值在两个方向的边界上都保持不变。</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> 本质上是 Python 标准库中 <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> 函数更强大的版本。在确保 threadlocals 工作之外，当在它下面使用包装时，它也会启用 <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> 的 <code class=\"docutils literal notranslate\">thread_sensitive</code> 模式。</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\">True</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>使用同步函数并返回包装它的异步函数。可用作直接包装器或装饰器：</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> thread_sensitive<span class=\"o\">=</span><span class=\"kc\">False</span><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 和 contextvars 值在两个方向的边界上都保持不变。</p>\n<p>假设所有同步功能都在主线程中运行时，则倾向于编写同步功能，因此 <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> 有两个线程模式：</p>\n<ul class=\"simple\">\n<li><p><code class=\"docutils literal notranslate\">thread_sensitive=True</code> （默认使用）：同步函数将与所有其它 <code class=\"docutils literal notranslate\">thread_sensitive</code> 函数在相同线程里运行。如果主线程是同步的并且你正在使用 <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> 装饰器，则该同步函数将成为主线程。</p></li>\n<li><p><code class=\"docutils literal notranslate\">thread_sensitive=False</code>：同步函数将在一个全新的线程中运行，该线程一旦完成，将会关闭。</p></li>\n</ul>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">Warning</p>\n<p><code class=\"docutils literal notranslate\">asgiref</code> 3.3.0版本将 <code class=\"docutils literal notranslate\">thread_sensitive</code> 的默认值改为了 <code class=\"docutils literal notranslate\">True</code> 。这是一个更加安全的默认项，并且在许多情况下与Django交互能得到正确的值。但是在使用 <code class=\"docutils literal notranslate\">asgiref</code> 的旧版本在升级前请评估 <code class=\"docutils literal notranslate\">sync_to_async()</code> 的使用情况。</p>\n</aside>\n<p>Thread-sensitive(线程敏感)模式非常特殊，在同一个线程中运行所有函数需要做很多工作。但是请注意，它依赖于堆栈中它上面的 <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> 的使用，以便在主线程上正确运行。如果你使用 <code class=\"docutils literal notranslate\">asyncio.run()</code> 或类似，它将退回到单独共享线程（但不是主线程）中运行 thread-sensitive 函数。</p>\n<p>在 Django 中需要这么做的原因是许多库，特别是数据库适配器，要求它们在创建时所在的同一个线程里对其进行访问。许多现有的 Django 代码也假设它都在同一进程中运行（比如中间件将内容添加到请求中以供稍后在视图中使用）。</p>\n<p>我们没有引入代码潜在的兼容性问题，而是选择了添加这种模式，以便所有现有的 Django 同步代码都在同一个线程中运行，从而完全兼容异步模式。注意，同步代码始终要与调用它的异步代码保持在不同线程中，所以你应该避免传递原始数据库句柄(handles)或者其他 thread-sensitive 引用。</p>\n<p>In practice this restriction means that you should not pass features of the\ndatabase <code class=\"docutils literal notranslate\">connection</code> object when calling <code class=\"docutils literal notranslate\">sync_to_async()</code>. Doing so will\ntrigger the thread safety checks:</p>\n<div class=\"code-block\" data-language=\"pycon\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Python console</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=\"Python console code\"><code><span class=\"go\"># DJANGO_SETTINGS_MODULE=settings.py python -m asyncio</span>\n<span class=\"gp\">&gt;&gt;&gt; </span><span class=\"kn\">import</span> <span class=\"nn\">asyncio</span>\n<span class=\"gp\">&gt;&gt;&gt; </span><span class=\"kn\">from</span> <span class=\"nn\">asgiref.sync</span> <span class=\"kn\">import</span> sync_to_async\n<span class=\"gp\">&gt;&gt;&gt; </span><span class=\"kn\">from</span> <span class=\"nn\">django.db</span> <span class=\"kn\">import</span> connection\n<span class=\"gp\">&gt;&gt;&gt; </span><span class=\"c1\"># In an async context so you cannot use the database directly:</span>\n<span class=\"gp\">&gt;&gt;&gt; </span>connection<span class=\"o\">.</span>cursor<span class=\"p\">()</span>\n<span class=\"gp\">...</span>\n<span class=\"go\">django.core.exceptions.SynchronousOnlyOperation: You cannot call this from</span>\n<span class=\"go\">an async context - use a thread or sync_to_async.</span>\n<span class=\"gp\">&gt;&gt;&gt; </span><span class=\"c1\"># Nor can you pass resolved connection attributes across threads:</span>\n<span class=\"gp\">&gt;&gt;&gt; </span><span class=\"k\">await</span> sync_to_async<span class=\"p\">(</span>connection<span class=\"o\">.</span>cursor<span class=\"p\">)()</span>\n<span class=\"gp\">...</span>\n<span class=\"go\">django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread</span>\n<span class=\"go\">can only be used in that same thread. The object with alias &#39;default&#39; was</span>\n<span class=\"go\">created in thread id 4371465600 and this is thread id 6131478528.</span>\n</code></pre></div>\n<p>Rather, you should encapsulate all database access within a helper function\nthat can be called with <code class=\"docutils literal notranslate\">sync_to_async()</code> without relying on the connection\nobject in the calling code.</p>\n</section>\n</section>","rootId":"asynchronous-support","toc":[{"title":"异步视图","anchor":"async-views","children":[{"title":"Queries & the ORM","anchor":"queries-the-orm","children":[]},{"title":"性能","anchor":"performance","children":[]}]},{"title":"异步安全","anchor":"async-safety","children":[]},{"title":"异步适配函数","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":"/zh-hans/4.1/topics/"}],"prev":{"docname":"topics/external-packages","title":"扩展包","url":"/zh-hans/4.1/topics/external-packages/"},"next":{"docname":"howto/index","title":"操作指南","url":"/zh-hans/4.1/howto/"},"formats":{"html":"/zh-hans/4.1/topics/async/","markdown":"/zh-hans/4.1/topics/async.md","json":"/zh-hans/4.1/topics/async.json"},"source":"https://github.com/django/django/blob/stable/4.1.x/docs/topics/async.txt","official":"https://docs.djangoproject.com/zh-hans/4.1/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","it","pt-br","ko","es","el","pl"]}