Performance: Bearer token handling
This affects the server response time and user interaction speed by how efficiently the token is validated and parsed.
Jump into concepts and practice - no test required
from fastapi import Request import asyncio async def get_token(request: Request): auth_header = request.headers.get('Authorization') if auth_header and auth_header.startswith('Bearer '): token = auth_header.split(' ')[1] # Use async validation to avoid blocking await validate_token_async(token) return token return None
from fastapi import Request async def get_token(request: Request): auth_header = request.headers.get('Authorization') if auth_header and auth_header.startswith('Bearer '): token = auth_header.split(' ')[1] # Simulate heavy synchronous validation validate_token_sync(token) return token return None
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous token validation | N/A | N/A | N/A | [X] Bad |
| Asynchronous token validation | N/A | N/A | N/A | [OK] Good |
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.get("/users/me")
async def read_users_me(token: str = Depends(oauth2_scheme)):
return {"token": token}
What will be the output if the client sends a request with header Authorization: Bearer abc123?oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.get("/items/")
async def read_items(token: str = Depends(oauth2_scheme)):
if token == None:
raise HTTPException(status_code=401, detail="Invalid token")
return {"token": token}