步骤5:创建数据库

As outlined earlier, Flaskr is a database powered application, and more precisely, it is an application powered by a relational database system. 关系数据库系统需要一个模式来决定存储信息的方式。Before starting the server for the first time, it’s important to create that schema.

可以通过管道把schema.sql作为sqlite3命令的输入来创建这个模式,命令为如下:

sqlite3 /tmp/flaskr.db < schema.sql

这种方法的缺点是需要安装sqlite3命令,而并不是每个系统都有安装。This also requires that you provide the path to the database, which can introduce errors. It’s a good idea to add a function that initializes the database for you, to the application.

要这么做,我们可以创建一个函数给flask命令来初始化数据库。For now just take a look at the code segment below. 添加这个函数和命令的好地方,就是在flaskr.py文件的connect_db函数下方:

def init_db():
    db = get_db()
    with app.open_resource('schema.sql', mode='r') as f:
        db.cursor().executescript(f.read())
    db.commit()

@app.cli.command('initdb')
def initdb_command():
    """Initializes the database."""
    init_db()
    print('Initialized the database.')

app.cli.command()装饰器注册一个新的命令到flask脚本中。当命令执行时,Flask将自动创建应用上下文绑定到正确的应用。在函数中,可以访问flask.g和其它你可能期望的东西。当脚本结束后时,应用上下文销毁并释放数据库连接。

然而,你将希望保留初始化数据库的实际函数,这样我们稍后可以在单元测试中轻松地创建数据库。(详细信息见测试Flask应用)。

The open_resource() method of the application object is a convenient helper function that will open a resource that the application provides. 这个函数从资源所在位置( flaskr/flaskr文件夹)打开文件,并允许你读取它。It is used in this example to execute a script on the database connection.

The connection object provided by SQLite can give you a cursor object. On that cursor, there is a method to execute a complete script. Finally, you only have to commit the changes. SQLite3 and other transactional databases will not commit unless you explicitly tell it to.

现在,可以用flask脚本来创建数据库了:

flask initdb
Initialized the database.

故障排除:

如果你遇到了表无法找到的异常,请检查你是否确实调用过initdb函数并且表的名称是正确的(比如弄混了单数和复数)。

继续步骤6︰ 视图函数