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 中使用这些功能

那么,如何以类似的方式获取/构建 hello_worldhello_world_number 的 URL?

原文由 JPG 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

我们有 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/"

退税

  • If we are using APIRouter , router.url_path_for('hello_world') may not work since router isn’t an instance of FastAPI class.也就是说, 我们必须有 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,这可能会给开发人员带来 丑陋 的感觉。

原文由 JPG 发布,翻译遵循 CC BY-SA 4.0 许可协议

其实你不需要重新发明轮子。 FastAPI 支持这种开箱即用的功能 (实际上是 Starlette)而且效果很好。

 app = FastAPI()

@app.get("/hello/{number}/")
def hello_world_number(number: int):
    return {"msg": "Hello World Number", "number": number}

如果你有这样的端点,你可以简单地使用

In:  app.url_path_for("hello_world_number", number=3)
In:  app.url_path_for("hello_world_number", number=50)

Out: /hello/3/
Out: /hello/50/

FastAPI 中, APIRouterFastAPI(APIRoute) 继承自 Router (Starlette’s) 所以,如果你有这样的 APIRouter ,你可以继续使用这个特性

router = APIRouter()

@router.get("/hello")
def hello_world():
    return {"msg": "Hello World"}

In:  router.url_path_for("hello_world")
Out: /hello

原文由 Yagiz Degirmenci 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题