Merge pull request #440 from jamesls/extension-docs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Reword the docs for writing a flask extension
authored by Ron DuPlain · committed by Ron DuPlain · parents d94efc6, 8d1546f · Browse files · 1 file·+49 added−70 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+49 added−70 removed
- other:+49 added−70 removed
Provenance
- Commit
a5d1cf4- Tree
7e193e7- Author
Ron DuPlain <ron.duplain@gmail.com>- Committer
Ron DuPlain <ron.duplain@gmail.com>- Parent 1
d94efc6- Parent 2
8d1546f
1 file changed+49 added−70 removed
modified:docs/extensiondev.rst+49 added-70 removed
123 unmodified lines124 Initializing Extensions125 -----------------------126 127 Many extensions will need some kind of initialization step. For example,128-consider your application is currently connecting to SQLite like the129-documentation suggests (:ref:`sqlite3`) you will need to provide a few130-functions and before / after request handlers. So how does the extension128+consider an application that's currently connecting to SQLite like the129+documentation suggests (:ref:`sqlite3`). So how does the extension130 know the name of the application object?131 132 Quite simple: you pass it to it.133 134 There are two recommended ways for an extension to initialize:135 136 initialization functions:137+138 If your extension is called `helloworld` you might have a function139 called ``init_helloworld(app[, extra_args])`` that initializes the140 extension for that application. It could attach before / after141 handlers etc.142 143 classes:144+145 Classes work mostly like initialization functions but can later be146 used to further change the behaviour. For an example look at how the147 `OAuth extension`_ works: there is an `OAuth` object that provides148 some helper functions like `OAuth.remote_app` to create a reference to149 a remote application that uses OAuth.150 151 What to use depends on what you have in mind. For the SQLite 3 extension151-we will use the class-based approach because it will provide users with a152-manager object that handles opening and closing database connections.152+we will use the class-based approach because it will provide users with an153+object that handles opening and closing database connections.154 155 The Extension Code156 ------------------157 158 Here's the contents of the `flask_sqlite3.py` for copy/paste::159 159- from __future__ import absolute_import160 import sqlite3161 162 from flask import _request_ctx_stack163 164+165 class SQLite3(object):166 166- def __init__(self, app):167+ def __init__(self, app=None):168+ if app is not None:169+ self.app = app170+ self.init_app(self.app)171+ else:172+ self.app = None173+174+ def init_app(self, app):175 self.app = app176 self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')177 self.app.teardown_request(self.teardown_request)178 self.app.before_request(self.before_request)8 unmodified lines187 def teardown_request(self, exception):188 ctx = _request_ctx_stack.top189 ctx.sqlite3_db.close()190 183- def get_db(self):191+ @property192+ def connection(self):193 ctx = _request_ctx_stack.top194 if ctx is not None:195 return ctx.sqlite3_db196 197+198 So here's what these lines of code do:199 190-1. The ``__future__`` import is necessary to activate absolute imports.191- Otherwise we could not call our module `sqlite3.py` and import the192- top-level `sqlite3` module which actually implements the connection to193- SQLite.194-2. We create a class for our extension that requires a supplied `app` object,195- sets a configuration for the database if it's not there196- (:meth:`dict.setdefault`), and attaches `before_request` and197- `teardown_request` handlers.198-3. Next, we define a `connect` function that opens a database connection.200+1. The ``__init__`` method takes an optional app object and, if supplied, will201+ call ``init_app``.202+2. The ``init_app`` method exists so that the ``SQLite3`` object can be203+ instantiated without requiring an app object. This method supports the204+ factory pattern for creating applications. The ``init_app`` will set the205+ configuration for the database, defaulting to an in memory database if206+ no configuration is supplied. In addition, the ``init_app`` method attaches207+ ``before_request`` and ``teardown_request`` handlers.208+3. Next, we define a ``connect`` method that opens a database connection.209 4. Then we set up the request handlers we bound to the app above. Note here210 that we're attaching our database connection to the top request context via201- `_request_ctx_stack.top`. Extensions should use the top context and not the202- `g` object to store things like database connections.203-5. Finally, we add a `get_db` function that simplifies access to the context's211+ ``_request_ctx_stack.top``. Extensions should use the top context and not the212+ ``g`` object to store things like database connections.213+5. Finally, we add a ``connection`` property that simplifies access to the context's214 database.215 216 So why did we decide on a class-based approach here? Because using our217 extension looks something like this::2 unmodified lines220 from flask_sqlite3 import SQLite3221 222 app = Flask(__name__)223 app.config.from_pyfile('the-config.cfg')214- manager = SQLite3(app)215- db = manager.get_db()224+ db = SQLite3(app)225 226 You can then use the database from views like this::227 228 @app.route('/')229 def show_all():221- cur = db.cursor()230+ cur = db.connection.cursor()231 cur.execute(...)232 224-Opening a database connection from outside a view function is simple.233+Additionally, the ``init_app`` method is used to support the factory pattern234+for creating apps::235 226->>> from yourapplication import db227->>> cur = db.cursor()228->>> cur.execute(...)236+ db = Sqlite3()237+ # Then later on.238+ app = create_app('the-config.cfg')239+ db.init_app(app)240 230-Adding an `init_app` Function231------------------------------241+Keep in mind that supporting this factory pattern for creating apps is required242+for approved flask extensions (described below).243 233-In practice, you'll almost always want to permit users to initialize your234-extension and provide an app object after the fact. This can help avoid235-circular import problems when a user is breaking their app into multiple files.236-Our extension could add an `init_app` function as follows::244 238- class SQLite3(object):245+Using _request_ctx_stack246+------------------------247 240- def __init__(self, app=None):241- if app is not None:242- self.app = app243- self.init_app(self.app)244- else:245- self.app = None248+In the example above, before every request, a ``sqlite3_db`` variable is assigned249+to ``_request_ctx_stack.top``. In a view function, this variable is accessible250+using the ``connection`` property of ``SQLite3``. During the teardown of a251+request, the ``sqlite3_db`` connection is closed. By using this pattern, the252+*same* connection to the sqlite3 database is accessible to anything that needs it253+for the duration of the request.254 247- def init_app(self, app):248- self.app = app249- self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')250- self.app.teardown_request(self.teardown_request)251- self.app.before_request(self.before_request)252-253- def connect(self):254- return sqlite3.connect(app.config['SQLITE3_DATABASE'])255-256- def before_request(self):257- ctx = _request_ctx_stack.top258- ctx.sqlite3_db = self.connect()259-260- def teardown_request(self, exception):261- ctx = _request_ctx_stack.top262- ctx.sqlite3_db.close()263-264- def get_db(self):265- ctx = _request_ctx_stack.top266- if ctx is not None:267- return ctx.sqlite3_db268-269-The user could then initialize the extension in one file::270-271- manager = SQLite3()272-273-and bind their app to the extension in another file::274-275- manager.init_app(app)276-255 End-Of-Request Behavior256 -----------------------257 258 Due to the change in Flask 0.7 regarding functions that are run at the end10 unmodified lines269 app.teardown_request(close_connection)270 else:271 app.after_request(close_connection)272 273+274 Strictly speaking the above code is wrong, because teardown functions are275 passed the exception and typically don't return anything. However because276 the return value is discarded this will just work assuming that the code277 in between does not touch the passed parameter.93 unmodified lines