mirror of
https://github.com/fastapi/fastapi.git
synced 2025-12-24 22:59:32 -05:00
* 📝 Add docs recommending Union over Optional * 📝 Update docs recommending Union over Optional * 📝 Update source examples for docs, recommend Union over Optional * 📝 Update highlighted lines with updated source examples * 📝 Update highlighted lines in Markdown with recent code changes * 📝 Update docs, use Union instead of Optional * ♻️ Update source examples to recommend Union over Optional * 🎨 Update highlighted code in Markdown after moving from Optional to Union
33 lines
755 B
Python
33 lines
755 B
Python
from typing import Union
|
|
|
|
from fastapi import Depends, FastAPI
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from pydantic import BaseModel
|
|
|
|
app = FastAPI()
|
|
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
|
|
|
|
|
|
class User(BaseModel):
|
|
username: str
|
|
email: Union[str, None] = None
|
|
full_name: Union[str, None] = None
|
|
disabled: Union[bool, None] = None
|
|
|
|
|
|
def fake_decode_token(token):
|
|
return User(
|
|
username=token + "fakedecoded", email="john@example.com", full_name="John Doe"
|
|
)
|
|
|
|
|
|
async def get_current_user(token: str = Depends(oauth2_scheme)):
|
|
user = fake_decode_token(token)
|
|
return user
|
|
|
|
|
|
@app.get("/users/me")
|
|
async def read_users_me(current_user: User = Depends(get_current_user)):
|
|
return current_user
|