-
| First Check
 Commit to Help
 Example Code (full working example)from fastapi import Depends, Security
from fastapi.security import SecurityScopes
from sqlmodel import Session, create_engine, select
def get_session():
    with Session(engine) as session:
        yield session
async def get_current_user(
    security_scopes: SecurityScopes,
    token: str = Depends(oauth2_scheme),
    session: Session = Depends(get_session)
):
    # Token read omitted 👈
    user = session.get(User, token_data.user_uuid)
    if user is None:
        raise credentials_exception
    return user
async def get_current_app_user(
    current_user: User = Security(get_current_user, scopes=["app"])
):
    return current_user
@app.patch("/me", response_model=UserRead)
def update_current_user(
    user: UserUpdate,
    current_user: User = Depends(get_current_app_user).
    session: Session = Depends(get_session),
):
    user_data = user.dict(exclude_unset=True)
    for key, value in user_data.items():
        setattr(current_user, key, value)
    # Session and session from current_user are different ⚠️
    session.add(current_user) 
    session.commit()
    session.refresh(current_user)
    return current_userDescriptionI am using a synchronous (SQLite) session in a FastAPI Dependency as shown in the SQLModel Tutorial. When a route "depends" on a  How can this be prevented? I would expect a Security to reuse Dependencies as long as  Operating SystemLinux Operating System DetailsNo response SQLModel Version0.0.8 Python VersionPython 3.8.10 Additional ContextNo response I also created a StackOverflow question about this issue. | 
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
| You can use Python's functools to explicitly cache the dependency, like so: This way, the session will be created only once. Any subsequent calls to the function (i.e. via dependencies) will return the cached object. | 
Beta Was this translation helpful? Give feedback.
-
| The original code was oversimplified. The issue is introduced when there is both a  | 
Beta Was this translation helpful? Give feedback.
The original code was oversimplified. The issue is introduced when there is both a
Securityobject and aDependsthat useget_session(). It looks more like a FastAPI bug withSecuritybehavior than a SQLModel issue. Consequently I created a FastAPI discussion and mark this discussion as solved.