在下面的示例中,请确保调用get_routes()
在将 FastAPI 实例传递给之前VersionedFastAPI
。此外,还有一个端点(即/greet
),没有指定版本。因此,为了确保此类端点(如果碰巧存在于您的 API 中)将被分配一个版本,您在尝试获取端点的版本时需要定义一个默认值(也可能是最新版本)这行代码:version = getattr(route.endpoint, "_api_version", (2, 0))
。通过访问 OpenAPI/Swagger UI 文档:http://127.0.0.1:8000/v1/docs http://127.0.0.1:8000/v1/docs and http://127.0.0.1:8000/v2/docs http://127.0.0.1:8000/v2/docs,你会注意到/greet
出现在两个版本的 API 中;因此,可以通过使用/v1/greet
or /v2/greet
。这是因为它最初并没有给出任何特定的版本;但是,使用任一端点,请求都将被分派到相同的路径操作函数。
工作示例
from fastapi import FastAPI, APIRouter
from fastapi_versioning import VersionedFastAPI, version
import uvicorn
app = FastAPI()
router = APIRouter()
all_routes =[]
def get_routes():
reserved_routes = ["/openapi.json", "/docs", "/docs/oauth2-redirect", "/redoc"]
for route in app.routes:
if route.path not in reserved_routes:
if route.name is not None:
version = getattr(route.endpoint, "_api_version", (2, 0))
all_routes.append("/v" + str(version[0]) + route.path)
@router.get("/")
def index():
return { "endpoints": all_routes }
@app.get("/foo")
@version(1)
def foo():
return "foo v1"
@app.get("/foo")
@version(2)
def foo():
return "foo v2"
@app.get("/items/{item_id}")
@version(2)
def get_item(item_id: int):
return item_id
@app.get("/greet")
def greet_with_hi():
return "Hi"
get_routes()
app = VersionedFastAPI(app, version_format='{major}',prefix_format='/v{major}')
app.include_router(router)
if __name__ == '__main__':
uvicorn.run(app, host='127.0.0.1', port=8000)
输出(当访问http://127.0.0.1:8000/ http://127.0.0.1:8000/):
{"endpoints":["/v1/foo","/v2/foo","/v2/items/{item_id}","/v2/greet"]}
这个答案 https://stackoverflow.com/a/72239186/17865804对于检索原始路由路径也可能会有所帮助。