On Mar 8, 2012, at 4:23 PM, ypg wrote:

> I am running SQLAlchemy under a multithreaded python server (paster),
> as part of a web application which is written using the Python Pyramid
> framework.  When I modify an existing database entry through SQL
> alchemy, subsequent page refreshes seem to randomly pick between the
> original instance of the object, and the modified copy.
> 
> For example: if I have user object where user.username is "jdoe", and
> I change the username to "rickymartin", and then keep refreshing the
> page, I will randomly see the "jdoe" and "rickymartin", as the
> username.  If I then change the username again to "shakira", and
> continue to refresh the page, I will randomly see "shakira" or
> "rickymartin".  If I check the database independently, or if I restart
> the web server, I will only ever see updated version of the username.
> 

SQLAlchemy maintains the value of columns within attributes loaded in a single 
Session.   It's not a strict form of caching, in that it isn't caching the 
results of queries, but for the span of an object in the identity map within a 
particular transaction it will hold onto loaded attribute values.

The refresh issue sounds like you have Sessions hanging open with uncommitted 
and/or stale data in them, and depending on which thread you get, you see 
either older or newer data.

Make sure you commit all pending data at the end of a request and then make 
sure you close out the session at the end of each request.   Start each new 
request with  brand new Session.

Some overview of this at 
http://docs.sqlalchemy.org/en/latest/orm/session.html#lifespan-of-a-contextual-session


> I am using a single scoped_session instance to create the sessions,
> which is global to all the threads running in the web application.  I
> can solve this issue by creating a new session every time a request
> comes in, but that would make the code a bit sloppy and I'm trying to
> avoid doing that.  

Well that's the cause here, and interesting you consider allocating new 
resources at the start of a request and cleaning them up at the end "sloppy".   
I'd view this as exactly the opposite, leaving remnants of a previous request 
hanging around would be the definition of sloppiness IMHO.

Pyramid supports clean patterns for establishing Session lifespan with the 
zope.transaction extension - you should check their docs and their mailing list 
for guidelines on its usage.

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to