步骤2:应用设置代码

现在已经有了数据库模式,你可以创建应用的模块,flaskr.py这个文件应该放置在flaskr/flaskr文件夹下。这个应用模块的代码开始几行是必需的import语句。之后是几行配置代码。对于小型的应用如flaskr,可以直接将配置丢在模块里面。然而,更干净的做法是创建一个单独的.ini.py文件,加载它,并从那里导入值。

下面是import语句(位于flaskr.py中):

# all the imports
import os
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, \
     render_template, flash

接下来的几行将创建真实的应用实例,并用来自同一个文件flaskr.py中的配置初始化它:

app = Flask(__name__) # create the application instance :)
app.config.from_object(__name__) # load config from this file , flaskr.py

# Load default config and override config from an environment variable
app.config.update(dict(
    DATABASE=os.path.join(app.root_path, 'flaskr.db'),
    SECRET_KEY='development key',
    USERNAME='admin',
    PASSWORD='default'
))
app.config.from_envvar('FLASKR_SETTINGS', silent=True)

The Config object works similarly to a dictionary, so it can be updated with new values.

Database Path

Operating systems know the concept of a current working directory for each process. Unfortunately, you cannot depend on this in web applications because you might have more than one application in the same process.

For this reason the app.root_path attribute can be used to get the path to the application. Together with the os.path module, files can then easily be found. In this example, we place the database right next to it.

For a real-world application, it’s recommended to use Instance Folders instead.

Usually, it is a good idea to load a separate, environment-specific configuration file. Flask allows you to import multiple configurations and it will use the setting defined in the last import. This enables robust configuration setups. from_envvar() can help achieve this.

app.config.from_envvar('FLASKR_SETTINGS', silent=True)

Simply define the environment variable FLASKR_SETTINGS that points to a config file to be loaded. 启用静默模式告诉 Flask 在没有设置该环境变量的情况下噤声。

In addition to that, you can use the from_object() method on the config object and provide it with an import name of a module. Flask will then initialize the variable from that module. Note that in all cases, only variable names that are uppercase are considered.

SECRET_KEY是保证客户端会话的安全的要点。Choose that key wisely and as hard to guess and complex as possible.

最好,你要添加了一个让连接到指定数据库变得很简单的方法。这个方法用于在请求时开启一个数据库连接,并且在交互式Python shell和脚本中也能使用。这为以后的操作提供了相当的便利。你可以创建一个简单的SQLite数据库的连接,并让它用sqlite3.Row对象表示数据库中的行。这使得我们可以通过字典而不是元组的形式访问行。

def connect_db():
    """Connects to the specific database."""
    rv = sqlite3.connect(app.config['DATABASE'])
    rv.row_factory = sqlite3.Row
    return rv

在下一节,你将看到如何运行这个应用。

请继续步骤3:安装flaskr为一个包