在 fastAPI 中使用中间件时 ASGI 生命周期的问题

问题描述 投票:0回答:0

这些是我在项目中使用的文件

main.py

from fastapi import Depends, FastAPI
from mysqlx import Session

from database import test_db_connection
from utils import get_db, login_user
from schemas import UserLogin
from fastapi.security import OAuth2PasswordRequestForm

from routers import auth, candidates
from middlewares.auth import auth_middleware

app = FastAPI()

# Apply the auth_middleware to the /users endpoint
# app.include_router(users.router, prefix="/users", tags=["users"], dependencies=[Depends(auth_middleware)])

# Exclude the auth_middleware from the /login and /logout endpoints
# app.include_router(auth.router, prefix="/auth", tags=["auth"])

#include auth router
app.include_router(auth.auth_router, prefix="/auth")
app.include_router(candidates.candidate_router, prefix="/candidate")

# add auth middleware
app.add_middleware(auth_middleware)

Middlware 在 middlewares/auth.py

from fastapi import HTTPException, Request
from fastapi.responses import JSONResponse
from typing import List
from starlette.status import HTTP_401_UNAUTHORIZED
import jwt, os
from jwt import PyJWTError

from utils import get_db
from models import User

async def auth_middleware(request: Request, call_next):
    excluded_routes = ['/login', '/logout']  # Add any routes that should be excluded
    path = request.url.path
    if path in excluded_routes:
        response = await call_next(request)
        return response
    token = request.headers.get('Authorization')
    # return 'dfsdf'
    if not token:
        return JSONResponse(status_code=HTTP_401_UNAUTHORIZED, content={'detail': 'Not authenticated'})
    # authentication logic
    try:
        decoded_token = jwt.decode(token, os.environ["SECRET_KEY"], algorithms=["HS256"])
        user = get_db().query(User).get(decoded_token["sub"])
        if user:
            request.state.current_user = user
        else:
            raise HTTPException(status_code=401, detail="Invalid authentication credentials")
    except PyJWTError:
        raise HTTPException(status_code=401, detail="Invalid authentication credentials")
    response = await call_next(request)
    return response

执行此操作时使用

uvicorn main:app --reload
这返回

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [23456] using WatchFiles
INFO:     Started server process [23458]
INFO:     Waiting for application startup.
INFO:     ASGI 'lifespan' protocol appears unsupported.
INFO:     Application startup complete.

auth_middleware() 我正在使用的函数。当我注释掉这个函数时,API 可以正常工作,这表明中间件导致了内部服务器错误。 有人可以帮我解决这个问题吗,因为我对 python 和 fastAPI 还很陌生

python fastapi middleware uvicorn asgi
© www.soinside.com 2019 - 2024. All rights reserved.