FastAPI中如何让RedirectResponse跳转至其他文件ApiRouter的/login路由?
解决未登录跳转至认证路由的问题
问题出在RedirectResponse中url_path_for的调用方式上,以下是具体修正方案:
1. 正确使用url_path_for方法
url_path_for需要传入路由函数的名称(而非路径字符串)来生成正确的路由地址。你的登录路由函数名为login,因此应该传入这个名称,而非"/login"。
2. 修正main.py中的异常处理器代码
修改后的完整代码如下:
# 建议将导入放在文件顶部,避免潜在的循环导入问题 from fastapi import FastAPI, Request from starlette.responses import RedirectResponse from routers.authenticate import auth_router, NotAuthenticatedException app = FastAPI(title="Some API") app.include_router(auth_router) @app.exception_handler(NotAuthenticatedException) def auth_exception_handler(request: Request, exc: NotAuthenticatedException): # 通过路由函数名生成正确的登录页面路径 login_url = auth_router.url_path_for("login") return RedirectResponse(login_url)
补充说明
- 若你在
include_router时给认证路由添加了前缀(例如app.include_router(auth_router, prefix="/auth")),url_path_for会自动将前缀包含在生成的路径中,无需手动拼接。 - 如果给路由设置了自定义
name参数(例如@auth_router.post('/login', name='auth_login')),则需要传入这个自定义名称(auth_router.url_path_for("auth_login"))来生成路径。
内容的提问来源于stack exchange,提问作者tabina
相关产品推荐
相关产品推荐

