Skip to content
Myr

Modify extensionsdev documentation.

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

authored by Matt Dawson · committed by Matt Dawson · parent fbd4886 · 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

1 file+80 added−45 removed

modified:docs/extensiondev.rst+80 added-45 removed
135 unmodified lines
136Now this is where your extension code goes. But how exactly should such137an extension look like? What are the best practices? Continue reading138for some insight.139140140Initializing Extensions141-----------------------142143Many extensions will need some kind of initialization step. For example,
19 unmodified lines
163 some helper functions like `OAuth.remote_app` to create a reference to164 a remote application that uses OAuth.165166What to use depends on what you have in mind. For the SQLite 3 extension168we will need to use the class based approach because we have to use a169controller object that can be used to connect to the database.167we will use the class based approach because it will provide users with a168manager object that handles opening and closing database connections.169170The Extension Code171------------------172173Here's the contents of the `flaskext/sqlite3.py` for copy/paste::174175 from __future__ import absolute_import176 import sqlite3178 from flask import g177178 from flask import _request_ctx_stack179180 class SQLite3(object):181 181182 def __init__(self, app):183 self.app = app184 self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')185186 self.app.before_request(self.before_request)185 self.app.after_request(self.after_request)186 self.app.before_request(self.before_request)187188 def connect(self):189 return sqlite3.connect(self.app.config['SQLITE3_DATABASE'])190191 def before_request(self):192 ctx = _request_ctx_stack.top193 g.sqlite3_db = self.connect()193 ctx.sqlite3_db = self.connect()194195 def after_request(self, response):196 ctx = _request_ctx_stack.top196 g.sqlite3_db.close()197 ctx.sqlite3_db.close()198 return response199199So 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_db2042011. 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.2052. 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.2083. Then it implements a `connect` function that returns a new database209 connection and the two handlers.205So here's what these lines of code do:2062071. 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.2112. 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.2153. Next, we define a `connect` function that opens a database connection.2164. 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.2205. Finally, we add a `get_db` function that simplifies access to the context's221 database.222211So why did we decide on a class based approach here? Because using that223So why did we decide on a class based approach here? Because using our224extension looks something like this::225214 from flask import Flask, g226 from flask import Flask227 from flaskext.sqlite3 import SQLite3228229 app = Flask(__name__)230 app.config.from_pyfile('the-config.cfg')219 db = SQLite(app)231 manager = SQLite3(app)232 db = manager.get_db()233221Either way you can use the database from the views like this::234You can then use the database from views like this::235236 @app.route('/')237 def show_all():225 cur = g.sqlite3_db.cursor()238 cur = db.cursor()239 cur.execute(...)240228But how would you open a database connection from outside a view function?229This is where the `db` object now comes into play:241Opening a database connection from outside a view function is simple.242243>>> from yourapplication import db232>>> con = db.connect()233>>> cur = con.cursor()244>>> cur = db.cursor()245>>> cur.execute(...)246235If you don't need that, you can go with initialization functions.247Adding an `init_app` Function248-----------------------------249237Initialization Functions238------------------------250In practice, you'll almost always want to permit users to initialize your251extension and provide an app object after the fact. This can help avoid252circular import problems when a user is breaking their app into multiple files.253Our extension could add an `init_app` function as follows::254240Here's what the module would look like with initialization functions::255 class SQLite3(object):256242 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 = None263246 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)269250 @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'])272254 @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()276277 def after_request(self, response):278 ctx = _request_ctx_stack.top279 ctx.sqlite3_db.close()280 return response281282 def get_db(self):283 ctx = _request_ctx_stack.top284 if ctx is not None:285 return ctx.sqlite3_db286287The user could then initialize the extension in one file::288289 manager = SQLite3()290291and bind their app to the extension in another file::292293 manager.init_app(app)294295Learn from Others296-----------------297298This documentation only touches the bare minimum for extension
12 unmodified lines
311312The best Flask extensions are extensions that share common idioms for the313API. And this can only work if collaboration happens early.314279315Approved Extensions316-------------------317318Flask also has the concept of approved extensions. Approved extensions
44 unmodified lines