如何让Django 3、channels和uvicorn协同工作
How to make Django 3, channels and uvicorn work together
我一直在尝试从 daphne 切换到 uvicorn 以使用 django 3 和频道进行生产。我在加载通道的经典 asgi 文件时遇到错误。由于对 django.setup 或 get_application 的同步调用,我无法使用它。我试图用 sync_to_async 调用来调整这个文件,但没有成功。有没有人设法让它发挥作用?
原版asgi.py
代码
import os
import django
from channels.routing import get_default_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
django.setup()
application = get_default_application()
堆栈跟踪
Traceback (most recent call last):
File "/usr/local/lib/python3.8/multiprocessing/process.py", line 315, in _bootstrap
self.run()
File "/usr/local/lib/python3.8/multiprocessing/process.py", line 108, in run
self._target(*self._args, **self._kwargs)
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/uvicorn/subprocess.py", line 61, in subprocess_started
target(sockets=sockets)
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/uvicorn/main.py", line 407, in run
loop.run_until_complete(self.serve(sockets=sockets))
File "/usr/local/lib/python3.8/asyncio/base_events.py", line 612, in run_until_complete
return future.result()
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/uvicorn/main.py", line 414, in serve
config.load()
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/uvicorn/config.py", line 300, in load
self.loaded_app = import_from_string(self.app)
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/uvicorn/importer.py", line 20, in import_from_string
module = importlib.import_module(module_str)
File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "./config/asgi.py", line 16, in <module>
django.setup()
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/django/apps/registry.py", line 122, in populate
app_config.ready()
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/django_prometheus/apps.py", line 23, in ready
ExportMigrations()
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/django_prometheus/migrations.py", line 52, in ExportMigrations
executor = MigrationExecutor(connections[alias])
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/django/db/migrations/executor.py", line 18, in __init__
self.loader = MigrationLoader(self.connection)
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/django/db/migrations/loader.py", line 49, in __init__
self.build_graph()
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/django/db/migrations/loader.py", line 212, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 76, in applied_migrations
if self.has_table():
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 56, in has_table
return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor())
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/django/utils/asyncio.py", line 24, in inner
raise SynchronousOnlyOperation(message)
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
已修改asgi.py
代码
import os
import django
from asgiref.sync import sync_to_async
from channels.routing import get_default_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
sync_to_async(django.setup, thread_sensitive=True)
application = sync_to_async(get_default_application, thread_sensitive=True)
堆栈跟踪
Traceback (most recent call last):
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/uvicorn/lifespan/on.py", line 55, in main
await app(scope, self.receive, self.send)
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
return await self.app(scope, receive, send)
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/asgiref/sync.py", line 296, in __call__
ret = await asyncio.wait_for(future, timeout=None)
File "/usr/local/lib/python3.8/asyncio/tasks.py", line 455, in wait_for
return await fut
File "/usr/local/lib/python3.8/concurrent/futures/thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/asgiref/sync.py", line 334, in thread_handler
return func(*args, **kwargs)
TypeError: get_default_application() takes 0 positional arguments but 3 were given
ERROR: Application startup failed. Exiting.
感谢大家阅读我的文章
- 根据这个 function
,您传递给 uvicorn 的可调用项将在事件循环中 运行
- 因为1.
django.setup()
需要转换成co-routine
get_default_application()
不应该是 运行 异步的,它会去 auto-magically return 路由器应用程序。 uvicorn应该指的就是这个。
django.setup()
必须 return 在主事件循环开始之前
鉴于这四点,您的代码应该如下:
import os
import django
from asgiref.sync import sync_to_async
from channels.routing import get_default_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
await sync_to_async(django.setup, thread_sensitive=True)()
application = get_default_application()
但是,在撰写本文时,您不能将 await 用作 top-level 指令,并且如果您将其删除,则无法保证设置会在模块解析之前完成(不会)。因此,如果您在启动应用程序之前有 运行 的同步代码,则不能使用 uvicorn 的命令行。
但是您可以通过编程方式启动它:
# server.py
import uvicorn
import os
import django
from channels.routing import get_default_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
django.setup()
app = get_default_application()
if __name__ == "__main__":
uvicorn.run("server:app") # Pass additional command line options as kwargs
我一直在尝试从 daphne 切换到 uvicorn 以使用 django 3 和频道进行生产。我在加载通道的经典 asgi 文件时遇到错误。由于对 django.setup 或 get_application 的同步调用,我无法使用它。我试图用 sync_to_async 调用来调整这个文件,但没有成功。有没有人设法让它发挥作用?
原版asgi.py
代码
import os
import django
from channels.routing import get_default_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
django.setup()
application = get_default_application()
堆栈跟踪
Traceback (most recent call last):
File "/usr/local/lib/python3.8/multiprocessing/process.py", line 315, in _bootstrap
self.run()
File "/usr/local/lib/python3.8/multiprocessing/process.py", line 108, in run
self._target(*self._args, **self._kwargs)
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/uvicorn/subprocess.py", line 61, in subprocess_started
target(sockets=sockets)
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/uvicorn/main.py", line 407, in run
loop.run_until_complete(self.serve(sockets=sockets))
File "/usr/local/lib/python3.8/asyncio/base_events.py", line 612, in run_until_complete
return future.result()
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/uvicorn/main.py", line 414, in serve
config.load()
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/uvicorn/config.py", line 300, in load
self.loaded_app = import_from_string(self.app)
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/uvicorn/importer.py", line 20, in import_from_string
module = importlib.import_module(module_str)
File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "./config/asgi.py", line 16, in <module>
django.setup()
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/django/apps/registry.py", line 122, in populate
app_config.ready()
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/django_prometheus/apps.py", line 23, in ready
ExportMigrations()
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/django_prometheus/migrations.py", line 52, in ExportMigrations
executor = MigrationExecutor(connections[alias])
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/django/db/migrations/executor.py", line 18, in __init__
self.loader = MigrationLoader(self.connection)
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/django/db/migrations/loader.py", line 49, in __init__
self.build_graph()
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/django/db/migrations/loader.py", line 212, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 76, in applied_migrations
if self.has_table():
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 56, in has_table
return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor())
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/django/utils/asyncio.py", line 24, in inner
raise SynchronousOnlyOperation(message)
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
已修改asgi.py
代码
import os
import django
from asgiref.sync import sync_to_async
from channels.routing import get_default_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
sync_to_async(django.setup, thread_sensitive=True)
application = sync_to_async(get_default_application, thread_sensitive=True)
堆栈跟踪
Traceback (most recent call last):
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/uvicorn/lifespan/on.py", line 55, in main
await app(scope, self.receive, self.send)
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
return await self.app(scope, receive, send)
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/asgiref/sync.py", line 296, in __call__
ret = await asyncio.wait_for(future, timeout=None)
File "/usr/local/lib/python3.8/asyncio/tasks.py", line 455, in wait_for
return await fut
File "/usr/local/lib/python3.8/concurrent/futures/thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/asgiref/sync.py", line 334, in thread_handler
return func(*args, **kwargs)
TypeError: get_default_application() takes 0 positional arguments but 3 were given
ERROR: Application startup failed. Exiting.
感谢大家阅读我的文章
- 根据这个 function ,您传递给 uvicorn 的可调用项将在事件循环中 运行
- 因为1.
django.setup()
需要转换成co-routine get_default_application()
不应该是 运行 异步的,它会去 auto-magically return 路由器应用程序。 uvicorn应该指的就是这个。django.setup()
必须 return 在主事件循环开始之前
鉴于这四点,您的代码应该如下:
import os
import django
from asgiref.sync import sync_to_async
from channels.routing import get_default_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
await sync_to_async(django.setup, thread_sensitive=True)()
application = get_default_application()
但是,在撰写本文时,您不能将 await 用作 top-level 指令,并且如果您将其删除,则无法保证设置会在模块解析之前完成(不会)。因此,如果您在启动应用程序之前有 运行 的同步代码,则不能使用 uvicorn 的命令行。
但是您可以通过编程方式启动它:
# server.py
import uvicorn
import os
import django
from channels.routing import get_default_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
django.setup()
app = get_default_application()
if __name__ == "__main__":
uvicorn.run("server:app") # Pass additional command line options as kwargs