【问题标题】:Error when integrating django channels with existing django 3.1 wsgi code将 django 频道与现有 django 3.1 wsgi 代码集成时出错
【发布时间】:2020-11-18 21:34:40
【问题描述】:

在 Django 中添加频道时出现以下错误。

应用程序内部的异常:init() 在 Django 3.1 中为通道添加 ASGI_APPLICATION 时需要 1 个位置参数

Exception inside application: __init__() takes 1 positional argument but 2 were given
Traceback (most recent call last):
  File "/home/dell/Desktop/s/s/s-env/lib/python3.6/site-packages/channels/staticfiles.py", line 44, in __call__
    return await self.application(scope, receive, send)
  File "/home/dell/Desktop/s/s/s-env/lib/python3.6/site-packages/channels/routing.py", line 71, in __call__
    return await application(scope, receive, send)
  File "/home/dell/Desktop/s/s/s-env/lib/python3.6/site-packages/channels/routing.py", line 160, in __call__
    send,
  File "/home/dell/Desktop/s/s/s-env/lib/python3.6/site-packages/asgiref/compatibility.py", line 33, in new_application
    instance = application(scope)
TypeError: __init__() takes 1 positional argument but 2 were give

应用程序在 WSGI 配置上运行良好。上述错误仅在添加 ASGI_APPLICATION = 'app.routing.application' 时出现。

由于它显示源自静态文件的错误,我已尝试再次生成静态文件,但没有帮助。

我正在使用默认的 django asgi 文件:

"""
ASGI config for mevsyou project.

It exposes the ASGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 's.settings.local')

application = get_asgi_application()

s/routing.py:

from channels.routing import ProtocolTypeRouter, URLRouter
from users import routing

application = ProtocolTypeRouter({
    'http': URLRouter(routing.urlpatterns),
})

【问题讨论】:

  • 你需要为application定义一个构造函数__init__,带有两个参数:__init__(self, scope)
  • @WillemVanOnsem,在哪里?我有默认的 django asgi.py 文件
  • 不是asgi 文件,而是app.routing.application
  • 如果你想同时支持两者,如果你想尽可能通用,你可以使用__init__(self, *args)__init__(self, *args, **kwargs)
  • @WillemVanOnsem 我添加了routing.py代码

标签: python django django-channels django-3.1


【解决方案1】:

您的代码适用于频道 2,而您使用的是频道 3。

在频道 3 中,您不应该有 routing.py。但是你的asgi.py 文件应该是这样的:

import os

from channels.routing import ProtocolTypeRouter
from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')

application = ProtocolTypeRouter({
    "http": get_asgi_application(),
})

事实上,ASGI_APPLICATION 应该设置为'app.asgi.application'

See Channels docs for 3.x

【讨论】:

  • 我有版本 3。
  • 所以,这就是问题所在。您的代码适用于 Channels 2。如果您使用版本 3,请确保遵循 Channels 3 的文档。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-31
  • 2017-06-13
  • 2018-08-06
  • 2011-02-13
  • 2010-10-31
  • 2019-10-16
相关资源
最近更新 更多