首页 > 其他分享 >fastapi socketio cros问题 已解决

fastapi socketio cros问题 已解决

时间:2023-01-29 11:00:26浏览次数:52  
标签:socketio fastapi app cros sid import sio

代码

import socketio
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResponse

# app
app = FastAPI()

# socketio
sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins=[])
app.mount("/ws", socketio.ASGIApp(sio))

# cros
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/")
def index():
    return RedirectResponse(url="/docs", status_code=303)


@app.get('/student')
async def student():
    return {'data': 'alice'}


@sio.event
async def connect(sid, environ):
    print(f'sid={sid}, environ={environ}')
    await sio.emit("connect", 'connect success!!!')


@sio.on('join')
async def ping_message(sid, data):
    print(data)
    await sio.emit("join", 'hello!~~ from server', room=sid)

关键代码

image

  • 其次要注意版本匹配问题

标签:socketio,fastapi,app,cros,sid,import,sio
From: https://www.cnblogs.com/zhuoss/p/17072039.html

相关文章