How do I split models.py into different files for different models in Pyramid?

↘锁芯ラ 提交于 2019-11-28 21:34:19

问题


I am new to pyramid and have been struggling to make some changes to my project. I am trying to split my models/Classes into individual files instead of a single models.py file. In order to do so I have removed the old models.py and created a models folder with __init__.py file along with one file for each class. In __init__.py I imported the class by using from .Foo import Foo.

This makes the views work correctly and they can initialize an object.

But running the initializedb script does not create new tables as it did when I had all the models in a single models.py. It does not create the relevant tables but directly tries to insert in them.

Can anyone give me an example of a pyramid project structure which has models in different files?


回答1:


myapp
    __init__.py
    scripts
        __init__.py
        initialize_db.py
    models
        __init__.py
        meta.py
        foo.py
        moo.py

now meta.py can contain a shared Base as well as the DBSession:

Base = declarative_base()
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension))

Each foo.py and moo.py can import their shared base from meta.py.

from .meta import Base

class Foo(Base):
    pass

To ensure that all of your tables are picked up, from within the models subpackage, and for convenience, you can import them into models/__init__.py:

from .meta import DBSession
from .foo import Foo
from .moo import Moo

Without doing something like this the different tables will not be attached to the Base and thus will not be created when create_all is invoked.

Your initialize_db script can then create all of the tables via

from myapp.models.meta import Base
Base.metadata.create_all(bind=engine)

Your views can import the models to profit:

from myapp.models import DBSession
from myapp.models import Foo



回答2:


I had the same problem once.

The solving for the splited model files: you must initialize all Base (parent) classes from your files separately:

#initializedb.py
...
from project.models.Foo import Base as FooBase
from project.models.Moo import Base as MooBase
...

def main(argv=sys.argv):
    ...
    FooBase.metadata.create_all(engine)
    MooBase.metadata.create_all(engine)


来源:https://stackoverflow.com/questions/10345698/how-do-i-split-models-py-into-different-files-for-different-models-in-pyramid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!