TypeError:对象 NoneType 不能在“await”表达式中使用

问题描述 投票:0回答:3

我试图从我的 Flask-socketio 服务器调用函数

from flask_socketio import emit
import asyncio

async def myfunc():
     for i in range(10):
         j = 1*3
         await emit('update', {'j':j})

在我正在运行的服务器功能中

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
task = asyncio.gather(myfunc())
loop.run_until_complete(task)

我在循环的第一次迭代中遇到错误一次成功发出。

File "path\to\Python\Python37-32\Lib\threading.py", line 917, in _bootstrap_inner self.run() File "path\to\Python\Python37-32\Lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "path\to\lib\site-packages\socketio\server.py", line 636, in _handle_event_internal r = server._trigger_event(data[0], namespace, sid, *data[1:]) File "path\to\lib\site-packages\socketio\server.py", line 665, in _trigger_event return self.handlers[namespace][event](*args) File "path\to\lib\site-packages\flask_socketio\__init__.py", line 280, in _handler *args) File "path\to\lib\site-packages\flask_socketio\__init__.py", line 694, in _handle_event ret = handler(*args) File "path\to\server.py", line 127, in print_message loop.run_until_complete(task) File "path\to\Python\Python37-32\Lib\asyncio\base_events.py", line 584, in run_until_complete return future.result() File "path\to\script.py", line 261, in fun await emit('update', {'j':j}) TypeError: object NoneType can't be used in 'await' expression

我希望能够调用 myfunc() 并在 for 循环的每次迭代中向我的 socketio 客户端发出更新

python-asyncio flask-socketio
3个回答
33
投票
当我在

await

 函数上调用 
non async
 时,我也遇到了同样的错误。

例如

def do_something(): print("Do Something") async erroneous_function(): await do_something()
解决方案很简单,删除 

await

 前面的 
do_something()
,因为它不是异步的。


1
投票
Flask 和 Flask-SocketIO 不能与 asyncio 一起使用。要么删除 asyncio 的东西,要么放弃 Flask 和 Flask-SocketIO 并使用 python-socketio,它确实支持 asyncio。


0
投票
致未来的 Django 程序员。如果您在 Django Channels Consumer 子类中收到此消息,请确保将正确的方法标记为异步:

async def disconnect(self, close_code): pass
是正确的方法。如果没有前缀 async,每当我的客户端调用 closes() WS conn 时,我都会收到与上述相同的错误。

© www.soinside.com 2019 - 2024. All rights reserved.