Avoiding boilerplate session handling code in sqlalchemy functions

前端 未结 3 1348
暗喜
暗喜 2020-12-25 12:50

I have a python application which has lots of small database access functions, using sqlalchemy. I\'m trying to avoid having lots of boilerplate session handling code around

3条回答
  •  情话喂你
    2020-12-25 13:34

    morphyn's suggestion to use a context manager is good. You could make such a context manager by applying the contextlib.contextmanager decorator to a function very much like your first get_ticket_history, replacing the code between try and except with a yield statement and renaming it, say, transaction. PEP 343 has a near-identical example of that name.

    Then, use that context manager with the with statement to reimplement get_ticket_history. It looks like SQLAlchemy already provides that function, though, as method begin:

    http://docs.sqlalchemy.org/en/rel_0_8/orm/session.html#autocommit-mode

提交回复
热议问题