使用fastapi Session 设置过期时间 写一个demo,需要注释
时间: 2024-05-09 18:18:13 浏览: 345
好的,这是一个技术问题,我可以直接回答。
代码如下:
```python
from fastapi import FastAPI, Depends, Request, Response
from fastapi.responses import JSONResponse
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from datetime import timedelta
app = FastAPI()
security = HTTPBasic()
users = {"john": "password", "jane": "secret"}
@app.post("/login")
def login(response: Response, credentials: HTTPBasicCredentials = Depends(security)):
correct_username = credentials.username in users
correct_password = users.get(credentials.username) == credentials.password
if not (correct_username and correct_password):
return JSONResponse({"error": "Bad username or password"}, status_code=400)
access_token = credentials.username + "secret"
response.set_cookie(key="access_token", value=access_token, httponly=True)
return {"message": "Welcome"}
@app.get("/data")
def read_data(request: Request, access_token: str = Depends(security)):
session_token = request.cookies.get("access_token")
if session_token != access_token:
raise HTTPException(status_code=400, detail="Invalid access token")
return {"data": "Some data"}
@app.get("/logout")
def logout(response: Response):
response.delete_cookie(key="access_token")
return {"message": "Logged out"}
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
response = await call_next(request)
max_age = 1800 # 30 minutes
response.headers["Cache-Control"] = f"max-age={max_age}, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"
return response
```
在这个例子中,我们使用了 `response.set_cookie()` 来设置会话令牌,通过这个令牌我们可以识别用户身份。我们可以使用 `request.cookies.get()` 来获得用户的会话令牌,并验证它是否与传递的访问令牌相同,来保证访问的安全性。我们通过注册一个中间件函数来设置响应头中的缓存控制字段,来保证每个响应在客户端中都具有唯一性。我们可以使用 `timedelta` 类来设置会话超时时间。
希望这个示例有助于您实现您的代码!
阅读全文