如何在SQLAlchemy声明性类中使用Engine?

时间:2012-05-24 17:14:15

标签: python orm sqlalchemy

假设我的User模块中有user.py。我将使用此User作为更大应用程序的一部分。我将在主应用程序模块中配置Engine(数据库连接)。但...

如果User.foo要求使用EngineSession,该怎么办?例如,我在数据库中有一个函数,它接受用户id,我想在foo内调用该函数。为此,我需要使用Engine.executeSession.execute;但尚未创建EngineSession

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)

2 个答案:

答案 0 :(得分:1)

使用Session类的object_session类方法:

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

答案 1 :(得分:0)

只要有人调用该方法,您就需要创建一个应用程序级API来检索数据库。

例如,当使用collective.lead将SQLAlchemy与Zope集成时,数据库作为实用程序在Zope组件体系结构中注册,因此每当我需要会话时,我都使用getUtility查找:

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

在这种情况下,ZCA getUtility是用于查找数据库连接的特定于应用程序的API,其中会话绑定到线程。

相关问题