0

我正在使用 FastAPI 创建一个 websocket 端点,但我有很多同步应用程序代码,我想在不创建异步包装器的情况下使用它们。但由于所有 websocket 方法似乎都是异步的,我试图将它们包装在一个同步实用程序函数中。

@app.websocket("/listen")
def listen_endpoint(websocket: WebSocket):
    run_sync(websocket.accept())
    run_sync(websocket.receive_json())
    run_sync(websocket.send_text('ACK'))
    run_sync(websocket.close())

问题在于run_sync. 我按照这里的建议尝试了以下操作:https ://websockets.readthedocs.io/en/stable/faq.html

我可以在没有 async / await 的情况下同步使用 websockets 吗?您可以通过将每个异步调用包装在 asyncio.get_event_loop().run_until_complete(...) 中将其转换为同步调用。

def run_sync(aw: Awaitable):
    return asyncio.get_event_loop().run_until_complete(aw)

但:

  File "app/main.py", line 56, in listen_endpoint
    run_sync(websocket.accept())
  File "app/lib/util.py", line 77, in run_sync
    return asyncio.get_event_loop().run_until_complete(aw)
  File "/home/mangesh/ws/python-versions/3.9.0/lib/python3.9/asyncio/base_events.py", line 618, in run_until_complete
    self._check_running()
  File "/home/mangesh/ws/python-versions/3.9.0/lib/python3.9/asyncio/base_events.py", line 578, in _check_running
    raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running

也试过这个:

def run_sync(aw: Awaitable):
    return asyncio.run(aw)

但:

  File "app/main.py", line 56, in listen_endpoint
    run_sync(websocket.accept())
  File "app/lib/util.py", line 77, in run_sync
    return asyncio.run(aw)
  File "/home/mangesh/ws/python-versions/3.9.0/lib/python3.9/asyncio/runners.py", line 33, in run
    raise RuntimeError(
RuntimeError: asyncio.run() cannot be called from a running event loop

在https://www.aeracode.org/2018/02/19/python-async-simplified/找到另一个建议,但我认为这不适用于 FastAPI。

有可能做我想做的事吗?提前致谢。

4

0 回答 0