【问题标题】:Pylons: how to declarative with reflection model definitionPylons:如何使用反射模型定义进行声明
【发布时间】:2011-03-17 21:22:00
【问题描述】:

美好的一天!

我正在学习 Pylons Web 框架来为我的数据库创建 Web UI。 目前我正在探索声明我的模型的方法。最性感的方式似乎是带有反射的声明性。 我可以将它与 Pylons 一起使用吗? (因为model/init.py声明我需要在init_model里面定义反射相关的人员)

谢谢!

【问题讨论】:

    标签: pylons


    【解决方案1】:

    有关 Pylons 1.0 中的最新答案,请参阅 SQLAlchemy declarative syntax with autoload (reflection) in Pylons

    解决办法是在model/__init__.py之外声明模型对象。我在 model 模块中创建了一个新文件,例如objects.py。然后我在这个文件中声明了我所有的模型对象(比如Event)。然后,我可以像这样导入我的模型:

    from PRJ.model.objects import Event
    

    此外,为了避免为每个表指定autoload-with,我在init_model()的末尾添加了这一行:

    Base.metadata.bind = engine
    

    这样我可以在没有样板代码的情况下声明我的模型对象,如下所示:

    class Event(Base):
        __tablename__ = 'events'
        __table_args__ = {'schema': 'events', 'autoload': True}
    
        event_identifiers = relationship(EventIdentifier)
    
        def __repr__(self):
            return "<Event(%s)>" % self.id
    

    【讨论】:

      【解决方案2】:

      您使用的是 Pylons 0.9.7 版吗? Pylons allrady 稳定在 1.0 版本。

      您可以在 init_model 函数之外的 model/init.py 中直接使用带有反射的声明性。或者,您可以在任何其他模块或包中分离模型定义。

      模型/schema.py

      from YOURAPP.model.meta import Base        # for declaration you models and reflection
      from YOURAPP.model.meta import Session     # for using sa session object
      
      class Category(Base):
          __tablename__ = 'category'
      
          id = Column(Integer, primary_key=True)
          name = Column(Unicode(70), index=True, unique=True)
      
      
          def __unicode__(self):
              return self.name
      
      
      class Attribute(Base):
           __tablename__ = 'attribute'
      
          id = Column(Integer, primary_key=True)
          name = Column(Unicode(70), index=True)
      
      
          #Relation
          category_id = Column(Integer, ForeignKey('category.id'))
          category = relation(Category, backref=backref('attributes',
                          order_by=(name,))
      
      
          def __unicode__(self):
              return self.name
      

      在模型/init.py

      from YOURAPP.model.schema import Category, Attribute
      

      【讨论】:

      • 0.9.7 因为 debian 目前附带 0.9.7,并且 pylons 参考书目也是 0.9.7。在您的示例中,您不会在任何地方使用 reflection 。请解释一下。
      猜你喜欢
      • 1970-01-01
      • 2016-06-07
      • 2011-05-30
      • 2011-05-06
      • 2021-09-07
      • 1970-01-01
      • 2019-05-28
      • 2021-01-16
      • 1970-01-01
      相关资源
      最近更新 更多