假设我有以下观点,
from fastapi import FastAPI
app = FastAPI()
@app.get('/hello/')
def hello_world():
return {"msg": "Hello World"}
@app.get('/hello/{number}/')
def hello_world_number(number: int):
return {"msg": "Hello World Number", "number": number}
我一直在 Flask 和 Django 中使用这些功能
那么,如何以类似的方式获取/构建 hello_world
和 hello_world_number
的 URL?
原文由 JPG 发布,翻译遵循 CC BY-SA 4.0 许可协议
我们有
Router.url_path_for(...)
位于 starlette 包内的方法方法一:使用
FastAPI
实例当您能够在当前上下文中访问
FastAPI
实例时,此方法很有用。 (感谢 @Yagizcan Degirmenci )退税
APIRouter
,router.url_path_for('hello_world')
may not work sincerouter
isn’t an instance ofFastAPI
class.也就是说, 我们必须有FastAPI
实例来解析 URL方法二:
Request
实例当您能够访问
Request
实例(传入请求)时,此方法很有用,通常是在视图中。退税
request
参数来解析 URL,这可能会给开发人员带来 丑陋 的感觉。