On 23 Aug 2014, at 17:05, alchemy1 <[email protected]> wrote:

> I've been following the pattern of (in Pyramid webapps) doing DBSession.add 
> then letting the web framework flush/commit the DBSession at the end of the 
> web request rather than doing it explicitly.
> 
> Are there cases where doing it this way could cause unexpected results, for 
> example let's say you want to register a user:
> 
> DBSession.add(new_user)
>  
> request.session.flash('new user registered')
> 
> headers = remember(request, username) 
> return HTTPFound(location=redirect_url, headers=headers)
> 
> 
> If at the end of the request the framework goes to commit the change and 
> there's some problem, like a constraint violation, then the user wouldn't get 
> created. But by that point the flash message has already been created and the 
> remember() method is already called to log in the user. So the user would be 
> logged in and see a success message even though the user creation operation 
> was not successful.

That discussion is somewhat off-topic for this list, since it involves pyramid 
and different transaction machinery; I would suggest posting to a 
Pyramid-specific list instead.

Having said that: yes, that example is slightly simplified and will result in 
an invalid flash message if the transaction fails. Fixing that is difficult 
since it the transaction is not committed until after the response is 
generated. There are several things you can do:

Flush the session before generating the flash message; that will trip any 
database error 99% of the time.
Use a session storage implementation which integrates with the transaction 
machinery. I'm not sure if any of those exist currently.
You may be able to use use session.flash in an after-commit hook (see 
http://zodb.readthedocs.org/en/latest/transactions.html#after-commit-hooks ). 
There is a chance that this happens too late in the request lifecycle to work, 
so you'll have to try that.
Commit the transaction manually before you call request.session.flash.

Wichert.



-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to