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