__init__.py 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. from sqlalchemy import engine_from_config
  2. from sqlalchemy.orm import sessionmaker
  3. from sqlalchemy.orm import configure_mappers
  4. import zope.sqlalchemy
  5. # import or define all models here to ensure they are attached to the
  6. # Base.metadata prior to any initialization routines
  7. from .mymodel import MyModel # flake8: noqa
  8. # run configure_mappers after defining all of the models to ensure
  9. # all relationships can be setup
  10. configure_mappers()
  11. def get_engine(settings, prefix='sqlalchemy.'):
  12. return engine_from_config(settings, prefix)
  13. def get_session_factory(engine):
  14. factory = sessionmaker()
  15. factory.configure(bind=engine)
  16. return factory
  17. def get_tm_session(session_factory, transaction_manager):
  18. """
  19. Get a ``sqlalchemy.orm.Session`` instance backed by a transaction.
  20. This function will hook the session to the transaction manager which
  21. will take care of committing any changes.
  22. - When using pyramid_tm it will automatically be committed or aborted
  23. depending on whether an exception is raised.
  24. - When using scripts you should wrap the session in a manager yourself.
  25. For example::
  26. import transaction
  27. engine = get_engine(settings)
  28. session_factory = get_session_factory(engine)
  29. with transaction.manager:
  30. dbsession = get_tm_session(session_factory, transaction.manager)
  31. """
  32. dbsession = session_factory()
  33. zope.sqlalchemy.register(
  34. dbsession, transaction_manager=transaction_manager)
  35. return dbsession
  36. def includeme(config):
  37. """
  38. Initialize the model for a Pyramid app.
  39. Activate this setup using ``config.include('tracim.models')``.
  40. """
  41. settings = config.get_settings()
  42. settings['tm.manager_hook'] = 'pyramid_tm.explicit_manager'
  43. # use pyramid_tm to hook the transaction lifecycle to the request
  44. config.include('pyramid_tm')
  45. # use pyramid_retry to retry a request when transient exceptions occur
  46. config.include('pyramid_retry')
  47. session_factory = get_session_factory(get_engine(settings))
  48. config.registry['dbsession_factory'] = session_factory
  49. # make request.dbsession available for use in Pyramid
  50. config.add_request_method(
  51. # r.tm is the transaction manager used by pyramid_tm
  52. lambda r: get_tm_session(session_factory, r.tm),
  53. 'dbsession',
  54. reify=True
  55. )