Current user with Annotated #9281
-
First Check
Commit to Help
Example CodeCurrentUser = Annotated[User, Depends(get_current_user)]
@router.get("/", status_code=status.HTTP_200_OK)
def get_posts(
db: Session = Depends(get_db),
current_user: CurrentUser = None, # <--- None ?
commons: CommonsDep = None,
) -> list[PostOut]:
"""
### Get post list
"""
passDescriptionI am testing fastapi ==0.95.0 with annontated feature. But I am using the default value in current_user = None, this is correct? Operating SystemWindows, macOS Operating System DetailsNo response FastAPI Version0.95.0 Python Version3.10.10 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
Since you specify The only case it will have an effect is if you call Also as a side note, this is most likely also a type error, unless |
Beta Was this translation helpful? Give feedback.
Since you specify
Depends(get_current_user),current_userwill always get the value returned byget_current_user()whenget_posts()is called by FastAPI. Therefore, setting the default value with= Nonewill have no effect within FastAPI.The only case it will have an effect is if you call
get_posts()directly in some other code. In that case, if you don't pass a value forcurrent_user, Python will apply the default. Note that this is an uncommon case, since usually only FastAPI calls your handlers and you don't call them yourself as normal functions.Also as a side note, this is most likely also a type error, unless
Useris some union type that allowsNoneas a value.