3

我正在将 Django Channels 与 uvicorn 一起使用,并且我有以下类型的代码:

async def connect(self): 
    """Accept connect if user has been provided by middleware"""  
    self.user = self.scope.get('user') 
    if self.user: 
        await self.accept() 
    else: 
        await self.close()

基本上,如果在通过中间件之后如果没有使用,我将关闭连接。当我用 Daphne 运行它时,它工作得非常好。否则,当我通过 uvicorn 服务器运行它时,它会引发以下错误:

ERROR: Exception in ASGI application
Traceback (most recent call last):
  File "/home/coldbrewtech/frnd/backend/env/lib/python3.6/site-packages/uvicorn/protocols/websockets/websockets_impl.py", line 146, in run_asgi
    result = await self.app(self.scope, self.asgi_receive, self.asgi_send)
  File "/home/coldbrewtech/frnd/backend/env/lib/python3.6/site-packages/uvicorn/middleware/asgi2.py", line 7, in __call__
    await instance(receive, send)
  File "/home/coldbrewtech/frnd/backend/env/lib/python3.6/site-packages/channels/consumer.py", line 59, in __call__
    [receive, self.channel_receive], self.dispatch
  File "/home/coldbrewtech/frnd/backend/env/lib/python3.6/site-packages/channels/utils.py", line 59, in await_many_dispatch
    await task
  File "/home/coldbrewtech/frnd/backend/env/lib/python3.6/site-packages/channels/utils.py", line 51, in await_many_dispatch
    result = task.result()
  File "/home/coldbrewtech/frnd/backend/env/lib/python3.6/site-packages/uvicorn/protocols/websockets/websockets_impl.py", line 226, in asgi_receive
    data = await self.recv()
  File "/home/coldbrewtech/frnd/backend/env/lib/python3.6/site-packages/websockets/protocol.py", line 419, in recv
    return_when=asyncio.FIRST_COMPLETED,
  File "/usr/lib/python3.6/asyncio/tasks.py", line 311, in wait
    fs = {ensure_future(f, loop=loop) for f in set(fs)}
  File "/usr/lib/python3.6/asyncio/tasks.py", line 311, in <setcomp>
    fs = {ensure_future(f, loop=loop) for f in set(fs)}
  File "/usr/lib/python3.6/asyncio/tasks.py", line 526, in ensure_future
    raise TypeError('An asyncio.Future, a coroutine or an awaitable is '
TypeError: An asyncio.Future, a coroutine or an awaitable is required

但是当我添加await self.accept()before时await self.close(),它​​不会引发任何错误。谁能帮我解决这个问题。

提前致谢!!!

4

1 回答 1

0

这显然是一个问题channels,在close()套接字设置期间该方法尚未准备好被调用。

从我在问题中可以阅读的内容来看,解决方案正是您正在做的,即首先接受连接然后关闭它。

于 2020-09-28T14:07:54.747 回答