2017-03-17 78 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