On 5/25/15 6:08 AM, c.bu...@posteo.jp wrote:
What do you think about that (simplified) code?
An instance of this class would be added to any gui-class (e.g. a
dialog) which handle data over SQLAlchemy.

The session would be destroyed/closed correct when the Controller
instance is destroyed, too. Correct?

[code]
import sqlalchemy as sa
import sqlalchemy.orm as sao

_engine = sa.create_engine('postgres://...')

class BasicController():
     """
     """
     def __init__(self):
         self._session = None

     def CreateSession(self):
         if self._session is not None:
             raise AttributeError('...')

         self._session = sao.sessionmaker(bind=_engine)()


     @property
     def session(self):
         """
         """
         if not self._session:
             self.CreateSession()

         return self._session


CreateSession and sessionmaker do the same thing. I'd lose one or the other.

For the memoized thing, I'd use a decorator like Pyramid @reify or SQLAlchemy's @memoized_property, wouldn't bother with all those conditionals and such.

As for "the session would be destroyed/closed", I'd never rely on that, that's a poor design, and it will lead to problems like connection pool overflows and deadlocks. The Session holds onto database resources and those resources should be released explicitly when a web request is complete. See http://docs.sqlalchemy.org/en/rel_1_0/orm/session_basics.html#when-do-i-construct-a-session-when-do-i-commit-it-and-when-do-i-close-it.




--
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 sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to