Flask实用小技巧

删除表并重建

@app.cli.command()
@click.option('--drop', is_flag=True, help='Create after drop.')
def initdb(drop):
    if drop:
        click.confirm('This operation will delete the database, do you want to continue?', abort=True)
        db.drop_all()
        click.echo('Drop tables.')
    db.create_all()
    click.echo('Initialized database.')

添加到上下文中

使用flask shell 可以直接用,而不需要导入,db, Singer, City

@app.shell_context_processor
def make_shell_context():
    return dict(db=db, Singer=Singer, Song=Song, City=City)

事件监听

如:下面的功能为当Draft.body被修改时,Draft.edit_time会增加1。(四个参数时必须的,参照示例中的代码)

# 写法一
@db.event.listens_for(Draft.body, 'set')
def increment_edit_time(target, value, oldvalue, initiator):
    if target.edit_time is not None:
        target.edit_time += 1 

# 写法二
@db.event.listens_for(Draft.body, 'set', named=True)
def increment_edit_time(**kwargs):
    if kwargs['target'].edit_time is not None:
        kwargs['target'].edit_time += 1 

posted on 2019-08-25 22:15  透明的洪湖里  阅读(194)  评论(0)    收藏  举报