python - FastAPI:从视图名称(路由名称)中检索 URL
问题描述
假设我有以下观点,
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 中使用这些函数
那么,我怎样才能以类似的方式获取/构建 和 的 URL hello_world
?hello_world_number
解决方案
我们得到了Router.url_path_for(...)
位于starlette包内的方法
方法一:使用FastAPI
实例
FastAPI
当您能够在当前上下文中访问实例时,此方法很有用。(感谢@Yagizcan Degirmenci)
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}
print(app.url_path_for('hello_world'))
print(app.url_path_for('hello_world_number', number=1}))
print(app.url_path_for('hello_world_number', number=2}))
# Results
/hello/
/hello/1/
/hello/2/
退税
- 如果我们使用
APIRouter
,router.url_path_for('hello_world')
可能不起作用,因为router
它不是FastAPI
类的实例。也就是说,我们必须有FastAPI
实例来解析 URL
方法二:Request
实例
Request
当您通常可以在视图中访问实例(传入请求)时,此方法很有用。
from fastapi import FastAPI, Request
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}
@app.get('/')
def named_url_reveres(request: Request):
return {
"URL for 'hello_world'": request.url_for("hello_world"),
"URL for 'hello_world_number' with number '1'": request.url_for("hello_world_number", number=1),
"URL for 'hello_world_number' with number '2''": request.url_for("hello_world_number", number=2})
}
# Result Response
{
"URL for 'hello_world'": "http://0.0.0.0:6022/hello/",
"URL for 'hello_world_number' with number '1'": "http://0.0.0.0:6022/hello/1/",
"URL for 'hello_world_number' with number '2''": "http://0.0.0.0:6022/hello/2/"
}
退税
- 我们必须
request
在每个(或必需的)视图中包含该参数以解析 URL,这可能会给开发人员带来丑陋的感觉。
推荐阅读
- fuzzing - 在 Fuzzing Mosquitto 库中需要一些帮助
- appium - NativeScript RadListView 索引
- r - R新手并试图改善分组箱形图的外观
- c++ - BigInt 计算器吐出稍微错误的结果
- java - 在java中检查hashmap上的正则表达式模式列表的最有效和最快的方法是什么
- asp.net-core - 在 .Net Core 中创建每周运行的调度程序
- javascript - 在 rimraf 包的帮助下使用 glob 删除 Node 中的所有子文件夹?
- android - 如何使 ViewRenderable 大小与检测到的图像相同,以便在 ARCore Sceneform 中准确叠加
- c# - 将 Long 转换为 DateTime 给出错误值
- arrays - 在 Julia 中使用 Interpolations.jl 和 Dierckx.jl 插值函数