fastapi-practices / fastapi_best_architecture

A RBAC (Role-Based Access Control) permission control system built on FastAPI, featuring a unique pseudo-three-tier architecture design, with built-in basic implementation of fastapi admin as a template library, free and open-source
https://fastapi-practices.github.io/fastapi_best_architecture_docs/
MIT License
633 stars 109 forks source link

添加 ws 集成 #405

Closed wu-clan closed 6 days ago

wu-clan commented 2 months ago

related: #210 #212 #328

elkon028 commented 1 month ago

安装依赖

pip install "python-socketio[asyncio]"

创建一个 sio

def create_socketio( cors_allowed_origins: str | list = '*', async_mode: str = 'asgi', kwargs ) -> AsyncServer: return AsyncServer( cors_credentials=True, async_mode=async_mode, cors_allowed_origins=cors_allowed_origins, kwargs )

sio = create_socketio()

@sio.event async def connect(sid, environ, auth): print(f'connected auth={auth} sid={sid}') await sio.emit('hello', ({'hello': 'you'}), to=sid)


## 设置一个 socketio 的路由
- backend/main.py
```py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import socketio
import uvicorn

from backend.core.registrar import register_app
from backend.core.socketio import sio

fastapi_app = register_app()
combined_asgi_app = socketio.ASGIApp(socketio_server=sio, other_asgi_app=fastapi_app)

fastapi_app.add_route('/socket.io/', route=combined_asgi_app, methods=['GET', 'POST'])
fastapi_app.add_websocket_route('/socket.io/', combined_asgi_app)

if __name__ == '__main__':
    try:
        uvicorn.run(combined_asgi_app, host='127.0.0.1', port=8000, reload=True, log_level='info')
    except Exception as e:
        raise e

vue 前端连接 socketio

pnpm add socket.io-client
wu-clan commented 1 month ago

@elkon028 非常感谢您提供帮助

wu-clan commented 6 days ago

Done.