{"title":"Tacaíocht asincrónach","version":"6.1","locale":"ga","docname":"topics/async","url":"/ga/6.1/topics/async/","canonical":"https://djangodocs.dev/ga/6.1/topics/async/","summary":"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…","html":"<h1>Tacaíocht asincrónach<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 has support for writing asynchronous (&quot;async&quot;) views, along with an\nentirely async-enabled request stack if you are running under <a class=\"reference internal\" href=\"/ga/6.1/howto/deployment/asgi/\"><span class=\"doc\">ASGI</span></a>. Async views will still work under WSGI, but\nwith a small per-request adaptation cost (see <a class=\"reference internal\" href=\"#async-performance\"><span class=\"std std-ref\">feidhmíocht</span></a>), and\nwithout the ability to have efficient long-running requests.</p>\n<p>Many parts of Django provide asynchronous APIs, including <a class=\"reference internal\" href=\"/ga/6.1/topics/db/queries/#async-queries\"><span class=\"std std-ref\">the ORM</span></a>, the cache framework, authentication, sessions, and signals.\nFor other code, the <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\"><span class=\"pre\">sync_to_async()</span></code></a> adapter is a low-cost bridge (see\n<a class=\"reference internal\" href=\"#async-performance\"><span class=\"std std-ref\">feidhmíocht</span></a>). A wide range of async-native Python libraries can\nalso be integrated.</p>\n<section id=\"async-views\">\n<h2>Tuairimí async<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>Is féidir aon radharc a dhearbhú async tríd an gcuid inghlaonta de coroutine a thabhairt ar ais - go coitianta, déantar é seo ag baint úsáide as <code class=\"docutils literal notranslate\"><span class=\"pre\">async</span> <span class=\"pre\">def</span></code>. Maidir le dearcadh bunaithe ar fheidhm, ciallaíonn sé seo an dearcadh iomlán a dhearbhú ag baint úsáide as <code class=\"docutils literal notranslate\"><span class=\"pre\">async</span> <span class=\"pre\">def</span></code>. Maidir le dearcadh rang-bhunaithe, ciallaíonn sé seo láimhseálaithe modh HTTP a dhearbhú, mar shampla <code class=\"docutils literal notranslate\"><span class=\"pre\">get</span> <span class=\"pre\">()</span> <span class=\"pre\">``agus</span> <span class=\"pre\">``post</span> <span class=\"pre\">()</span></code> mar async def` (ní a <code class=\"docutils literal notranslate\"><span class=\"pre\">__init__</span> <span class=\"pre\">()</span> <span class=\"pre\">``,</span> <span class=\"pre\">nó</span> <span class=\"pre\">``as_view</span> <span class=\"pre\">()</span></code>).</p>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">Note</p>\n<p>Django uses <code class=\"docutils literal notranslate\"><span class=\"pre\">inspect.iscoroutinefunction</span></code> to test if your view is\nasynchronous or not. If you implement your own method of returning a\ncoroutine, ensure you use <code class=\"docutils literal notranslate\"><span class=\"pre\">inspect.markcoroutinefunction</span></code> so this\nfunction returns <code class=\"docutils literal notranslate\"><span class=\"pre\">True</span></code>.</p>\n</aside>\n<p>Faoi fhreastalaí WSGI, reáchtálfaidh tuairimí async ina lúb imeachta aonuaire féin. Ciallaíonn sé seo gur féidir leat gnéithe async a úsáid, cosúil le hiarratais HTTP async comhthráthacha, gan aon cheisteanna, ach ní gheobhaidh tú na buntáistí a bhaineann le cruach async.</p>\n<p>Is iad na príomhbhuntáistí an cumas na céadta naisc a sheirbheáil gan snáitheanna Python a úsáid. Ligeann sé seo duit sruthú mall, vótaíocht fhada, agus cineálacha freagartha spreagúla eile a úsáid.</p>\n<p>Más mian leat iad seo a úsáid, beidh ort Django a úsáid ag baint úsáidea:doc: ASGI ina ionad &lt;/howto/deployment/asgi/index&gt;.</p>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">Note</p>\n<p>A fully asynchronous request stack requires async middleware end-to-end.\nWhere a piece of synchronous middleware sits between an ASGI server and an\nasync view, Django adapts it by running it in its own thread; see\n<a class=\"reference internal\" href=\"#async-performance\"><span class=\"std std-ref\">feidhmíocht</span></a> for the cost trade-off.</p>\n<p>Django's bundled middleware supports both <a class=\"reference internal\" href=\"/ga/6.1/topics/http/middleware/#async-middleware\"><span class=\"std std-ref\">sync and async</span></a>. Third-party middleware may not. To see which\nmiddleware Django adapts, turn on debug logging for the <code class=\"docutils literal notranslate\"><span class=\"pre\">django.request</span></code>\nlogger and look for log messages about <em>&quot;Asynchronous handler adapted for\nmiddleware ...&quot;</em>.</p>\n</aside>\n<p>I mód ASGI agus WSGI araon, is féidir leat tacaíocht asincrónach a úsáid go sábháilte fós chun cód a reáchtáil ag an am céanna seachas go sraitheach. Tá sé seo áisiúil go háirithe agus tú ag déileáil le APIs seachtracha nó stórais sonraí.</p>\n<p>Más mian leat glaoch ar chuid de Django atá fós sioncrónach, beidh ort é a fhilleadh i nglao a:func: sync_to_async. Mar shampla:</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=\"w\"> </span><span class=\"nn\">asgiref.sync</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">sync_to_async</span>\n\n<span class=\"n\">results</span> <span class=\"o\">=</span> <span class=\"k\">await</span> <span class=\"n\">sync_to_async</span><span class=\"p\">(</span><span class=\"n\">sync_function</span><span class=\"p\">,</span> <span class=\"n\">thread_sensitive</span><span class=\"o\">=</span><span class=\"kc\">True</span><span class=\"p\">)(</span><span class=\"n\">pk</span><span class=\"o\">=</span><span class=\"mi\">123</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>&lt;async-safety&gt;Má dhéanann tú iarracht de thaisme glaoch ar chuid de Django atá sioncrónach amháin ó radharc async, spreagfaidh tú Django's:ref: <a href=\"#id1\"><span class=\"problematic\" id=\"id2\">`</span></a>cosaint sábháilteachta asincrónach <a href=\"#id3\"><span class=\"problematic\" id=\"id4\">`</span></a>chun do chuid sonraí a chosaint ar éilliú.</p>\n<section id=\"decorators\">\n<h3>Maisitheoirí<a class=\"heading-anchor\" href=\"#decorators\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Is féidir na maisitheoirí seo a leanas a úsáid le feidhmeanna amharc sioncrónach agus asincrónach araon:</p>\n<ul class=\"simple\">\n<li><p><a class=\"reference internal\" href=\"/ga/6.1/topics/http/decorators/#django.views.decorators.cache.cache_control\" title=\"django.views.decorators.cache.cache_control\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">cache_control()</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ga/6.1/topics/http/decorators/#django.views.decorators.cache.never_cache\" title=\"django.views.decorators.cache.never_cache\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">never_cache()</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ga/6.1/topics/http/decorators/#django.views.decorators.common.no_append_slash\" title=\"django.views.decorators.common.no_append_slash\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">no_append_slash()</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ga/6.1/ref/csp/#django.views.decorators.csp.csp_override\" title=\"django.views.decorators.csp.csp_override\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">csp_override()</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ga/6.1/ref/csp/#django.views.decorators.csp.csp_report_only_override\" title=\"django.views.decorators.csp.csp_report_only_override\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">csp_report_only_override()</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ga/6.1/ref/csrf/#django.views.decorators.csrf.csrf_exempt\" title=\"django.views.decorators.csrf.csrf_exempt\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">csrf_exempt()</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ga/6.1/ref/csrf/#django.views.decorators.csrf.csrf_protect\" title=\"django.views.decorators.csrf.csrf_protect\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">csrf_protect()</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ga/6.1/ref/csrf/#django.views.decorators.csrf.ensure_csrf_cookie\" title=\"django.views.decorators.csrf.ensure_csrf_cookie\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">ensure_csrf_cookie()</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ga/6.1/ref/csrf/#django.views.decorators.csrf.requires_csrf_token\" title=\"django.views.decorators.csrf.requires_csrf_token\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">requires_csrf_token()</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ga/6.1/howto/error-reporting/#django.views.decorators.debug.sensitive_variables\" title=\"django.views.decorators.debug.sensitive_variables\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">sensitive_variables()</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ga/6.1/howto/error-reporting/#django.views.decorators.debug.sensitive_post_parameters\" title=\"django.views.decorators.debug.sensitive_post_parameters\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">sensitive_post_parameters()</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ga/6.1/topics/http/decorators/#django.views.decorators.gzip.gzip_page\" title=\"django.views.decorators.gzip.gzip_page\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">gzip_page()</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ga/6.1/topics/http/decorators/#django.views.decorators.http.condition\" title=\"django.views.decorators.http.condition\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">condition()</span></code></a></p></li>\n<li><p><a href=\"#id1\"><span class=\"problematic\" id=\"id2\">``</span></a>leathanach_coinníollacha () ``</p></li>\n<li><p><a class=\"reference internal\" href=\"/ga/6.1/topics/http/decorators/#django.views.decorators.http.etag\" title=\"django.views.decorators.http.etag\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">etag()</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ga/6.1/topics/http/decorators/#django.views.decorators.http.last_modified\" title=\"django.views.decorators.http.last_modified\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">last_modified()</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ga/6.1/topics/http/decorators/#django.views.decorators.http.require_http_methods\" title=\"django.views.decorators.http.require_http_methods\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">require_http_methods()</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ga/6.1/topics/http/decorators/#django.views.decorators.http.require_GET\" title=\"django.views.decorators.http.require_GET\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">require_GET()</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ga/6.1/topics/http/decorators/#django.views.decorators.http.require_POST\" title=\"django.views.decorators.http.require_POST\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">require_POST()</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ga/6.1/topics/http/decorators/#django.views.decorators.http.require_safe\" title=\"django.views.decorators.http.require_safe\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">require_safe()</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ga/6.1/topics/http/decorators/#django.views.decorators.vary.vary_on_cookie\" title=\"django.views.decorators.vary.vary_on_cookie\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">vary_on_cookie()</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/ga/6.1/topics/http/decorators/#django.views.decorators.vary.vary_on_headers\" title=\"django.views.decorators.vary.vary_on_headers\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">vary_on_headers()</span></code></a></p></li>\n<li><p><a href=\"#id1\"><span class=\"problematic\" id=\"id2\">``</span></a>xframe_options_deny () ``</p></li>\n<li><p><a href=\"#id1\"><span class=\"problematic\" id=\"id2\">``</span></a>xframe_options_sameorigin () ``</p></li>\n<li><p><a href=\"#id1\"><span class=\"problematic\" id=\"id2\">``</span></a>xframe_options_díolmhaithe () ``</p></li>\n</ul>\n<p>Mar shampla:</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=\"w\"> </span><span class=\"nn\">django.views.decorators.cache</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">never_cache</span>\n\n\n<span class=\"nd\">@never_cache</span>\n<span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">my_sync_view</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">):</span> <span class=\"o\">...</span>\n\n\n<span class=\"nd\">@never_cache</span>\n<span class=\"k\">async</span> <span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">my_async_view</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">):</span> <span class=\"o\">...</span>\n</code></pre></div>\n<p><a class=\"reference internal\" href=\"/ga/6.1/ref/utils/#django.utils.decorators.method_decorator\" title=\"django.utils.decorators.method_decorator\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">method_decorator()</span></code></a> can be used with asynchronous\nmethods, including <code class=\"docutils literal notranslate\"><span class=\"pre\">async</span> <span class=\"pre\">def</span></code> view handlers. Note, though, that if\ndecorating <a class=\"reference internal\" href=\"/ga/6.1/ref/class-based-views/base/#django.views.generic.base.View.dispatch\" title=\"django.views.generic.base.View.dispatch\"><code class=\"xref py py-meth docutils literal notranslate\"><span class=\"pre\">dispatch()</span></code></a> on a <code class=\"docutils literal notranslate\"><span class=\"pre\">View</span></code> with\nasynchronous handlers, you will need to override <code class=\"docutils literal notranslate\"><span class=\"pre\">dispatch</span></code> to make it\n<code class=\"docutils literal notranslate\"><span class=\"pre\">async</span> <span class=\"pre\">def</span></code> 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\">class</span><span class=\"w\"> </span><span class=\"nc\">MyClass</span><span class=\"p\">(</span><span class=\"n\">View</span><span class=\"p\">):</span>\n    <span class=\"nd\">@method_decorator</span><span class=\"p\">(</span><span class=\"n\">never_cache</span><span class=\"p\">)</span>\n    <span class=\"k\">async</span> <span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">dispatch</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"o\">*</span><span class=\"n\">args</span><span class=\"p\">,</span> <span class=\"o\">**</span><span class=\"n\">kwargs</span><span class=\"p\">):</span>\n        <span class=\"k\">return</span> <span class=\"nb\">super</span><span class=\"p\">()</span><span class=\"o\">.</span><span class=\"n\">dispatch</span><span class=\"p\">(</span><span class=\"o\">*</span><span class=\"n\">args</span><span class=\"p\">,</span> <span class=\"o\">**</span><span class=\"n\">kwargs</span><span class=\"p\">)</span>\n\n    <span class=\"k\">async</span> <span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">get</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">request</span><span class=\"p\">):</span> <span class=\"o\">...</span>\n\n    <span class=\"k\">async</span> <span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">post</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">request</span><span class=\"p\">):</span> <span class=\"o\">...</span>\n</code></pre></div>\n<p>Here, because we are decorating <code class=\"docutils literal notranslate\"><span class=\"pre\">dispatch</span></code>, rather than the individual\nhandler methods, we need to make <code class=\"docutils literal notranslate\"><span class=\"pre\">dispatch</span></code> asynchronous so that\n<code class=\"docutils literal notranslate\"><span class=\"pre\">method_decorator</span></code> can correctly mark the resulting method as a coroutine\nfunction.</p>\n</section>\n<section id=\"queries-the-orm\">\n<h3>Fiosrúcháin &amp; an 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<p>With some exceptions, Django can run ORM queries asynchronously:</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> <span class=\"n\">author</span> <span class=\"ow\">in</span> <span class=\"n\">Author</span><span class=\"o\">.</span><span class=\"n\">objects</span><span class=\"o\">.</span><span class=\"n\">filter</span><span class=\"p\">(</span><span class=\"n\">name__startswith</span><span class=\"o\">=</span><span class=\"s2\">&quot;A&quot;</span><span class=\"p\">):</span>\n    <span class=\"n\">book</span> <span class=\"o\">=</span> <span class=\"k\">await</span> <span class=\"n\">author</span><span class=\"o\">.</span><span class=\"n\">books</span><span class=\"o\">.</span><span class=\"n\">afirst</span><span class=\"p\">()</span>\n</code></pre></div>\n<p>Is féidir nótaí mionsonraithe a fháil in:ref: async-queries, ach i mbeagán focal:</p>\n<ul class=\"simple\">\n<li><p>Tá leagan asincrónach réamhshocraithe ag gach modh <code class=\"docutils literal notranslate\"><span class=\"pre\">QuerySet</span></code> a fhágann go dtarlóidh ceist SQL.</p></li>\n<li><p>Tacaítear le <code class=\"docutils literal notranslate\"><span class=\"pre\">async</span> <span class=\"pre\">for</span></code> ar gach cearrSets (lena n-áirítear aschur <code class=\"docutils literal notranslate\"><span class=\"pre\">luachanna</span> <span class=\"pre\">()</span> <span class=\"pre\">``agus</span> <span class=\"pre\">``values_list</span> <span class=\"pre\">()</span></code>.)</p></li>\n</ul>\n<p>Asynchronous model methods that use the database are also supported:</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\">def</span><span class=\"w\"> </span><span class=\"nf\">make_book</span><span class=\"p\">(</span><span class=\"o\">*</span><span class=\"n\">args</span><span class=\"p\">,</span> <span class=\"o\">**</span><span class=\"n\">kwargs</span><span class=\"p\">):</span>\n    <span class=\"n\">book</span> <span class=\"o\">=</span> <span class=\"n\">Book</span><span class=\"p\">(</span><span class=\"o\">...</span><span class=\"p\">)</span>\n    <span class=\"k\">await</span> <span class=\"n\">book</span><span class=\"o\">.</span><span class=\"n\">asave</span><span class=\"p\">(</span><span class=\"n\">using</span><span class=\"o\">=</span><span class=\"s2\">&quot;secondary&quot;</span><span class=\"p\">)</span>\n\n\n<span class=\"k\">async</span> <span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">make_book_with_tags</span><span class=\"p\">(</span><span class=\"n\">tags</span><span class=\"p\">,</span> <span class=\"o\">*</span><span class=\"n\">args</span><span class=\"p\">,</span> <span class=\"o\">**</span><span class=\"n\">kwargs</span><span class=\"p\">):</span>\n    <span class=\"n\">book</span> <span class=\"o\">=</span> <span class=\"k\">await</span> <span class=\"n\">Book</span><span class=\"o\">.</span><span class=\"n\">objects</span><span class=\"o\">.</span><span class=\"n\">acreate</span><span class=\"p\">(</span><span class=\"o\">...</span><span class=\"p\">)</span>\n    <span class=\"k\">await</span> <span class=\"n\">book</span><span class=\"o\">.</span><span class=\"n\">tags</span><span class=\"o\">.</span><span class=\"n\">aset</span><span class=\"p\">(</span><span class=\"n\">tags</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>Ní oibríonn idirbhearta fós i mód async. Má tá píosa cód agat a dteastaíonn iompar idirbhearta uaidh, molaimid duit an píosa sin a scríobh mar fheidhm sioncrónach amháin agus glaoch air ag baint úsáid:func: sync_to_async.</p>\n<p><a class=\"reference internal\" href=\"/ga/6.1/ref/databases/#persistent-database-connections\"><span class=\"std std-ref\">Persistent database connections</span></a>, set\nvia the <a class=\"reference internal\" href=\"/ga/6.1/ref/settings/#std-setting-CONN_MAX_AGE\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CONN_MAX_AGE</span></code></a> setting, should also be disabled in async mode.\nInstead, use your database backend's built-in connection pooling if available,\nor investigate a third-party connection pooling option if required. As in\nsynchronous Django, concurrent requests in a single process share that pool, so\nsize it to the target in-flight query concurrency.</p>\n</section>\n<section id=\"performance\">\n<span id=\"async-performance\"></span><h3>feidhmíocht<a class=\"heading-anchor\" href=\"#performance\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>When running in a mode that does not match the view (e.g. an async view under\nWSGI, or a traditional sync view under ASGI), Django must emulate the other\ncall style to allow your code to run. The per-call cost of this adaptation is\nsmall: tens of microseconds in the in-request ASGI path, where the running\nevent loop is reused, and a few hundred microseconds in the cold-start path\nused by management commands, background tasks, and scripts. Against typical\nrequest times measured in milliseconds, this is rarely visible in itself, but\ncan become so under GIL contention as the number of active threads grows.</p>\n<p>If you find yourself wrapping individual rows or operations in a tight loop,\nrestructure your code so the loop runs inside a single <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\"><span class=\"pre\">sync_to_async()</span></code></a>\n(or <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\"><span class=\"pre\">async_to_sync()</span></code></a>) crossing. The per-call cost of the context switch is\nthen spread across the whole loop and effectively disappears.</p>\n<p>The same per-call adaptation cost applies to middleware. Django will attempt to\nminimize the number of context-switches between sync and async. If you have an\nASGI server, but all your middleware and views are synchronous, it will switch\njust once, before it enters the middleware stack.</p>\n<p>However, if you put synchronous middleware between an ASGI server and an\nasynchronous view, it will have to switch into sync mode for the middleware and\nthen back to async mode for the view. Django will also hold the sync thread\nopen for middleware exception propagation. For request/response views that hit\nthe ORM and return, this is not usually a meaningful penalty. It matters most\nwhen you are using ASGI for high in-process concurrency over non-ORM I/O (for\nexample upstream HTTP fan-out, server-sent events, or other long-lived\nrequests), where the extra thread per request caps that concurrency.</p>\n<p>Ba chóir duit do thástáil feidhmíochta féin a dhéanamh chun a fháil amach cén éifeacht atá ag ASGI i gcoinne WSGI ar do chód. I roinnt cásanna, d'fhéadfadh go mbeadh méadú feidhmíochta ann fiú le haghaidh bunachar cóid sioncrónach amháin faoi ASGI toisc go bhfuil an cód láimhseála iarratais fós ag rith go gascrónach. Go ginearálta ní bheidh tú ag iarraidh modh ASGI a chumasú ach má tá cód asincrónach agat i do thionscadal.</p>\n</section>\n<section id=\"handling-disconnects\">\n<span id=\"async-handling-disconnect\"></span><h3>Dícheangail láimhseáil<a class=\"heading-anchor\" href=\"#handling-disconnects\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Maidir le hiarratais fadré, féadfaidh cliant a dhícheangal sula dtugann an radharc freagra ar ais. Sa chás seo, ardófar <code class=\"docutils literal notranslate\"><span class=\"pre\">Asyncio.CancelleDerror</span></code> sa radharc. Is féidir leat an earráid seo a ghabháil agus é a láimhseáil más gá duit aon ghlanadh a dhéanamh:</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\">def</span><span class=\"w\"> </span><span class=\"nf\">my_view</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">):</span>\n    <span class=\"k\">try</span><span class=\"p\">:</span>\n        <span class=\"c1\"># Do some work</span>\n        <span class=\"o\">...</span>\n    <span class=\"k\">except</span> <span class=\"n\">asyncio</span><span class=\"o\">.</span><span class=\"n\">CancelledError</span><span class=\"p\">:</span>\n        <span class=\"c1\"># Handle disconnect</span>\n        <span class=\"k\">raise</span>\n</code></pre></div>\n<p>&lt;request-response-streaming-disconnect&gt;Is féidir leat freis:ref: <a href=\"#id1\"><span class=\"problematic\" id=\"id2\">`</span></a>dícheangail cliant a láimhseáil i bhfreagraí sruthú <a href=\"#id3\"><span class=\"problematic\" id=\"id4\">`</span></a>.</p>\n</section>\n</section>\n<section id=\"async-safety\">\n<span id=\"id1\"></span><h2>Sábháilteacht async<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\"><span class=\"pre\">DJANGO_ALLOW_ASYNC_UNSAFE</span></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>Certain key parts of Django are not able to operate safely in an async\nenvironment, as they have global state that is not coroutine-aware. These parts\nof Django are classified as &quot;async-unsafe&quot;, and are protected from execution in\nan async environment. The synchronous API of the ORM is the main example, but\nthere are other parts that are also protected in this way.</p>\n<p>Má dhéanann tú iarracht aon cheann de na codanna seo a reáchtáil ó snáithe ina bhfuil lúb imeachta reath* ann, gheobhaidh tú:: exc: ~Django.Core.Exceptions.SynchronousOnlyOperation earráid. Tabhair faoi deara nach gá duit a bheith taobh istigh de fheidhm async go díreach chun an earráid seo a tharlóidh. Má ghlaoigh tú feidhm sioncrónaithe go díreach ó fheidhm async, gan úsáid: func: sync_to_async nó den chineál céanna, ansin is féidir leis tarlú freisin. Tá sé seo toisc go bhfuil do chód fós ag rith i snáithe le lúb imeachta gníomhach, cé nach bhféadfar é a dhearbhú mar chód async.</p>\n<p>Má thagann tú ar an earráid seo, ba cheart duit do chód a shocrú chun gan an cód ciontach a ghlaoch ó chomhthéacs async. Ina áit sin, scríobh do chód a labhraíonn le feidhmeanna async-neamhshábháilte ina fheidhm sioncrónaithe féin, agus glaoigh air sin ag baint úsáid:func: asgiref.sync.sync_to_async (nó aon bhealach eile chun cód sioncrónaithe a reáchtáil ina snáithe féin).</p>\n<p>Is féidir leis an timpeallacht ina bhfuil do chód Django á reáchtáil agat an comhthéacs async a fhorchur ort. Mar shampla, soláthraíonn leabhair nótaí <a class=\"reference external\" href=\"https://jupyter.org/\">Jupyter</a> agus sliogáin idirghníomhacha <a class=\"reference external\" href=\"https://ipython.org\">iPython</a> lúb imeachta gníomhach go trédhearcach ionas go mbeidh sé níos éasca idirghníomhú le APIs asincrónacha.</p>\n<p>Má tá blaosc IPython á úsáid agat, is féidir leat an lúb imeachta seo a dhíchumasú trí rith:</p>\n<div class=\"code-block\" data-language=\"shell\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</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=\"Shell code\"><code>%autoawait<span class=\"w\"> </span>off\n</code></pre></div>\n<p>mar ordú ag an iPython pras. Ligfidh sé seo duit cód sioncrónach a reáchtáil gan earráidí: exc: ~django.core.exceptions.synchronousOnlyOperation a ghiniúint; áfach, ní bheidh tú in ann APIs asincrónacha <code class=\"docutils literal notranslate\"><span class=\"pre\">feith</span></code> a dhéanamh freisin. Chun lúb an imeachta a chasadh ar ais, rith:</p>\n<div class=\"code-block\" data-language=\"shell\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</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=\"Shell code\"><code>%autoawait<span class=\"w\"> </span>on\n</code></pre></div>\n<p>Má tá tú i dtimpeallacht seachas IPython (nó mura féidir leat <a href=\"#id1\"><span class=\"problematic\" id=\"id2\">``</span></a>autowait <a href=\"#id3\"><span class=\"problematic\" id=\"id4\">``</span></a>a mhúchadh i iPython ar chúis éigin), tá tú cinnte* nach bhfuil aon seans ann go ndéanfar do chód a reáchtáil ag an am céanna, agus ní mór duit <em>go hiomlán</em> do chód sioncrónaithe a reáchtáil ó chomhthéacs async, ansin is féidir leat an rabhadh a dhíchumasú trí:envvar: DJANGO_ALLOW_ASYNC_UNEAFE_ASYNC_UN comhshaoil athraitheach go luach ar bith.</p>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">Warning</p>\n<p>Má chumasaíonn tú an rogha seo agus má tá rochtain chomhthráthach ann ar na codanna asínc-neamhshábháilte de Django, d'fhéadfadh caillteanas sonraí nó éilliú a bheith ort. Bí an-chúramach agus ná húsáid é seo i dtimpeallachtaí táirgeachta.</p>\n</aside>\n<p>Más gá duit é seo a dhéanamh ó laistigh de Python, déan é sin le os.environment `:</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=\"w\"> </span><span class=\"nn\">os</span>\n\n<span class=\"n\">os</span><span class=\"o\">.</span><span class=\"n\">environ</span><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>Feidhmeanna cuibheoir async<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>Is gá an stíl ghlaonna a oiriúnú agus tú ag glaoch ar chód sioncrónaithe ó chomhthéacs async, nó a mhalairt. Chuige seo tá dhá fheidhm oiriúnaitheora ann, ón modúl <code class=\"docutils literal notranslate\"><span class=\"pre\">asgiref.sync</span></code>: :func: async_to_sync agus:func: sync_to_async. Úsáidtear iad chun aistriú idir na stíleanna glaonna agus comhoiriúnacht á chaomhnú.</p>\n<p>Úsáidtear na feidhmeanna cuibheora seo go forleathan i Django. Tá an pacáiste: pypi: asgiref féin mar chuid de thionscadal Django, agus suiteáiltear é go huathoibríoch mar spleáchas nuair a shuiteálann tú Django le <code class=\"docutils literal notranslate\"><span class=\"pre\">pip</span></code>.</p>\n<section id=\"async-to-sync\">\n<h3><a href=\"#id1\"><span class=\"problematic\" id=\"id2\">``</span></a>async_to_sync () ``<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\"><span class=\"pre\">async_to_sync</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">async_function</span></span></em>, <em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">force_new_loop</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">False</span></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>Glacann sé feidhm async agus filleann sé feidhm sioncrónaithe a fhilleann é. Is féidir é a úsáid mar fhilleadh díreach nó mar mhaisitheoir:</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=\"w\"> </span><span class=\"nn\">asgiref.sync</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">async_to_sync</span>\n\n\n<span class=\"k\">async</span> <span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">get_data</span><span class=\"p\">():</span> <span class=\"o\">...</span>\n\n\n<span class=\"n\">sync_get_data</span> <span class=\"o\">=</span> <span class=\"n\">async_to_sync</span><span class=\"p\">(</span><span class=\"n\">get_data</span><span class=\"p\">)</span>\n\n\n<span class=\"nd\">@async_to_sync</span>\n<span class=\"k\">async</span> <span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">get_other_data</span><span class=\"p\">():</span> <span class=\"o\">...</span>\n</code></pre></div>\n<p>Reáchtáiltear an fheidhm async sa lúb imeachta don snáithe reatha, má tá ceann i láthair. Mura bhfuil lúb imeachta reatha ann, déantar lúb imeachta nua a chasadh suas go sonrach don iontráil async aonair agus dúnadh síos arís nuair a bheidh sé críochnaithe. I gceachtar cás, déanfaidh an fheidhm async a fhorghníomhú ar snáithe difriúil leis an gcód glaonna.</p>\n<p>Caomhnaítear luachanna snáithe agus comhthéacsúla thar an teorainn sa dá threo.</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\"><span class=\"pre\">async_to_sync()</span></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\"><span class=\"pre\">asyncio.run()</span></code></a> function in Python's standard library. As well as ensuring\nthreadlocals work, it also enables the <code class=\"docutils literal notranslate\"><span class=\"pre\">thread_sensitive</span></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\"><span class=\"pre\">sync_to_async()</span></code></a> when that wrapper is used below it. In the cold path\n(no running event loop) it pays the cost of starting a fresh event loop, like\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\"><span class=\"pre\">asyncio.run()</span></code></a>; when an event loop is already running (the in-request ASGI\ncase), the running loop is reused and the cost drops accordingly.</p>\n</section>\n<section id=\"sync-to-async\">\n<h3><a href=\"#id1\"><span class=\"problematic\" id=\"id2\">``</span></a>sync_to_async () ``<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\"><span class=\"pre\">sync_to_async</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">sync_function</span></span></em>, <em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">thread_sensitive</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">True</span></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>Glacann sé feidhm sioncrónaithe agus filleann sé feidhm async a fhilleann é. Is féidir é a úsáid mar fhilleadh díreach nó mar mhaisitheoir:</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=\"w\"> </span><span class=\"nn\">asgiref.sync</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">sync_to_async</span>\n\n<span class=\"n\">async_function</span> <span class=\"o\">=</span> <span class=\"n\">sync_to_async</span><span class=\"p\">(</span><span class=\"n\">sync_function</span><span class=\"p\">,</span> <span class=\"n\">thread_sensitive</span><span class=\"o\">=</span><span class=\"kc\">False</span><span class=\"p\">)</span>\n<span class=\"n\">async_function</span> <span class=\"o\">=</span> <span class=\"n\">sync_to_async</span><span class=\"p\">(</span><span class=\"n\">sensitive_sync_function</span><span class=\"p\">,</span> <span class=\"n\">thread_sensitive</span><span class=\"o\">=</span><span class=\"kc\">True</span><span class=\"p\">)</span>\n\n\n<span class=\"nd\">@sync_to_async</span>\n<span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">sync_function</span><span class=\"p\">():</span> <span class=\"o\">...</span>\n</code></pre></div>\n<p>Caomhnaítear luachanna snáithe agus comhthéacsúla thar an teorainn sa dá threo.</p>\n<p>Is gnách go scríobhtar feidhmeanna sioncrónaithe ag glacadh leis go ritheann siad go léir sa phríomhsnáithe, mar sin: func: tá dhá mhodh snáithe ag sync_to_async:</p>\n<ul class=\"simple\">\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">thread_sensitive=True</span></code> (an réamhshocraithe): rithfidh an fheidhm sioncrónaithe sa snáithe céanna le gach feidhm <code class=\"docutils literal notranslate\"><span class=\"pre\">thread_sensitive</span></code> eile. Is é seo an príomh-snáithe, má tá an príomh-snáithe sioncrónach agus má tá an fillteán: func: async_to_sync á úsáid agat.</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">thread_sensitive=False</span></code>: reáchtálfaidh an fheidhm sioncrónaithe i snáithe úrnua a dhúnadh ansin nuair a bheidh an t-ionghairm críochnaithe.</p></li>\n</ul>\n<p>Tá modh íogair do snáithe speisialta go leor, agus déanann sé go leor oibre chun gach feidhm a reáchtáil sa snáithe céanna. Tabhair faoi deara, áfach, go mbraitheann sé ar úsáid*: func: async_to_sync <em>os cionn é sa chrú</em> chun rudaí a reáchtáil i gceart ar an bpríomh-snáithe. Má úsáideann tú <a href=\"#id1\"><span class=\"problematic\" id=\"id2\">``</span></a>asyncio.run () <a href=\"#id3\"><span class=\"problematic\" id=\"id4\">``</span></a>nó dá leithéid, tiocfaidh sé ar ais ar fheidhmeanna íogair snáithe a reáchtáil i snáithe amháin, roinnte, ach ní hé seo an príomh-snáithe.</p>\n<p>Is é an fáth a bhfuil gá leis seo i Django ná go n-éilíonn go leor leabharlanna, go sonrach oiriúnaitheoirí bunachar sonraí, go ndéantar rochtain orthu sa snáithe céanna a cruthaíodh iad. Chomh maith leis sin glacann go leor de chód Django atá ann cheana go ritheann sé go léir sa snáithe céanna, m.sh. middleware ag cur rudaí le hiarratas lena n-úsáid níos déanaí i dtuairimí.</p>\n<p>Seachas saincheisteanna comhoiriúnachta féideartha a thabhairt isteach leis an gcód seo, roghnaíomar ina ionad sin an modh seo a chur leis ionas go rithfidh gach cód sioncrónaithe Django atá ann cheana sa snáithe céanna agus dá bhrí sin go mbeidh sé comhoiriúnach Tabhair faoi deara go mbeidh cód sioncrónaithe i snáith* difriol* i gcónaí le haon chód async atá ag glaoch air, mar sin ba cheart duit láimhseálacha bunachar sonraí amh nó tagairtí eile atá íogair do shnáithe a sheachaint timpeall.</p>\n<p>Within a single request, multiple <code class=\"docutils literal notranslate\"><span class=\"pre\">thread_sensitive</span></code> calls serialize on that\nrequest's worker thread, but each request gets its own per-context worker, so\nconcurrent requests do <em>not</em> serialize against each other. This mirrors\nDjango's connection-per-thread model, and the same constraint applies in other\nasync database libraries, where concurrent queries on a single connection\nserialize on a lock. To support more concurrent requests, increase the\nconnection pool size accordingly rather than disabling <code class=\"docutils literal notranslate\"><span class=\"pre\">thread_sensitive</span></code>.</p>\n<p>Go praiticiúil ciallaíonn an srian seo nár chóir duit gnéithe den réad bunachar sonraí nasc` a rith agus tú ag glaoch ar sync_to_async () `. Spreagfaidh sé sin na seiceálacha sábháilteachta snáithe:</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=\"w\"> </span><span class=\"nn\">asyncio</span>\n<span class=\"gp\">&gt;&gt;&gt; </span><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">asgiref.sync</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">sync_to_async</span>\n<span class=\"gp\">&gt;&gt;&gt; </span><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.db</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">connection</span>\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><span class=\"n\">connection</span><span class=\"o\">.</span><span class=\"n\">cursor</span><span class=\"p\">()</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> <span class=\"n\">sync_to_async</span><span class=\"p\">(</span><span class=\"n\">connection</span><span class=\"o\">.</span><span class=\"n\">cursor</span><span class=\"p\">)()</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>Ina ionad sin, ba cheart duit gach rochtain bunachar sonraí a chumhdú laistigh de fheidhm chúntóra ar féidir a ghlaoch le <a href=\"#id1\"><span class=\"problematic\" id=\"id2\">`</span></a>sync_to_async () <a href=\"#id3\"><span class=\"problematic\" id=\"id4\">`</span></a>gan brath ar an réad nasc sa chód glaonna.</p>\n</section>\n</section>","rootId":"asynchronous-support","toc":[{"title":"Tuairimí async","anchor":"async-views","children":[{"title":"Maisitheoirí","anchor":"decorators","children":[]},{"title":"Fiosrúcháin & an ORM","anchor":"queries-the-orm","children":[]},{"title":"feidhmíocht","anchor":"performance","children":[]},{"title":"Dícheangail láimhseáil","anchor":"handling-disconnects","children":[]}]},{"title":"Sábháilteacht async","anchor":"async-safety","children":[]},{"title":"Feidhmeanna cuibheoir async","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":"Using Django","url":"/ga/6.1/topics/"}],"prev":{"docname":"topics/checks","title":"Creat seiceála an chórais","url":"/ga/6.1/topics/checks/"},"next":{"docname":"topics/tasks","title":"Django's Tasks framework","url":"/ga/6.1/topics/tasks/"},"formats":{"html":"/ga/6.1/topics/async/","markdown":"/ga/6.1/topics/async.md","json":"/ga/6.1/topics/async.json"},"source":"https://github.com/django/django/blob/stable/6.1.x/docs/topics/async.txt","official":"https://docs.djangoproject.com/ga/6.1/topics/async/","inVersions":["6.1","6.0","5.2"],"inLocales":["en","sv","zh-hans","ga","fr","ja","id","it","pt-br","ko","es","el","pl"]}