Python 烧瓶+;Peewee:在哪里创建表?

Python 烧瓶+;Peewee:在哪里创建表?,python,flask,peewee,Python,Flask,Peewee,我使用的不是flask-peewee而是普通的peewee包 以下是我初始化数据库的方式: import os # just extending the BaseFlask with yaml config reader from . extensions.flask_app import Flask # peewee's wrapper around the database from playhouse.flask_utils import FlaskDB db_wrapper =

我使用的不是flask-peewee而是普通的peewee

以下是我初始化数据库的方式:

import os

# just extending the BaseFlask with yaml config reader
from . extensions.flask_app import Flask

# peewee's wrapper around the database
from playhouse.flask_utils import FlaskDB


db_wrapper = FlaskDB() 


# define the application factory
def create_app(env):

    app = Flask(__name__)

    # load config depending on the environment
    app.config.from_yaml(os.path.join(app.root_path, 'config.yml'), env)

    # init extensions
    db_wrapper.init_app(app)

    # ...
我知道我应该调用此函数来创建表:

from . models import User

db_wrapper.database.connect()
db_wrapper.database.create_tables([User])
但是我应该把表创建代码放在哪里,这样数据库就已经初始化了

编辑

查看后,我发现我可以使用
User.create\u表(fail\u静默=True)
如下所示:

# in app/__init__.py

# define the application factory
def create_app(env):

    app = Flask(__name__)

    # load config depending on the environment
    app.config.from_yaml(os.path.join(app.root_path, 'config.yml'), env)

    # init extensions
    db_wrapper.init_app(app)

    create_tables();

    # rest of the initialization

def create_tables():

    from . models import User    
    User.create_table(fail_silently=True)
在这里可以吗?还是有更好的方法/工具

编辑


我明白了。请看下面我的答案。

更新

我不知道Flask中内置的CLI支持。我不知道你是否应该考虑这样的方法,因为你可以把事情做出来(见)。
我可以使用flask脚本包。我以前做过,只是忽略了它

激活您的虚拟环境跑步

pip安装烧瓶脚本

然后在根目录中创建manage.py文件,添加以下行:

import os
from app import create_app, db_wrapper
from app.models import *
from flask_script import Manager, Shell

# create the application instance    
app = create_app(os.getenv('FLASK_ENV', 'development'))

# instantiate script manager
manager = Manager(app)

def make_shell_context():
    return dict(app=app, db_wrapper=db_wrapper, User=User)


@manager.command
def run_shell():
    Shell(make_context = make_shell_context).run(no_ipython=True, no_bpython=True)


# here's my simple command
@manager.command
def create_tables():
    User.create_table(fail_silently=True)


@manager.command
def run_tests():
    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(tests)


# run it
if __name__ == '__main__':
    manager.run()

确保在创建表后清理连接@coleifer你的意思是我需要调用
db.close()
db.open()
?db.close()--虽然有db.connect(),但没有db.open()。无需调用connect(),因为第一次尝试在封闭数据库上执行查询时会调用它。当然,我认为显式地调用connect()是好的,但严格来说并不是必需的。@coleifer好的,明白了。非常感谢。