假设我有几个位于food.py
的简单模型:
import peewee as pw
db = pw.SqliteDatabase('food.db')
class BaseModel(pw.Model):
class Meta:
database = db
class Taco(BaseModel):
has_cheese = pw.BooleanField()
class Spaghetti(BaseModel):
has_meatballs = pw.BooleanField()
db.connect()
# populate with some data if table doesn't exist
from random import random
if not Taco.table_exists():
db.create_table(Taco)
for _ in range(10):
Taco.create( has_cheese = (random() < 0.5) )
db.commit()
if not Spaghetti.table_exists():
db.create_table(Spaghetti)
for _ in range(10):
Spaghetti.create( has_meatballs = (random() < 0.5) )
db.commit()
之后,我有food.py
和food.db
。但是,让我们说Taco
和Spaghetti
模型变得庞大而复杂,所以我想将它们分成不同的文件。具体来说,我想在food
中使用典型的层次结构创建一个PYTHONPATH
文件夹:
food/
- __init__.py
- BaseModel.py
- Taco.py
- Spaghetti.py
- db/
- food.db
我想将模型放入各自的.py
文件中,并拥有一个__init__.py
文件,如下所示:
import peewee as pw
db = pw.SqliteDatabase('./db/food.db')
from . import BaseModel
from . import Taco
from . import Spaghetti
db.connect()
但是,这显然无效,因为BaseModel.py
无法访问db
。如果能够以这种方式模块化多个peewee模型,那么这样做的正确方法是什么?
答案 0 :(得分:2)
显然,技巧是连接到BaseModel.py
文件中的数据库。我将概述模块内容。假设顶级文件夹名为food
并且位于PYTHONPATH
中。最后假设food.db
中存在food/db/food.db
并且已填充(例如,如问题中第一个代码块的底部)。
以下是模块文件:
__初始化__。PY
from Taco import Taco
from Spaghetti import Spaghetti
BaseModel.py
import peewee as pw
db = pw.SqliteDatabase('/abs/path/to/food/db/food.db')
class BaseModel(pw.Model):
class Meta:
database = db
Taco.py
import peewee as pw
from BaseModel import BaseModel
class Taco(BaseModel):
has_cheese = pw.BooleanField()
Spaghetti.py
import peewee as pw
from BaseModel import BaseModel
class Spaghetti(BaseModel):
has_meatballs = pw.BooleanField()
现在,例如,您可以编写一个脚本(当然位于模块文件夹之外),例如:
main.py
import food
for t in food.Taco.select():
print "Taco", t.id, ("has" if t.has_cheese else "doesn't have"), "cheese"
产生
Taco 1 has cheese
Taco 2 has cheese
Taco 3 has cheese
Taco 4 doesn't have cheese
Taco 5 doesn't have cheese
Taco 6 has cheese
Taco 7 has cheese
Taco 8 has cheese
Taco 9 doesn't have cheese
Taco 10 doesn't have cheese
答案 1 :(得分:0)
您在路径中遇到问题:
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
db = pw.SqliteDatabase(os.path.join(__location__, 'db/food.db'));
还尝试实现__init__
个类并将db
作为参数传递给它:
class BaseModel(pw.Model):
def __init__(self, db = None)
self.database = db
而不是__init__.py
:
from BaseModel import BaseModel
db = pw.SqliteDatabase('./db/food.db')
bm = BaseModel(db)
答案 2 :(得分:0)
有关使用peewee模块化烧瓶应用程序的说明,请参阅此文章:
http://charlesleifer.com/blog/structuring-flask-apps-a-how-to-for-those-coming-from-django/