Flask Documentation (1.1.x)
and Context Keeping the Context Around Accessing and Modifying Sessions Testing JSON APIs Testing CLI Commands Application Errors Error Logging Tools Error handlers Logging Debugging Application Errors Blueprint Objects Incoming Request Data Response Objects Sessions Session Interface Test Client Test CLI Runner Application Globals Useful Functions and Classes Message Flashing JSON Support Template Rendering response is sent. flaskr/db.py import sqlite3 import click from flask import current_app, g from flask.cli import with_appcontext def get_db(): if 'db' not in g: g.db = sqlite3.connect(0 码力 | 428 页 | 895.98 KB | 1 年前3Flask Documentation (1.1.x)
Listing 4: flaskr/db.py import sqlite3 import click from flask import current_app, g from flask.cli import with_appcontext def get_db(): if 'db' not in g: g.db = sqlite3.connect( current_app.config['DATABASE'] teardown_appcontext(close_db) app.cli.add_command(init_db_command) app.teardown_appcontext() tells Flask to call that function when cleaning up after returning the response. app.cli.add_command() adds a new command page) def client(app): return app.test_client() @pytest.fixture def runner(app): return app.test_cli_runner() tempfile.mkstemp() creates and opens a temporary file, returning the file object and the0 码力 | 291 页 | 1.25 MB | 1 年前3Flask入门教程
Shell 都会使用这个命令打开。 和 flask shell 类似,我们可以编写一个自定义命令来自动执行创建数据库表操 作: 第 5 章:数据库 39 import click @app.cli.command() # 注册为命令 @click.option('--drop', is_flag=True, help='Create after drop.') # 设置选项 def Watchlist 生成虚拟数据 因为有了数据库,我们可以编写一个命令函数把虚拟数据添加到数据库里。下面是 用来生成虚拟数据的命令函数: 第 5 章:数据库 44 import click @app.cli.command() def forge(): """Generate fake data.""" db.create_all() # 全局的两个变量移动到这个函数内 因为程序只允许一个人使用,没有必要编写一个注册页面。我们可以编写一个命令 来创建管理员账户,下面是实现这个功能的 admin() 函数: 第 8 章:用户认证 74 import click @app.cli.command() @click.option('--username', prompt=True, help='The username used to login.') @click.option('--password'0 码力 | 127 页 | 7.62 MB | 1 年前3
共 3 条
- 1