代码示例都来自于FastAPI的官方文档。示例代码写的很好,基本复制一下就能用了。
第一种方法,是直接返回一个RedirectResponse
对象,默认的HTTP码是307
:
from fastapi import FastAPI
from fastapi.responses import RedirectResponse
app = FastAPI()
@app.get("/typer")
async def redirect_typer():
return RedirectResponse("https://typer.tiangolo.com")
也可以将RedirectResponse
对象作为参数response_class
的值:
from fastapi import FastAPI
from fastapi.responses import RedirectResponse
app = FastAPI()
@app.get("/fastapi", response_class=RedirectResponse)
async def redirect_fastapi():
return "https://fastapi.tiangolo.com"
这样做的好处,是返回的就是URL字符串,可以很方便地用一个函数对其进行处理。
如果想换成其它的status_code
,放到get
函数中即可:
from fastapi import FastAPI
from fastapi.responses import RedirectResponse
app = FastAPI()
@app.get("/pydantic", response_class=RedirectResponse, status_code=302)
async def redirect_pydantic():
return "https://pydantic-docs.helpmanual.io/"
以上就是官方文档提供的代码。为了使运行更为便捷,添加上main
函数,完整代码如下所示:
# -*- coding: UTF-8 -*-
# main.py
import uvicorn
from fastapi import FastAPI
from fastapi.responses import RedirectResponse
app = FastAPI()
@app.get("/pydantic", response_class=RedirectResponse, status_code=302)
async def redirect_pydantic():
return "https://pydantic-docs.helpmanual.io/"
if __name__ == '__main__':
uvicorn.run(
app='main:app',
host="0.0.0.0",
port=302,
workers=4,
reload=True,
debug=True)
此时,在本机浏览器访问http://127.0.0.1:302/pydantic
,网页就自动跳转到https://pydantic-docs.helpmanual.io/
上了。