Skip to content
Myr

Reword the docs for writing a flask extension

Before adoption: this commit came in with the history the project adopted, so no landing records it.

There was a minor bug in the example extension that's been fixed. I also updated the description of the fixed code accordingly, and expanded on the usage of _request_ctx_stack.top for adding data that should be accesible to view functions. I verified that the existing code as is works as expected.

authored by James Saryerwinnie · committed by James Saryerwinnie · parent 7ed3cba · 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

1 file+49 added−70 removed

modified:docs/extensiondev.rst+49 added-70 removed
123 unmodified lines
124Initializing Extensions125-----------------------126127Many extensions will need some kind of initialization step. For example,128consider your application is currently connecting to SQLite like the129documentation suggests (:ref:`sqlite3`) you will need to provide a few130functions and before / after request handlers. So how does the extension128consider an application that's currently connecting to SQLite like the129documentation suggests (:ref:`sqlite3`). So how does the extension130know the name of the application object?131132Quite simple: you pass it to it.133134There are two recommended ways for an extension to initialize:135136initialization functions:137138 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.142143classes:144145 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.150151What to use depends on what you have in mind. For the SQLite 3 extension151we will use the class-based approach because it will provide users with a152manager object that handles opening and closing database connections.152we will use the class-based approach because it will provide users with an153object that handles opening and closing database connections.154155The Extension Code156------------------157158Here's the contents of the `flask_sqlite3.py` for copy/paste::159159 from __future__ import absolute_import160 import sqlite3161162 from flask import _request_ctx_stack163164165 class SQLite3(object):166166 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 = None173174 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 lines
187 def teardown_request(self, exception):188 ctx = _request_ctx_stack.top189 ctx.sqlite3_db.close()190183 def get_db(self):191 @property192 def connection(self):193 ctx = _request_ctx_stack.top194 if ctx is not None:195 return ctx.sqlite3_db196197198So here's what these lines of code do:1991901. 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.1942. 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.1983. Next, we define a `connect` function that opens a database connection.2001. The ``__init__`` method takes an optional app object and, if supplied, will201 call ``init_app``.2022. 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.2083. Next, we define a ``connect`` method that opens a database connection.2094. 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.2035. 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.2135. Finally, we add a ``connection`` property that simplifies access to the context's214 database.215216So why did we decide on a class-based approach here? Because using our217extension looks something like this::
2 unmodified lines
220 from flask_sqlite3 import SQLite3221222 app = Flask(__name__)223 app.config.from_pyfile('the-config.cfg')214 manager = SQLite3(app)215 db = manager.get_db()224 db = SQLite3(app)225226You can then use the database from views like this::227228 @app.route('/')229 def show_all():221 cur = db.cursor()230 cur = db.connection.cursor()231 cur.execute(...)232224Opening a database connection from outside a view function is simple.233Additionally, the ``init_app`` method is used to support the factory pattern234for creating apps::235226>>> 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)240230Adding an `init_app` Function231-----------------------------241Keep in mind that supporting this factory pattern for creating apps is required242for approved flask extensions (described below).243233In practice, you'll almost always want to permit users to initialize your234extension and provide an app object after the fact. This can help avoid235circular import problems when a user is breaking their app into multiple files.236Our extension could add an `init_app` function as follows::244238 class SQLite3(object):245Using _request_ctx_stack246------------------------247240 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 = None248In the example above, before every request, a ``sqlite3_db`` variable is assigned249to ``_request_ctx_stack.top``. In a view function, this variable is accessible250using the ``connection`` property of ``SQLite3``. During the teardown of a251request, the ``sqlite3_db`` connection is closed. By using this pattern, the252*same* connection to the sqlite3 database is accessible to anything that needs it253for the duration of the request.254247 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)252253 def connect(self):254 return sqlite3.connect(app.config['SQLITE3_DATABASE'])255256 def before_request(self):257 ctx = _request_ctx_stack.top258 ctx.sqlite3_db = self.connect()259260 def teardown_request(self, exception):261 ctx = _request_ctx_stack.top262 ctx.sqlite3_db.close()263264 def get_db(self):265 ctx = _request_ctx_stack.top266 if ctx is not None:267 return ctx.sqlite3_db268269The user could then initialize the extension in one file::270271 manager = SQLite3()272273and bind their app to the extension in another file::274275 manager.init_app(app)276255End-Of-Request Behavior256-----------------------257258Due to the change in Flask 0.7 regarding functions that are run at the end
10 unmodified lines
269 app.teardown_request(close_connection)270 else:271 app.after_request(close_connection)272273274Strictly speaking the above code is wrong, because teardown functions are275passed the exception and typically don't return anything. However because276the return value is discarded this will just work assuming that the code277in between does not touch the passed parameter.
89 unmodified lines