简体   繁体   中英

How do I go about storing session objects?

I have a few a few model classes such as a user class which is passed a dictionary, and wraps it providing various methods, some of which communicate with the database when a value needs to be changed. The dictionary itself is made from an sqlalchemy RowProxy, so all its keys are actually attribute names taken directly from the sql user table. (attributes include user_id, username, email, passwd, etc)

If a user is logged in, should I simply save this dictionary to a redis key value store, and simply call a new user object when needed and pass it this dictionary from redis(which should be faster than only saving a user id in a session and loading the values again from the db based on that user_id)?

Or should I somehow serialize the entire object and save it in redis? I'd appreciate any alternate methods of managing model and session objects that any of you feel would be better as well.

In case anyone is wondering I'm only using the sqlalchemy expression language, and not the orm. I'm using the model classes as interfaces, and coding against those.

Unless you're being really careful, serializing the entire object into redis is going to cause problems. You're effectively treating it like a cache, so you have to be careful that those values are expired if the user changes something about themselves. You also have to make sure that all of the values are serializable (likely via pickle). You didn't specify whether this is a premature optimization so I'm going to say that it probably is and recommend that you just track the user id and reload his information when you need it from your database.

+1 on Michael's answer.

i'd also note a few things-

if you do decide to cache this data, you should treat it as a read-only store. you should never update the database based on this.

i have my projects split into two logical sections:

/account - heavy write operations , data must be current /everything-else - mostly read operations , data should be current

everything in /account always hits the DB for the most up-to-date version. the rest of the site can hit the db or a cache - i don't care.

for your described needs, and using the expression language, you shouldn't need to create objects from cache data to do any of your operations.

http://docs.sqlalchemy.org/en/rel_0_7/core/tutorial.html#inserts-and-updates

>>> conn.execute(users.update().

... where(users.c.name=='jack').

... values(name='ed')

... )

why not just do:

where(users.c.id==cached_value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM