1

Тема: FastAPI - редирект на сторінку логіна при помилці 401

Тут все просто

from fastapi import HTTPException

@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    if exc.status_code == status.HTTP_401_UNAUTHORIZED:
        return templates.TemplateResponse("401.html", {"request": request})
    elif exc.status_code == status.HTTP_404_NOT_FOUND:
        return templates.TemplateResponse("404.html", {"request": request})
    elif exc.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR:
        tb = traceback.format_exc()
        return templates.TemplateResponse("500.html", {"request": request, "detail": str(exc), "error_name": str(type(exc).__name__), "traceback": tb})
    elif exc.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY:
        return templates.TemplateResponse("422.html", {"request": request})
    return JSONResponse(
        status_code=exc.status_code,
        content={"message": f"HTTP error occurred: {exc.detail}"},
    )
<!DOCTYPE html>
<html>
<head>

    <title>Unauthorized Access</title>
</head>
<body>
    <h1>Unauthorized Access</h1>
    
    <br>
    <p>You can navigate to the login page by clicking <a href="{{ url_for('login') }}"><b>here</b></a>.</p>
</body>
</html>