Pylons / pyramid

Pyramid - A Python web framework
https://trypyramid.com/
Other
3.97k stars 887 forks source link

SQLAlchemy sessions close before add_finished_callback() processing #3600

Closed kenneaal closed 4 years ago

kenneaal commented 4 years ago

Describe the bug This is potentially intended behavior that may benefit from being reviewed and reimplemented.

In a SQLAlchemy enabled scaffold, the transaction manager has closed the transaction (probably in the tween). This means that rather than using the request-attached session, you must start a new dbsession and transaction if you are doing database operations in a callback.

This may be counterproductive, especially in situations where for instance the application attaches the authenticated user as a database lookup to the request session (For instance, as request.user). Changes to request.user within a view would be persisted, while in the callback you would not have this convenience.

Perhaps a look into whether the session cleanup should happen later in the flow might be warranted?

To Reproduce

  1. Create a SQLAlchemy enabled project.
  2. Add a view and add a add_finished_callback() to it.
  3. In the callback, access the database through request.dbsession.query().
  4. The request will fail with transaction.interfaces.NoTransaction

Expected behavior request.dbsession should still have a live transaction, or start a new one before processing the callback.

mmerickel commented 4 years ago

I’m the one that replied to your stackoverflow question and the behavior I described there is by design as part of pyramid_tm. You can’t do everything you want in every hook pyramid provides. Each hook has different guarantees about the state of the request.