如何使用 Peewee 拆分文件中的模型声明

How to split model declaration in files with Peewee

我想将定义数据库中模型的代码拆分到不同的 Python 文件中,以使我的项目更加结构化。

可悲的是,我最终遇到了一个包含循环,并且出现了一个错误,因为某些东西没有在应该初始化的时候初始化。

我现在已经做了这样的事情(简体):


# In file file_database.py

import peewee as pw

from tables import Table1, Table2, Table3

DATABASE_PATH = ...
MY_DB = pw.SqliteDatabase(DATABASE_PATH)

def make_tables():
    """Make the tables in the database if they don't already exist."""
    MY_DB.create_tables([Table1, Table2, Table3]) # Problem happens here

# Create the database file if it doesn't already exist
if not DATABASE_PATH.exists():
    LOGGER.info("The database doesn't exists. Creating it...")
    make_tables()

# In file tables.py

import peewee as pw

from file_database import MY_DB

class BaseModel(pw.Model):
    class Meta:
        database = MY_DB

class Table1(BaseModel):
    name = ...

class Table2(BaseModel):
    name = ...

class Table3(BaseModel):
    name = ...

我有一个例外: ImportError: cannot import name 'Table1' 这似乎是合乎逻辑的,因为函数 makeTables 需要先从 tables.py 导入表。 但是这个需要 file_database.py.

的数据库

所以我被困在这里了。 我还尝试将 from tables import Table1, Table2, Table3 放在 makeTables 函数中以尝试进行某种延迟加载,但没有成功。

有人帮忙吗?谢谢。

您创建了第三个模块,它引入了这两个模块并协调了导入顺序。

这里详细介绍了大致的流程:

http://charlesleifer.com/blog/structuring-flask-apps-a-how-to-for-those-coming-from-django/

不错的教程,虽然还没有完全理解,但这里有一个有效的代码:

database/__init__.py

import database.tables
from database import file_database

file_database.initialization()

database/tables.py

import peewee as pw

MY_DB = pw.SqliteDatabase(None) # Create a blank database here

class BaseModel(pw.Model):
    class Meta:
        database = MY_DB

class Table1(BaseModel):
    name = ...

class Table2(BaseModel):
    name = ...

class Table3(BaseModel):
    name = ...

database/file_database.py

import peewee as pw

from database.tables import MY_DB, Table1, Table2, Table3

DATABASE_PATH = ...

def make_tables():
    """Make the tables in the database"""
    MY_DB.create_tables([Table1, Table2, Table3])

def initialization():
    MY_DB.init(DATABASE_PATH) # Actually init the database

    # Create the database file if it doesn't already exist
    if not DATABASE_PATH.exists():
        LOGGER.info("The database doesn't exists. Creating it...")
        make_tables()