如何在 FastAPI 中提取标签名称和描述?

时间:2020-12-28 14:20:25

标签: python fastapi

我想在方法内使用 tags_metadata 中存在的名称和描述。我不知道怎么做,有什么办法可以使用这些属性

from fastapi import FastAPI

tags_metadata = [
    {
        "name": "select name",
        "description": "Operations with users. The **login** logic is also here.",
    },
    {
        "name": "items",
        "description": "Manage items. So _fancy_ they have their own docs.",
        "externalDocs": {
            "description": "Items external docs",
            "url": "https://fastapi.tiangolo.com/",
        },
    },
]

app = FastAPI(openapi_tags=tags_metadata)


@app.get("/users/", tags=["users"])
async def get_users():
    return [{"name": "Harry"}, {"name": "Ron"}]


@app.get("/items/", tags=["items"])
async def get_items():
    return [{"name": "wand"}, {"name": "flying broom"}]

这里我想在get_users()方法中从tags_metadata中选择名字属性

输出需要-->“选择名称”

https://fastapi.tiangolo.com/tutorial/metadata/?h=+tags#use-your-tags

1 个答案:

答案 0 :(得分:-1)

是的。

from fastapi import FastAPI 

app = FastAPI()


@app.get("/dummy", tags=["dummy2"])
async def dummy():
    ... 

@app.post("/dummy2", tags=["dummy2"])
async def dummy2():
    ... 

假设我们有这些路由。通过检查来自 app.router 的每条路线,我们可以找到路径。

@app.get("/tags", tags=["tags"])
async def tags():
    tags = {}
    for route in app.router.__dict__["routes"]:
        if hasattr(route, "tags"):
            tags[route.__dict__["path"]] = route.__dict__["tags"]

    return tags

当我们到达 /tags 端点时,我们会看到这一点。

{
   "/dummy":[
      "dummy2"
   ],
   "/dummy2":[
      "dummy2"
   ],
   "/tags":[
      "tags"
   ]
}