python Django +乌维康

rseugnpd  于 2023-02-18  发布在  Python
关注(0)|答案(3)|浏览(102)

我正在尝试使用Django 3.0和Uvicorn,并得到这个开始:

INFO:     Started server process [96219]
INFO:     Waiting for application startup.
INFO:     ASGI 'lifespan' protocol appears unsupported.
INFO:     Application startup complete.

我可以用--lifespan off标记关闭寿命,但是有没有办法让它在Django上工作?快速搜索Django +寿命似乎没有返回任何东西。

vq8itlhq

vq8itlhq1#

不,lifespan协议不适用于Django 3.0。
查看此票证:https://code.djangoproject.com/ticket/31508

hs1ihplo

hs1ihplo2#

    • 这是我在django 3.1/3.2中使用的初始设置**

编辑:一些粗略的性能基准测试:https://github.com/allen-munsch/benchmark-django-fastapi

旧版本

your_django/old_wsgi.py

import os

from django.core.wsgi import get_wsgi_application
from dj_static import Cling

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_django.settings")

application = Cling(get_wsgi_application())

以前的运行方式:

newrelic-admin run-program gunicorn your_django.old_wsgi \
-k eventlet --log-file - --timeout 60

新版本

your_django/asgi.py

import os

from django.core.asgi import get_asgi_application
from django.contrib.staticfiles.handlers import ASGIStaticFilesHandler

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pm.settings")

application = ASGIStaticFilesHandler(
    get_asgi_application()
)

为了逃跑

gunicorn your_django.asgi --log-level=debug -k uvicorn.workers.UvicornWorker \
--log-file - --timeout 60

# OR for local dev

uvicorn --reload your_django.asgi

相关:

pdtvr36n

pdtvr36n3#

作为@KubaMisiorny pointed out. Django不支持Lifespan Protocol.
如果您想禁用此协议,您有几个选项,具体取决于您的设置。

运行uvicorn

传递--lifespan off选项。
uvicorn --lifespan off

使用uvicorn.workers.UvicornWorker运行gunicorn

您需要通过创建工作类的子类来传递配置参数
创建uvicorn_worker.py

from uvicorn.workers import UvicornWorker as BaseUvicornWorker

# Django does not support Lifespan Protocol
# https://asgi.readthedocs.io/en/latest/specs/lifespan.html
# https://github.com/django/django/pull/13636
# https://code.djangoproject.com/ticket/31508
# Using uvicorn.workers.UvicornWorker throws INFO warning:
#   "ASGI 'lifespan' protocol appears unsupported."
# To avoid that we need to disable 'lifespan' in the worker
class UvicornWorker(BaseUvicornWorker):
    CONFIG_KWARGS = {"lifespan": "off"}

gunicorn.conf.py

# https://www.uvicorn.org/deployment/#gunicorn
# using custom one to disable Lifespan Protocol
# needs to be passed by string https://github.com/benoitc/gunicorn/issues/1539
worker_class = "uvicorn_worker.UvicornWorker"

相关问题