fastapi Session 设置过期时间 demo
时间: 2023-11-12 18:05:44 浏览: 117
Sure, here's a demo of setting the expiration time for a session in FastAPI:
```
from fastapi import FastAPI, Request, Response, APIRouter, Depends, HTTPException, status
from fastapi.templating import Jinja2Templates
from fastapi.security import OAuth2PasswordRequestForm
from datetime import timedelta
app = FastAPI()
router = APIRouter()
templates = Jinja2Templates(directory="templates")
def get_settings():
return settings
# Configurations
class Settings(BaseSettings):
access_token_expire_minutes: int = 30
refresh_token_expire_days: int = 30
api_prefix: str
settings = Settings()
# Session
router = APIRouter()
ACCESS_TOKEN_EXPIRE_MINUTES = settings.access_token_expire_minutes
@router.post("/login/access-token")
async def login_access_token(
form_data: OAuth2PasswordRequestForm = Depends(),
session: Session = Depends(get_session),
):
user = authenticate_user(session, form_data.username, form_data.password)
if not user:
raise HTTPException(status_code=400, detail="Incorrect username or password")
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": user.email}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
async def on_startup():
app.session_cookie_name = "access_token"
app.include_router(router)
return
@app.on_event("startup")
async def startup():
await on_startup()
```
Hope that helps! Let me know if you have any more questions.
阅读全文