Sqlalchemy: how to not commit initialized orm objects that are read from cache

Viewed 59

Using sqlalchemy and Postgres. Want to utilize redis for cache. Say we use the following function to attempt to read from redis first, if it doesn't exist, read from db.

def get_user(id) -> User:
    key = f'{USER_REDIS_PREFIX}{id}'
    res = redis_conn.get(key)
    if res:
        user_dict = json.loads(res, object_hook=datetime_hook)
        return User(**user_dict)
    else:
        # read from postgres    
    return user

I'm initializing the User ORM object from the user dictionary in order to return User type.

The problem is this user object from the cache is not registered in the db. So if I do

    user = get_user()
    session = get_session()
    team = Team(
        creator=user,              
        name=name
    )
    session.add(team)
    session.flush()

Sqlalchemy tries to insert a new user. resulting in a primary key violation because the user id is already in db.

I can either do creator_id=user.id or just not initialize the User object and return an dict on get. Is there a better way to do this?

0 Answers
Related