db_session

The code which interacts with the database has to be placed within a database session. When you work with Python’s interactive shell you don’t need to worry about the database session, because it is maintained by Pony automatically. But when you use Pony in your application, all database interactions should be done within a database session. In order to do that you need to wrap the functions that work with the database with the db_session() decorator:

  1. @db_session
  2. def print_person_name(person_id):
  3. p = Person[person_id]
  4. print p.name
  5. # database session cache will be cleared automatically
  6. # database connection will be returned to the pool
  7. @db_session
  8. def add_car(person_id, make, model):
  9. Car(make=make, model=model, owner=Person[person_id])
  10. # commit() will be done automatically
  11. # database session cache will be cleared automatically
  12. # database connection will be returned to the pool

The db_session() decorator performs the following actions on exiting function:

  • Performs rollback of transaction if the function raises an exception

  • Commits transaction if data was changed and no exceptions occurred

  • Returns the database connection to the connection pool

  • Clears the database session cache

Even if a function just reads data and does not make any changes, it should use the db_session() in order to return the connection to the connection pool.

The entity instances are valid only within the db_session(). If you need to render an HTML template using those objects, you should do this within the db_session().

Another option for working with the database is using the db_session() as the context manager instead of the decorator:

  1. with db_session:
  2. p = Person(name='Kate', age=33)
  3. Car(make='Audi', model='R8', owner=p)
  4. # commit() will be done automatically
  5. # database session cache will be cleared automatically
  6. # database connection will be returned to the pool