{"title":"Dukungan asinkronus","version":"3.0","locale":"id","docname":"topics/async","url":"/id/3.0/topics/async/","canonical":"https://djangodocs.dev/id/3.0/topics/async/","summary":"New in Django 3.0 Django has developing support for asynchronous (\"async\") Python, but does not yet support asynchronous views or middleware; they will be coming in…","html":"<h1>Dukungan asinkronus<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\">\n<p class=\"version-note-title\">New in Django 3.0</p></aside>\n<p>Django has developing support for asynchronous (&quot;async&quot;) Python, but does not\nyet support asynchronous views or middleware; they will be coming in a future\nrelease.</p>\n<p>There is limited support for other parts of the async ecosystem; namely, Django\ncan natively talk <a class=\"reference internal\" href=\"/id/3.0/howto/deployment/asgi/\"><span class=\"doc\">ASGI</span></a>, and some async\nsafety support.</p>\n<section id=\"async-safety\">\n<span id=\"id1\"></span><h2>Async-safety<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>Certain key parts of Django are not able to operate safely in an asynchronous\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 asynchronous environment. The ORM is the main example, but there are other\nparts that are also protected in this way.</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=\"/id/3.0/ref/exceptions/#django.core.exceptions.SynchronousOnlyOperation\" title=\"django.core.exceptions.SynchronousOnlyOperation\"><code class=\"xref py py-exc docutils literal notranslate\"><span class=\"pre\">SynchronousOnlyOperation</span></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\"><span class=\"pre\">sync_to_async()</span></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\"><span class=\"pre\">asgiref.sync.sync_to_async()</span></code></a>, or any other preferred way of running\nsynchronous code in its own thread.</p>\n<p>If you are <em>absolutely</em> in dire need to run this code from an asynchronous\ncontext - for example, it is being forced on you by an external environment,\nand you are sure there is no chance of it being run concurrently (e.g. you are\nin a <a class=\"reference external\" href=\"https://jupyter.org/\">Jupyter</a> notebook), then you can disable the warning with the\n<code class=\"docutils literal notranslate\"><span class=\"pre\">DJANGO_ALLOW_ASYNC_UNSAFE</span></code> environment variable.</p>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">Peringatan</p>\n<p>If you enable this option and there is concurrent access to the\nasync-unsafe parts of Django, you may suffer data loss or corruption. Be\nvery careful and do not use this in production environments.</p>\n</aside>\n<p>Jika anda buth melakukan ini dari dalam Python, lakukan dengan <code class=\"docutils literal notranslate\"><span class=\"pre\">os.environ</span></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=\"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>fungsi  adaptasi asingkronus<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\"><span class=\"pre\">asgiref.sync</span></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\"><span class=\"pre\">async_to_sync()</span></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\"><span class=\"pre\">sync_to_async()</span></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\"><span class=\"pre\">pip</span></code>.</p>\n<section id=\"async-to-sync\">\n<h3><code class=\"docutils literal notranslate\"><span class=\"pre\">async_to_sync()</span></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\"><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>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=\"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<span class=\"n\">sync_function</span> <span class=\"o\">=</span> <span class=\"n\">async_to_sync</span><span class=\"p\">(</span><span class=\"n\">async_function</span><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=\"w\"> </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\"><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=\"(di Python v3.14)\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">asyncio.run()</span></code></a> function available in Python's standard library. As well\nas ensuring threadlocals 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.</p>\n</section>\n<section id=\"sync-to-async\">\n<h3><code class=\"docutils literal notranslate\"><span class=\"pre\">sync_to_async()</span></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\"><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\">False</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>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=\"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>\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<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><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\"><span class=\"pre\">sync_to_async()</span></code></a> has two threading modes:</p>\n<ul class=\"simple\">\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">thread_sensitive=False</span></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\"><span class=\"pre\">thread_sensitive=True</span></code>: the synchronous function will run in the same\nthread as all other <code class=\"docutils literal notranslate\"><span class=\"pre\">thread_sensitive</span></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\"><span class=\"pre\">async_to_sync()</span></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\"><span class=\"pre\">async_to_sync()</span></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\"><span class=\"pre\">asyncio.run()</span></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":"Async-safety","anchor":"async-safety","children":[]},{"title":"fungsi  adaptasi asingkronus","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":"Menggunakan Django","url":"/id/3.0/topics/"}],"prev":{"docname":"topics/external-packages","title":"Paket eksternal","url":"/id/3.0/topics/external-packages/"},"next":{"docname":"howto/index","title":"Panduan \"Bagaimana\"","url":"/id/3.0/howto/"},"formats":{"html":"/id/3.0/topics/async/","markdown":"/id/3.0/topics/async.md","json":"/id/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/id/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"]}