FastAPI如何在WebSocket视图函数内获取对应路由的name属性
FastAPI WebSocket路由获取name属性解决方案
方案1:直接从WebSocket scope提取(推荐,适用于FastAPI 0.65.0及以上版本)
FastAPI底层基于Starlette框架,WebSocket对象的scope字典内置了当前匹配的路由实例,路由的name属性就是你注册时定义的endpoint值,直接调用即可:
@ws_app.websocket("/route1", name="endpoint1") @ws_app.websocket("/route2", name="endpoint2") async def main_stream(ws: WebSocket): current_endpoint = ws.scope['route'].name if current_endpoint == 'endpoint1': # 处理/route1路径的请求逻辑 ...
如果你的FastAPI版本过低拿不到该属性,建议先升级框架版本,或者使用下面的全兼容方案。
方案2:自定义装饰器显式传参(全版本兼容)
不想依赖框架内部属性的话,可以通过自定义装饰器把endpoint名显式传递给视图函数,稳定性更高:
from functools import wraps # 自定义装饰器,用于传递endpoint名称 def pass_endpoint(name: str): def decorator(func): @wraps(func) async def wrapper(*args, **kwargs): kwargs["current_endpoint"] = name return await func(*args, **kwargs) return wrapper return decorator # 注册路由时同步添加装饰器传入对应name @ws_app.websocket("/route1", name="endpoint1") @pass_endpoint("endpoint1") @ws_app.websocket("/route2", name="endpoint2") @pass_endpoint("endpoint2") async def main_stream(ws: WebSocket, current_endpoint: str): if current_endpoint == 'endpoint1': # 处理/route1路径的请求逻辑 ...
内容的提问来源于stack exchange,提问作者GG_Python
相关产品推荐
相关产品推荐

