2017-03-17 77 views
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) 

它是正常的,在這裏做嗎?還是有更好的方法/工具呢?

編輯

想通了。請看下面的答案。

回答

0

更新

我不知道在內置CLI支持。我不知道你是否應該考慮這種方法,因爲你可以開箱即用(見documntation)。


我可以利用燒瓶腳本包。我之前做過,只是忽略了它。

激活您的虛擬環境運行

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() 
+0

爲什麼使用Flask-Script? Flask已經提供了一年以上的內置CLI。只需使用'@ app.cli.command'添加一個自定義命令。 – davidism

+0

@davidism我不知道這一點。謝謝指點我。我會檢查一下。 – lexeme

+0

創建表格後務必清理連接! – coleifer