推荐答案
在 FastAPI 中,RedirectResponse 用于将客户端重定向到另一个 URL。以下是一个简单的示例,展示了如何在 FastAPI 中使用 RedirectResponse:
// www.javascriptcn.com code example
from fastapi import FastAPI
from fastapi.responses import RedirectResponse
app = FastAPI()
@app.get("/old-url")
async def old_url():
return RedirectResponse(url="/new-url")
@app.get("/new-url")
async def new_url():
return {"message": "Welcome to the new URL!"}在这个示例中,当用户访问 /old-url 时,他们将被重定向到 /new-url,并看到 {"message": "Welcome to the new URL!"} 的响应。
本题详细解读
1. 导入 RedirectResponse
首先,你需要从 fastapi.responses 模块中导入 RedirectResponse。RedirectResponse 是一个特殊的响应类,用于处理 HTTP 重定向。
from fastapi.responses import RedirectResponse
2. 创建 FastAPI 应用
接下来,创建一个 FastAPI 应用实例:
app = FastAPI()
3. 定义路由和处理函数
你可以定义一个路由 /old-url,并在其处理函数中返回 RedirectResponse。RedirectResponse 的 url 参数指定了重定向的目标 URL。
@app.get("/old-url")
async def old_url():
return RedirectResponse(url="/new-url")在这个例子中,当用户访问 /old-url 时,他们将被重定向到 /new-url。
4. 定义目标路由
你还需要定义目标路由 /new-url,以便用户在被重定向后能够看到内容。
@app.get("/new-url")
async def new_url():
return {"message": "Welcome to the new URL!"}5. 运行 FastAPI 应用
最后,运行 FastAPI 应用,用户就可以通过访问 /old-url 来体验重定向功能了。
uvicorn main:app --reload
6. 其他注意事项
RedirectResponse默认使用 HTTP 状态码307(临时重定向)。如果你想使用其他状态码,比如301(永久重定向),可以通过status_code参数指定:return RedirectResponse(url="/new-url", status_code=301)
RedirectResponse也可以用于重定向到外部 URL,只需将完整的 URL 传递给url参数即可。return RedirectResponse(url="https://example.com")
通过以上步骤,你可以在 FastAPI 中轻松实现 URL 重定向功能。