当前位置:   article > 正文

fastapi 使用第三方包socketio 示例_fastapi socketio

fastapi socketio
  1. import socketio
  2. from typing import Text
  3. from urllib.parse import parse_qs
  4. from fastapi import FastAPI, APIRouter
  5. _sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins= [] )
  6. _app = socketio.ASGIApp( socketio_server=_sio, socketio_path="socket.io" )
  7. async def connect(sid, *args, **kwargs):
  8. query_string =args[0]["QUERY_STRING"]
  9. query_dict = parse_qs(query_string)
  10. await _sio.enter_room(sid=sid,room=query_dict["roomId"][0])
  11. async def disconnect(sid, *args, **kwargs):
  12. query_string =args[0]["QUERY_STRING"]
  13. query_dict = parse_qs(query_string)
  14. await _sio.leave_room(sid=sid,room=query_dict["roomId"][0])
  15. _sio.on('connect',connect)
  16. _sio.on('disconnect',disconnect)
  17. def SocketMnager(app:APIRouter|FastAPI):
  18. app.mount("/ws",_app)
  19. app.sio = _sio
  20. from fastapi.middleware.cors import CORSMiddleware
  21. from fastapi import FastAPI
  22. app = FastAPI()
  23. app.add_middleware(
  24. CORSMiddleware,
  25. allow_origins=["*"],
  26. allow_credentials=True,
  27. allow_methods=["*"],
  28. allow_headers=["*"],
  29. )
  30. SocketMnager(app)
  31. import uvicorn
  32. uvicorn.run("__main__:app",host="0.0.0.0",port=3000,reload=False)

前端出现错误1
The 'Access-Control-Allow-Origin' header contains multiple values'*, *', but only one is allowed.
 

  1. # 将前文中的cors_allowed_origins设置为[]
  2. # 这是由于 CORSMiddleware 与socketio 重复设置请求头导致
'
运行

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/863458
推荐阅读
相关标签
  

闽ICP备14008679号