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

时间:2019-07-03 14:27:10

标签: python-asyncio flask-socketio

我试图从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

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

2 个答案:

答案 0 :(得分:1)

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

例如

def do_something():
    print("Do Something")

async erroneous_function():
    await do_something()

解决方案很简单,请删除await前面的do_something(),因为它不是异步的。

答案 1 :(得分:0)

Flask和Flask-SocketIO不适用于asyncio。要么删除asyncio的内容,要么删除Flask和Flask-SocketIO并使用确实支持asyncio的python-socketio。