fastapi socketio 简单使用
fastapi 集成python-socketio的简单说明
参考使用
- 安装依赖
pip install fastapi uvicorn python-socketio
- backend 代码
from fastapi import FastAPI,Body
from fastapi.middleware.cors import CORSMiddleware
import socketio
# 注意namespaces * 可以接受各种namespace,默认是/
sio = socketio.AsyncServer(cors_allowed_origins='*',namespaces="*",async_mode='asgi')
@sio.on("connect",namespace="*")
async def connect(namespace, sid,env,auth):
print(f"Client {namespace},{sid} connected to namespace {auth}")
if auth["token"] != "demoapp":
return False
@sio.event(namespace="*")
def disconnect(namespace,sid):
print('disconnect ', sid,namespace)
@sio.on('*',namespace="*")
async def any_event(event,namespace,sid, data):
print(type(event),type(sid),type(namespace),type(data))
print(event,sid,namespace, data)
await sio.emit("dalong", data, namespace="/appdemo")
app = FastAPI()
app.add_middleware(CORSMiddleware,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"])
@app.get("/")
async def demo():
return {"message": "Hello World"}
@app.post("/send_message/{sid}")
async def send_message(sid:str,message: str = Body()):
await sio.emit('message', message, to=sid)
return {"message": f"Message sent to client {sid}: {message}"}
# socketio ASGIApp 包装
app.mount("/message", socketio.ASGIApp(sio, socketio_path="/message"))
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0",port=8000)
- web 集成
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>socketio</title>
</head>
<body>
<script src="https://cdn.socket.io/4.0.1/socket.io.js"></script>
<script>
// demoapp 是namespace ,path 是自定义的path ,auth 是自定义的认证机制
var socket = io('http://localhost:8000/demoapp',{
path: "/message",
auth: {
token: "demoapp"
}
})
socket.on('connect', function(){
console.log('connected');
});
socket.on('message', function(data){
console.log(data);
});
socket.on("dalong", function(data){
console.log(data);
});
socket.on('disconnect', function(){
console.log('disconnected');
});
</script>
</body>
</html>
说明
以上是一个简单说明,python-socketio 的使用还是比较简单的,对于支持ha 以及集群模式的,可以配置redis 以及其他队列服务
参考配置
mgr = socketio.AsyncRedisManager('redis://')
sio = socketio.AsyncServer(client_manager=mgr)
参考资料
https://python-socketio.readthedocs.io/en/stable/index.html
https://github.com/miguelgrinberg/python-socketio