如何将Pyramid中的不同模型的models.py拆分为不同的文件? [英] How do I split models.py into different files for different models in Pyramid?
问题描述
我刚接触金字塔,一直在努力对我的项目进行一些更改.我正在尝试将模型/类拆分为单个文件,而不是单个models.py文件.为此,我删除了旧的models.py并创建了一个包含__init__.py
文件以及每个类一个文件的models文件夹.在__init__.py
中,我使用from .Foo import Foo
导入了该类.
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.
但是,当我将所有模型都放在一个models.py中时,运行initializedb脚本不会创建新表.它不会创建相关表,而是直接尝试在其中插入.
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?
推荐答案
myapp
__init__.py
scripts
__init__.py
initialize_db.py
models
__init__.py
meta.py
foo.py
moo.py
现在meta.py
可以包含共享的Base
以及DBSession
:
now meta.py
can contain a shared Base
as well as the DBSession
:
Base = declarative_base()
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension))
每个foo.py
和moo.py
都可以从meta.py
导入其共享库.
Each foo.py
and moo.py
can import their shared base from meta.py
.
from .meta import Base
class Foo(Base):
pass
要确保从models
子包中拾取所有表,并且为了方便起见,可以将它们导入models/__init__.py
:
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
如果不执行这样的操作,不同的表将不会附加到Base
上,因此在调用create_all
时将不会创建这些表.
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.
您的initialize_db
脚本随后可以通过以下方式创建所有表
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
这篇关于如何将Pyramid中的不同模型的models.py拆分为不同的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!