gpt4 book ai didi

Django Channels中间件使用ORM

转载 作者:行者123 更新时间:2023-12-04 15:18:47 26 4
gpt4 key购买 nike

我无法检查中间件内部的用户 token 。我从 cookie 中获取 token ,然后我需要查询数据库以检查此 token 是否存在以及是否属于发出请求的用户。

路由.py

from channels.routing import ProtocolTypeRouter, URLRouter
import game.routing
from authentication.utils import TokenAuthMiddlewareStack

application = ProtocolTypeRouter({
# (http->django views is added by default)
'websocket': TokenAuthMiddlewareStack(
URLRouter(
game.routing.websocket_urlpatterns
)
),
})

中间件.py

from rest_framework.authentication import TokenAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_auth.models import TokenModel

from channels.auth import AuthMiddlewareStack
from django.contrib.auth.models import AnonymousUser
from django.db import close_old_connections
...
class TokenAuthMiddleware:
"""
Token authorization middleware for Django Channels 2
"""

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


def __call__(self, scope):
close_old_connections()

headers = dict(scope['headers'])
if b'Authorization' in headers[b'cookie']:
try:
cookie_str = headers[b'cookie'].decode('utf-8')

try: # no cookie Authorization=Token in the request
token_str = [x for x in cookie_str.split(';') if re.search(' Authorization=Token', x)][0].strip()
except IndexError:
scope['user'] = AnonymousUser()
return self.inner(scope)

token_name, token_key = token_str.replace('Authorization=', '').split()
if token_name == 'Token':
token = TokenModel.objects.get(key=token_key)
scope['user'] = token.user

except TokenModel.DoesNotExist:
scope['user'] = AnonymousUser()
return self.inner(scope)


TokenAuthMiddlewareStack = lambda inner: TokenAuthMiddleware(AuthMiddlewareStack(inner))

这给了我

django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.

我也尝试了以下方法

async def __call__(self, scope):
...
if token_name == 'Token':
token = await self.get_token(token_key)
scope['user'] = token.user
...

# approach 1
@sync_to_async
def get_token(self, token_key):
return TokenModel.objects.get(key=token_key)

# approach 2
@database_sync_to_async
def get_token(self, token_key):
return TokenModel.objects.get(key=token_key)

这些方法给出了以下错误

[Failure instance: Traceback: <class 'TypeError'>: 'coroutine' object is not callable
/Users/nikitatonkoshkur/Documents/work/svoya_igra/venv/lib/python3.8/site-packages/autobahn/websocket/protocol.py:2847:processHandshake
/Users/nikitatonkoshkur/Documents/work/svoya_igra/venv/lib/python3.8/site-packages/txaio/tx.py:366:as_future
/Users/nikitatonkoshkur/Documents/work/svoya_igra/venv/lib/python3.8/site-packages/twisted/internet/defer.py:151:maybeDeferred
/Users/nikitatonkoshkur/Documents/work/svoya_igra/venv/lib/python3.8/site-packages/daphne/ws_protocol.py:72:onConnect
--- <exception caught here> ---
/Users/nikitatonkoshkur/Documents/work/svoya_igra/venv/lib/python3.8/site-packages/twisted/internet/defer.py:151:maybeDeferred
/Users/nikitatonkoshkur/Documents/work/svoya_igra/venv/lib/python3.8/site-packages/daphne/server.py:206:create_application
]```

最佳答案

我不确定它是否有效,但你可以试试

先在类外写get_token函数

   # approach 1
@sync_to_async
def get_token(self, token_key):
return TokenModel.objects.get(key=token_key)

然后在你的异步函数中写 get_token() 而不是 self.get_token()

  async def __call__(self, scope):
...
if token_name == 'Token':
token = await get_token(token_key)
scope['user'] = token.user
...

关于Django Channels中间件使用ORM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63802423/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com