0
而不是烧瓶peewee我使用普通peewee包。Flask + 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])
但我在哪里把表创建代码 ,这样数据库就已经初始化了?
编辑
望着docs我发现我可以使用User.create_table(fail_silently=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-Script? Flask已经提供了一年以上的内置CLI。只需使用'@ app.cli.command'添加一个自定义命令。 – davidism
@davidism我不知道这一点。谢谢指点我。我会检查一下。 – lexeme
创建表格后务必清理连接! – coleifer