【问题标题】:Django Channels CustomAuthentication close_old_connections SynchronousOnlyOperation exceptionDjango Channels CustomAuthentication close_old_connections SynchronousOnlyOperation 异常
【发布时间】:2020-04-23 01:14:32
【问题描述】:

我尝试从Django Channels documentation 实现 CustomAuthentication,但每次尝试建立 websocket 连接时都会收到 SynchronousOnlyOperation 异常。我错过了什么?

我尝试使用channels.db 中的database_sync_to_async,但是即使我使用的是await,我也被一个协程对象作为返回值卡住了。也许有人知道我做错了什么?

软件包版本:

  • Python 3.6.9
  • Django 3.0.2
  • ASGI/频道 2.4.0
  • 达芙妮 2.4.1
  • asgiref 3.2.3
  • channels-redis 2.4.1

数据库:

  • sqlite3

执行:

python3 manage.py runserver

文件:

settings.py

[...]

ASGI_APPLICATION = 'backend.routing.application'
CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            'hosts': [('127.0.0.1', 6379)]
        },
    },
}

[...]

routing.py(应用程序)

from channels.routing import ProtocolTypeRouter, URLRouter
import backend.api.routing as route
from backend.api.auth import TicketAuthMiddleware

application = ProtocolTypeRouter({
    'websocket': TicketAuthMiddleware(
        URLRouter(
            route.websocket_urlpatterns
        )
    )
})

routing.py (url)

from django.urls import re_path
from backend.api.consumers import OwnConsumer

websocket_urlpatterns = [
        re_path(r'<url>', OwnConsumer)
        ]

consumers.py

from channels.generic.websocket import WebsocketConsumer
import json

class OwnConsumer(WebsocketConsumer):
    def connect(self):
        self.accept()

    def disconnect(self, close_code):
        print("disconnected", close_code)

auth.py

from django.db import close_old_connections

class TicketAuthMiddleware:
    def __init__(self, inner):
        self.inner = inner

    def __call__(self, scope):
       close_old_connections() # <--- raising SynchronousOnlyOperation exception
       return self.inner(dict(scope))

【问题讨论】:

  • 您使用的是哪个数据库?
  • 我现在正在使用 sqlite3

标签: python django authentication websocket channels


【解决方案1】:

目前这是一个记录在案的问题,显然是 Django 3: https://github.com/django/channels/issues/1399(解决方案在里面)。

【讨论】:

    猜你喜欢
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2020-01-25
    • 2021-07-24
    • 1970-01-01
    • 2021-06-15
    相关资源
    最近更新 更多