On Thu, Mar 29, 2018 at 8:57 AM,  <[email protected]> wrote:
> Hello,
>
> I had some database problems (unfinished transactions) so I have wrapped
> sqlalchemy database handling functions in following way:
>
> def add(entry, session):
>     """Wrapper for db_session.add"""
>     try:
>         return session.add(entry)
>     except Exception as e:
>         session.rollback()
>         raise e
>
> def query(ModelClass, session):
>     """Wrapper for session.query(Class)"""
>     try:
>         return session.query(ModelClass)
>     except Exception as e:
>         session.rollback()
>         raise e
>
> def commit(session):
>     """Wrapper for session.commit"""
>     try:
>         return session.commit()
>     except Exception as e:
>         session.rollback()
>         raise e
>
> def delete(entry, session):
>     """Wrapper for session.delete"""
>     try:
>         return session.delete(entry)
>     except Exception as e:
>         session.rollback()
>         raise e
>
> Is this a good practice?
>

In general, you should do what makes the most sense for your
application, and if this style works for you, that's fine. It's
difficult to say more without seeing how you use these functions. A
more common pattern is to put the session management "around" the rest
of your application code, and handle exceptions in just one place.
There's a section in the docs with more details:

http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#session-faq-whentocreate

Hope that helps,

Simon

-- 
SQLAlchemy - 
The Python SQL Toolkit and Object Relational Mapper

http://www.sqlalchemy.org/

To post example code, please provide an MCVE: Minimal, Complete, and Verifiable 
Example.  See  http://stackoverflow.com/help/mcve for a full description.
--- 
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 https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to