Pyramid Framework包括从插件到主应用程序的models.py

时间:2013-11-15 09:19:54

标签: python sqlalchemy pyramid

我正在尝试创建一个金字塔框架身份验证插件/插件。插件需要有一个存储用户登录和其他数据的数据库,因此如果用户使用我的插件,他的数据库必须包含插件中的某些表/模型。例如这个用户表

class User(Base):
    __tablename__ = 'User'
    id = Column(Integer, primary_key=True)
    username = Column(Text())
    user_firstname = Column(Text())
    user_lastname = Column(Text())
    user_email = Column(Text())
    user_password = Column(Text())
    user_registrationdate = Column(DateTime())
    user_email_key = Column(Text())
    user_email_key_date_created = Column(DateTime())
    user_email_approved = Column(Boolean())
    user_email_sent = Column(Boolean())
    user_active_account = Column(Boolean())
    user_banned = Column(Boolean())
    user_banned_reason = Column(Text())

我需要将此模型包含在用户主应用程序中,我猜我必须在我的includeme中包含一些内容,如下所示

def includeme(config):
    config.include('pyramid_mako')
    config.add_route('pyramid.admin', '/pyramid/admin')

    #static views
    config.add_static_view('assets', 'pyramidadmin:static/assets/')

    config.scan('pyramidadmin.views')

但我不知道该怎么做。有没有办法可以将Base和DBSession从我的插件合并到主应用程序的基础中,这样如果用户运行../bin/initialize_myapp_db myaddon和主应用程序中的表都被创建了?

2 个答案:

答案 0 :(得分:0)

您可以使用以下方法:

import sqlalchemy
import sqlalchemy.orm as orm
from zope.sqlalchemy import ZopeTransactionExtension
from sqlalchemy.ext.declarative import declarative_base

DBSession = None

def get_sa_base(engine):
    sabase = sqlalchemy.ext.declarative.declarative_base()
    sabase.metadata.reflect(engine)
    return sabase

def includeme(config):
    global DBSession
    engine = sqlalchemy.engine_from_config(config.registry.settings)
    if DBSession is None:
        DBSession = orm.scoped_session(
            orm.sessionmaker(extension=ZopeTransactionExtension()))
    DBSession.remove()
    DBSession.configure(bind=engine)
    Base = get_sa_base(engine)

    # example:
    Base.metadata.tables.values()

可以找到一个示例here

答案 1 :(得分:0)

我自己也遇到过同样的问题。我仍在努力尝试使用更多可插拔的东西,但结果好坏参半。我解决这个问题的方法是将每个声明性基类与相同的引擎绑定。在我的通用scaffolding中,我这样做:

# create db engine
engine = engine_from_config(settings, 'sqlalchemy.')
# setup db.sessionmaker
settings['db.sessionmaker'] = DBSession
# bind session to engine
DBSession.configure(bind=engine)
# bind objects to engine
Base.metadata.bind = engine
from trumpet.models.base import Base as TrumpetBase
TrumpetBase.metadata.bind = engine
if settings.get('db.populate', 'False') == 'True':
    from mslemon.models.main import make_test_data
    import mslemon.models.misslemon
    Base.metadata.create_all(engine)
    TrumpetBase.metadata.create_all(engine)
    #initialize_sql(engine)