gpt4 book ai didi

python - 模块化 peee

转载 作者:行者123 更新时间:2023-12-01 04:15:31 29 4
gpt4 key购买 nike

假设我有几个简单的模型驻留在 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.pyfood.db。但假设 TacoSpaghetti 模型变得庞大且复杂,因此我想将它们拆分为不同的文件。具体来说,我想在我的 PYTHONPATH 中创建一个具有典型层次结构的 food 文件夹:

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 模型,那么正确的方法是什么?

最佳答案

显然,技巧是连接到 BaseModel.py 文件中的数据库。我将给出模块内容的完整概述。假设顶级文件夹名为 food 并位于 PYTHONPATH 中。最后假设 food.db 存在于 food/db/food.db 中并且已被填充(例如,如问题中第一个代码块的底部所示) 。

以下是模块文件:

__init__.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

关于python - 模块化 peee,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34344556/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com