FastAPI路由路径中能否使用f-string?示例写法可行性咨询
FastAPI路由路径中使用f-string的可行性
这种写法是完全可行的。
FastAPI的路由装饰器(比如@app.get())本质上接收的是字符串格式的路径,用f-string拼接路径片段后,最终生成的字符串和直接手写完整路径的效果完全一致。
以你给出的代码为例:
common_path = '/{user}/{item_id}' @app.get(f'{common_path}/testing')
拼接后实际的路由路径是/{user}/{item_id}/testing,和直接写@app.get('/{user}/{item_id}/testing')没有任何区别,FastAPI依然能正确识别路径中的参数user和item_id,并在处理请求时自动解析。
这种方式还能帮你复用重复的路径片段,减少代码冗余,是很实用的写法。比如你可以把多个端点共用的路径部分抽出来,用f-string组合成不同的完整路由,维护起来更方便。
下面是一个可运行的完整示例:
from fastapi import FastAPI app = FastAPI() # 复用的路径片段 common_path = '/{user}/{item_id}' @app.get(f'{common_path}/testing') async def get_testing_data(user: str, item_id: int): return { "user": user, "item_id": item_id, "message": "来自testing端点的数据" } @app.get(f'{common_path}/details') async def get_item_details(user: str, item_id: int): return { "user": user, "item_id": item_id, "message": "来自details端点的详情数据" }
内容的提问来源于stack exchange,提问作者NFeruch - FreePalestine
相关产品推荐
相关产品推荐

