Buttons840
Buttons840

Reputation: 9637

How can I use the Engine within a SQLAlchemy declarative class?

Lets say I have this User in my user.py module. I will use this User as part of a larger application. I will configure the Engine (database connection) in the main application module. But...

What if User.foo requires a using an Engine or Session? For example, I have a function in the database which takes a user id and I want to call that function inside foo. To do so, I need to use Engine.execute or Session.execute; but the Engine or Session hasn't been created yet.

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
Base = declarative_base()
class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    password = Column(String)

    def __init__(self, name, fullname, password):
        self.name = name
        self.fullname = fullname
        self.password = password

    def foo(self, bar):
        """I need an Engine or Session!"""
        pass #....

    def __repr__(self):
       return "<User('%s','%s', '%s')>" % (self.name, self.fullname, self.password)

Upvotes: 0

Views: 113

Answers (2)

van
van

Reputation: 77002

Use object_session class method of Session class:

def foo(self, bar):
    session = Session.object_session(self)
    #....

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1122362

You'll need to create an application-level API to retrieve the database whenever someone calls that method.

When using collective.lead to integrate SQLAlchemy with Zope, for example, the database is registered with the Zope Component Architecture as a utility, so whenever I need the session I use a getUtility lookup:

db = getUtility(IDatabase, name=u'responsecentre')
session = db.session                        

In this case, the ZCA getUtility is the application-specific API to look up the database connection, where sessions are bound to threads.

Upvotes: 0

Related Questions