Merge remote branch 'mattd/extensions-docs'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parents 6758179, c1c20ac · Browse files · 1 file·+80 added−45 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+80 added−45 removed
- other:+80 added−45 removed
Provenance
- Commit
fd0862c- Tree
37fe5e5- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent 1
6758179- Parent 2
c1c20ac
1 file changed+80 added−45 removed
modified:docs/extensiondev.rst+80 added-45 removed
135 unmodified lines136 Now this is where your extension code goes. But how exactly should such137 an extension look like? What are the best practices? Continue reading138 for some insight.139 140-140 Initializing Extensions141 -----------------------142 143 Many extensions will need some kind of initialization step. For example,19 unmodified lines163 some helper functions like `OAuth.remote_app` to create a reference to164 a remote application that uses OAuth.165 166 What to use depends on what you have in mind. For the SQLite 3 extension168-we will need to use the class based approach because we have to use a169-controller object that can be used to connect to the database.167+we will use the class based approach because it will provide users with a168+manager object that handles opening and closing database connections.169 170 The Extension Code171 ------------------172 173 Here's the contents of the `flaskext/sqlite3.py` for copy/paste::174 175 from __future__ import absolute_import176 import sqlite3178- from flask import g177 178+ from flask import _request_ctx_stack179+180 class SQLite3(object):181- 181+182 def __init__(self, app):183 self.app = app184 self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')185-186- self.app.before_request(self.before_request)185 self.app.after_request(self.after_request)186+ self.app.before_request(self.before_request)187 188 def connect(self):189 return sqlite3.connect(self.app.config['SQLITE3_DATABASE'])190 191 def before_request(self):192+ ctx = _request_ctx_stack.top193- g.sqlite3_db = self.connect()193+ ctx.sqlite3_db = self.connect()194 195 def after_request(self, response):196+ ctx = _request_ctx_stack.top196- g.sqlite3_db.close()197+ ctx.sqlite3_db.close()198 return response199 199-So here's what the lines of code do:200+ def get_db(self):201+ ctx = _request_ctx_stack.top202+ if ctx is not None:203+ return ctx.sqlite3_db204 201-1. the ``__future__`` import is necessary to activate absolute imports.202- This is needed because otherwise we could not call our module203- `sqlite3.py` and import the top-level `sqlite3` module which actually204- implements the connection to SQLite.205-2. We create a class for our extension that sets a default configuration206- for the SQLite 3 database if it's not there (:meth:`dict.setdefault`)207- and connects two functions as before and after request handlers.208-3. Then it implements a `connect` function that returns a new database209- connection and the two handlers.205+So here's what these lines of code do:206 207+1. The ``__future__`` import is necessary to activate absolute imports.208+ Otherwise we could not call our module `sqlite3.py` and import the209+ top-level `sqlite3` module which actually implements the connection to210+ SQLite.211+2. We create a class for our extension that requires a supplied `app` object,212+ sets a configuration for the database if it's not there213+ (:meth:`dict.setdefault`), and attaches `before_request` and214+ `after_request` handlers.215+3. Next, we define a `connect` function that opens a database connection.216+4. Then we set up the request handlers we bound to the app above. Note here217+ that we're attaching our database connection to the top request context via218+ `_request_ctx_stack.top`. Extensions should use the top context and not the219+ `g` object to store things like database connections.220+5. Finally, we add a `get_db` function that simplifies access to the context's221+ database.222+211-So why did we decide on a class based approach here? Because using that223+So why did we decide on a class based approach here? Because using our224 extension looks something like this::225 214- from flask import Flask, g226+ from flask import Flask227 from flaskext.sqlite3 import SQLite3228 229 app = Flask(__name__)230 app.config.from_pyfile('the-config.cfg')219- db = SQLite(app)231+ manager = SQLite3(app)232+ db = manager.get_db()233 221-Either way you can use the database from the views like this::234+You can then use the database from views like this::235 236 @app.route('/')237 def show_all():225- cur = g.sqlite3_db.cursor()238+ cur = db.cursor()239 cur.execute(...)240 228-But how would you open a database connection from outside a view function?229-This is where the `db` object now comes into play:241+Opening a database connection from outside a view function is simple.242 243 >>> from yourapplication import db232->>> con = db.connect()233->>> cur = con.cursor()244+>>> cur = db.cursor()245+>>> cur.execute(...)246 235-If you don't need that, you can go with initialization functions.247+Adding an `init_app` Function248+-----------------------------249 237-Initialization Functions238-------------------------250+In practice, you'll almost always want to permit users to initialize your251+extension and provide an app object after the fact. This can help avoid252+circular import problems when a user is breaking their app into multiple files.253+Our extension could add an `init_app` function as follows::254 240-Here's what the module would look like with initialization functions::255+ class SQLite3(object):256 242- from __future__ import absolute_import243- import sqlite3244- from flask import g257+ def __init__(self, app=None):258+ if app is not None:259+ self.app = app260+ self.init_app(self.app)261+ else:262+ self.app = None263 246- def init_sqlite3(app):247- app = app248- app.config.setdefault('SQLITE3_DATABASE', ':memory:')264+ def init_app(self, app):265+ self.app = app266+ self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')267+ self.app.after_request(self.after_request)268+ self.app.before_request(self.before_request)269 250- @app.before_request251- def before_request():252- g.sqlite3_db = sqlite3.connect(self.app.config['SQLITE3_DATABASE'])270+ def connect(self):271+ return sqlite3.connect(app.config['SQLITE3_DATABASE'])272 254- @app.after_request255- def after_request(response):256- g.sqlite3_db.close()273+ def before_request(self):274+ ctx = _request_ctx_stack.top275+ ctx.sqlite3_db = self.connect()276+277+ def after_request(self, response):278+ ctx = _request_ctx_stack.top279+ ctx.sqlite3_db.close()280 return response281 282+ def get_db(self):283+ ctx = _request_ctx_stack.top284+ if ctx is not None:285+ return ctx.sqlite3_db286+287+The user could then initialize the extension in one file::288+289+ manager = SQLite3()290+291+and bind their app to the extension in another file::292+293+ manager.init_app(app)294+295 Learn from Others296 -----------------297 298 This documentation only touches the bare minimum for extension12 unmodified lines311 312 The best Flask extensions are extensions that share common idioms for the313 API. And this can only work if collaboration happens early.314 279-315 Approved Extensions316 -------------------317 318 Flask also has the concept of approved extensions. Approved extensions44 unmodified lines