步骤4:数据库连接

You currently have a function for establishing a database connection with connect_db, but by itself, it is not particularly useful. Creating and closing database connections all the time is very inefficient, so you will need to keep it around for longer. Because database connections encapsulate a transaction, you will need to make sure that only one request at a time uses the connection. 实现这一点的一个优雅的方式是利用应用的上下文

Flask提供了两种上下文:应用上下文请求上下文暂且,你只需要知道不同上下文有不同的特殊变量。例如,request 变量与当前请求的请求对象有关, 而 g 是与当前应用上下文有关的通用变量。本教程会在后面更详细地讨论这些内容。

For the time being, all you have to know is that you can store information safely on the g object.

那么你何时把数据库连接存放到它上面?To do that you can make a helper function. 这个函数 首次调用的时候会为当前环境创建一个数据库连接,后继调用返回已经建 立好的连接:

def get_db():
    """Opens a new database connection if there is none yet for the
    current application context.
    """
    if not hasattr(g, 'sqlite_db'):
        g.sqlite_db = connect_db()
    return g.sqlite_db

Now you know how to connect, but how can you properly disconnect? For that, Flask provides us with the teardown_appcontext() decorator. It’s executed every time the application context tears down:

@app.teardown_appcontext
def close_db(error):
    """Closes the database again at the end of the request."""
    if hasattr(g, 'sqlite_db'):
        g.sqlite_db.close()

Functions marked with teardown_appcontext() are called every time the app context tears down. What does this mean? Essentially, the app context is created before the request comes in and is destroyed (torn down) whenever the request finishes. 销毁有两种原因:一切正常(错误参数会是None)或发生异常,后者情况中,错误会被传递给销毁时函数。

Curious about what these contexts mean? Have a look at the The Application Context documentation to learn more.

阅读步骤5:创建数据库以继续。

Hint

Where do I put this code?

If you’ve been following along in this tutorial, you might be wondering where to put the code from this step and the next. A logical place is to group these module-level functions together, and put your new get_db and close_db functions below your existing connect_db function (following the tutorial line-by-line).

如果你需要来找准定位,可以看一下示例源码是怎么组织的。In Flask, you can put all of your application code into a single Python module. 但你无需这么做,而且在你的应用规模扩大以后,这显然不妥。