【问题标题】:How to extract tags name and description in FastAPI?如何在 FastAPI 中提取标签名称和描述?
【发布时间】:2020-12-28 14:20:25
【问题描述】:

我想在方法内使用 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

【问题讨论】:

  • 在什么情况下您可能需要这个?
  • 有什么代码可以分享吗?到目前为止,您尝试过什么?

标签: python fastapi


【解决方案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"
   ]
}

【讨论】:

  • 如果使用API​​Router?我需要提取特定端点标签名称
  • 使用 APIRouter 的实例名称。 app 只是一个实例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
相关资源
最近更新 更多