FastAPI - 是否有可能有一个同步的 websocket 端点?

问题描述

我正在使用 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",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 中不起作用。

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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...