获取“Django只能处理ASGI/HTTP连接,不能处理websocket。”在heroku上托管ASGI时出错?

2024-05-29 05:15:08 发布

您现在位置:Python中文网/ 问答频道 /正文

一直在滚动StackOverflow和Youtube上的每个问题以找到答案。我正在通过Heroku上的Django频道部署WSGI和ASGI/websockets。它在本地工作,但在生产过程中给我带来了麻烦

设置

这是我的文件:

web: daphne API.asgi:application --port $PORT --bind 0.0.0.0 -v2
worker: python manage.py runworker background -v2

Settings.py:

# Redis Setup
ASGI_APPLICATION = 'API.routing.application'
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [(HEROKU_URL, 6379)],
        },
    },
}

asgi.py:

import os
import django
from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'API.settings')
django.setup()
application = get_asgi_application()

最后,routing.py:

application = ProtocolTypeRouter({
    'websocket':AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter(
                [
                    url(r"^timer/$", TestConsumer.as_asgi()),
                ]
            )
        )
    )
    ,'channel':ChannelNameRouter({
        'background':BackgroundConsumer.as_asgi()
    })
}) 

问题/日志

Heroku在连接到websocket时记录:

2021-07-02T19:42:42.209398+00:00 app[web.1]: IP - - [02/Jul/2021:19:42:42] "GET /chat_switch/1/" 200 10480
2021-07-02T19:43:02.708851+00:00 app[web.1]: IP - - [02/Jul/2021:19:43:02] "WSCONNECTING /timer/" - -
2021-07-02T19:43:02.709658+00:00 app[web.1]: 2021-07-02 19:43:02,709 DEBUG    Upgraded connection [IP, 32183] to WebSocket
2021-07-02T19:43:03.058159+00:00 app[web.1]: 2021-07-02 19:43:03,057 ERROR    Exception inside application: Django can only handle ASGI/HTTP connections, not websocket.
2021-07-02T19:43:03.058167+00:00 app[web.1]: Traceback (most recent call last):
2021-07-02T19:43:03.058168+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/asgi.py", line 143, in __call__
2021-07-02T19:43:03.058168+00:00 app[web.1]:     raise ValueError(
2021-07-02T19:43:03.058169+00:00 app[web.1]: ValueError: Django can only handle ASGI/HTTP connections, not websocket.
2021-07-02T19:43:03.059813+00:00 app[web.1]: 2021-07-02 19:43:03,059 INFO     failing WebSocket opening handshake ('Internal server error')
2021-07-02T19:43:03.060494+00:00 app[web.1]: 2021-07-02 19:43:03,060 WARNING  dropping connection to peer tcp4:IP:32183 with abort=False: Internal server error
2021-07-02T19:43:03.064484+00:00 app[web.1]: 2021-07-02 19:43:03,063 DEBUG    WebSocket closed for [IP, 32183]

除此之外,常规API函数按预期工作

我试过的

如果有人知道我在这里能做些什么,我将不胜感激


Tags: django答案pycoreimportipapiapp
1条回答
网友
1楼 · 发布于 2024-05-29 05:15:08

看起来application中的routing.py并没有做任何事情。我看到它是在ASGI_APPLICATION中指定的,但我相信,开发服务器(manage.py runserver)会使用它。在daphne命令中,您提供的是API.asgi:application,它只定义了django ASGI应用程序——“http”连接处理程序

您需要的是将get_asgi_application()替换为ProtocolTypeRouter,它定义了每个协议的服务方式——“http”进入django ASGI应用程序,“websocket”进入用户路由

看一下Channels文档中的Deploying部分。您的asgi.py可能看起来像这样(我没有包括您的消费者导入):

import os

from django.core.asgi import get_asgi_application
from django.urls import path

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

django_asgi_app = get_asgi_application()

from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator
from channels.routing import ProtocolTypeRouter, URLRouter, ChannelNameRouter

application = ProtocolTypeRouter({
    'http': django_asgi_app,
    'websocket': AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter(
                [
                    path('timer/', TestConsumer.as_asgi()),
                ]
            )
        )
    ),
    'channel': ChannelNameRouter({
        'background': BackgroundConsumer.as_asgi()
    })
})

相关问题 更多 >

    热门问题