FastAPI:从视图名(路由名)中检索URL [英] FastAPI: Retrieve URL from view name ( route name )

查看:0
本文介绍了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?

推荐答案

我们有位于starlette包内的Router.url_path_for(...)方法

方法1:使用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/

缺陷

  • 如果我们使用APIRouterrouter.url_path_for('hello_world')可能无法工作,因为router不是FastAPI类的实例。也就是说,我们必须有FastAPI实例来解析URL

方法2: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,这可能会给开发人员带来难看的感觉。

这篇关于FastAPI:从视图名(路由名)中检索URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆