forked from orbit-oss/flask
Updated examples to new sqlite patterns and added new section to appcontext docs
This commit is contained in:
parent
3e9f4e254b
commit
c2e5799879
4 changed files with 169 additions and 104 deletions
|
|
@ -85,3 +85,47 @@ Extensions are free to store additional information on the topmost level,
|
|||
assuming they pick a sufficiently unique name.
|
||||
|
||||
For more information about that, see :ref:`extension-dev`.
|
||||
|
||||
Context Usage
|
||||
-------------
|
||||
|
||||
The context is typically used to cache resources on there that need to be
|
||||
created on a per-request or usage case. For instance database connects
|
||||
are destined to go there. When storing things on the application context
|
||||
unique names should be chosen as this is a place that is shared between
|
||||
Flask applications and extensions.
|
||||
|
||||
The most common usage is to split resource management into two parts:
|
||||
|
||||
1. an implicit resource caching on the context.
|
||||
2. a context teardown based resource deallocation.
|
||||
|
||||
Generally there would be a ``get_X()`` function that creates resource
|
||||
``X`` if it does not exist yet and otherwise returns the same resource,
|
||||
and a ``teardown_X()`` function that is registered as teardown handler.
|
||||
|
||||
This is an example that connects to a database::
|
||||
|
||||
import sqlite3
|
||||
from flask import _app_ctx_stack
|
||||
|
||||
def get_db():
|
||||
top = _app_ctx_stack.top
|
||||
if not hasattr(top, 'database'):
|
||||
top.database = connect_to_database()
|
||||
return top.database
|
||||
|
||||
@app.teardown_appcontext
|
||||
def teardown_db(exception):
|
||||
top = _app_ctx_stack.top
|
||||
if hasattr(top, 'database'):
|
||||
top.database.close()
|
||||
|
||||
The first time ``get_db()`` is called the connection will be established.
|
||||
To make this implicit a :class:`~werkzeug.local.LocalProxy` can be used::
|
||||
|
||||
from werkzeug.local import LocalProxy
|
||||
db = LocalProxy(get_db)
|
||||
|
||||
That way a user can directly access ``db`` which internally calls
|
||||
``get_db()``.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue