extensiondev.rst
This file
Path
docs/extensiondev.rst
341 lines · 12.9 KiB
Last changed by
Merge branch '1.0.x' into 1.1.xDavid Lordbefore adoptionc42803f
History of this fileTake it
The walk stopped after 200 commits: lines older than d24bb9e point at it.
Merge pull request #2525 from proog/docs-twisted-portDavid Lordbefore adoptiond24bb9e
lines 1–6why, one step back1.. _extension-dev:23Flask Extension Development4===========================56Flask, being a microframework, often requires some repetitive steps to getMerge branch '1.0.x'David Lordbefore adoption1351d0a
line 7why, one step back7a third party library working. Many such extensions are already availableMerge branch '1.0.x' into 1.1.xDavid Lordbefore adoptionc42803f
line 8why, one step back8on `PyPI`_.Merge pull request #2525 from proog/docs-twisted-portDavid Lordbefore adoptiond24bb9e
lines 9–158why, one step back910If you want to create your own Flask extension for something that does not11exist yet, this guide to extension development will help you get your12extension running in no time and to feel like users would expect your13extension to behave.1415Anatomy of an Extension16-----------------------1718Extensions are all located in a package called ``flask_something``19where "something" is the name of the library you want to bridge. So for20example if you plan to add support for a library named `simplexml` to21Flask, you would name your extension's package ``flask_simplexml``.2223The name of the actual extension (the human readable name) however would24be something like "Flask-SimpleXML". Make sure to include the name25"Flask" somewhere in that name and that you check the capitalization.26This is how users can then register dependencies to your extension in27their :file:`setup.py` files.2829But what do extensions look like themselves? An extension has to ensure30that it works with multiple Flask application instances at once. This is31a requirement because many people will use patterns like the32:ref:`app-factories` pattern to create their application as needed to aid33unittests and to support multiple configurations. Because of that it is34crucial that your application supports that kind of behavior.3536Most importantly the extension must be shipped with a :file:`setup.py` file and37registered on PyPI. Also the development checkout link should work so38that people can easily install the development version into their39virtualenv without having to download the library by hand.4041Flask extensions must be licensed under a BSD, MIT or more liberal license42in order to be listed in the Flask Extension Registry. Keep in mind43that the Flask Extension Registry is a moderated place and libraries will44be reviewed upfront if they behave as required.4546"Hello Flaskext!"47-----------------4849So let's get started with creating such a Flask extension. The extension50we want to create here will provide very basic support for SQLite3.5152First we create the following folder structure::5354 flask-sqlite3/55 flask_sqlite3.py56 LICENSE57 README5859Here's the contents of the most important files:6061setup.py62````````6364The next file that is absolutely required is the :file:`setup.py` file which is65used to install your Flask extension. The following contents are66something you can work with::6768 """69 Flask-SQLite370 -------------7172 This is the description for that library73 """74 from setuptools import setup757677 setup(78 name='Flask-SQLite3',79 version='1.0',80 url='http://example.com/flask-sqlite3/',81 license='BSD',82 author='Your Name',83 author_email='your-email@example.com',84 description='Very short description',85 long_description=__doc__,86 py_modules=['flask_sqlite3'],87 # if you would be using a package instead use packages instead88 # of py_modules:89 # packages=['flask_sqlite3'],90 zip_safe=False,91 include_package_data=True,92 platforms='any',93 install_requires=[94 'Flask'95 ],96 classifiers=[97 'Environment :: Web Environment',98 'Intended Audience :: Developers',99 'License :: OSI Approved :: BSD License',100 'Operating System :: OS Independent',101 'Programming Language :: Python',102 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',103 'Topic :: Software Development :: Libraries :: Python Modules'104 ]105 )106107That's a lot of code but you can really just copy/paste that from existing108extensions and adapt.109110flask_sqlite3.py111````````````````112113Now this is where your extension code goes. But how exactly should such114an extension look like? What are the best practices? Continue reading115for some insight.116117Initializing Extensions118-----------------------119120Many extensions will need some kind of initialization step. For example,121consider an application that's currently connecting to SQLite like the122documentation suggests (:ref:`sqlite3`). So how does the extension123know the name of the application object?124125Quite simple: you pass it to it.126127There are two recommended ways for an extension to initialize:128129initialization functions:130131 If your extension is called `helloworld` you might have a function132 called ``init_helloworld(app[, extra_args])`` that initializes the133 extension for that application. It could attach before / after134 handlers etc.135136classes:137138 Classes work mostly like initialization functions but can later be139 used to further change the behavior. For an example look at how the140 `OAuth extension`_ works: there is an `OAuth` object that provides141 some helper functions like `OAuth.remote_app` to create a reference to142 a remote application that uses OAuth.143144What to use depends on what you have in mind. For the SQLite 3 extension145we will use the class-based approach because it will provide users with an146object that handles opening and closing database connections.147148When designing your classes, it's important to make them easily reusable149at the module level. This means the object itself must not under any150circumstances store any application specific state and must be shareable151between different applications.152153The Extension Code154------------------155156Here's the contents of the `flask_sqlite3.py` for copy/paste::157158 import sqlite3Merge pull request #2647 from pallets/docs-extensionsDavid Lordbefore adoptiond72612d
line 159why, one step back159 from flask import current_app, _app_ctx_stackMerge pull request #2525 from proog/docs-twisted-portDavid Lordbefore adoptiond24bb9e
lines 160–169why, one step back160161162 class SQLite3(object):163 def __init__(self, app=None):164 self.app = app165 if app is not None:166 self.init_app(app)167168 def init_app(self, app):169 app.config.setdefault('SQLITE3_DATABASE', ':memory:')Merge pull request #2647 from pallets/docs-extensionsDavid Lordbefore adoptiond72612d
line 170why, one step back170 app.teardown_appcontext(self.teardown)Merge pull request #2525 from proog/docs-twisted-portDavid Lordbefore adoptiond24bb9e
lines 171–175why, one step back171172 def connect(self):173 return sqlite3.connect(current_app.config['SQLITE3_DATABASE'])174175 def teardown(self, exception):Merge pull request #2647 from pallets/docs-extensionsDavid Lordbefore adoptiond72612d
line 176why, one step back176 ctx = _app_ctx_stack.topMerge pull request #2525 from proog/docs-twisted-portDavid Lordbefore adoptiond24bb9e
lines 177–181why, one step back177 if hasattr(ctx, 'sqlite3_db'):178 ctx.sqlite3_db.close()179180 @property181 def connection(self):Merge pull request #2647 from pallets/docs-extensionsDavid Lordbefore adoptiond72612d
line 182why, one step back182 ctx = _app_ctx_stack.topMerge pull request #2525 from proog/docs-twisted-portDavid Lordbefore adoptiond24bb9e
lines 183–196why, one step back183 if ctx is not None:184 if not hasattr(ctx, 'sqlite3_db'):185 ctx.sqlite3_db = self.connect()186 return ctx.sqlite3_db187188189So here's what these lines of code do:1901911. The ``__init__`` method takes an optional app object and, if supplied, will192 call ``init_app``.1932. The ``init_app`` method exists so that the ``SQLite3`` object can be194 instantiated without requiring an app object. This method supports the195 factory pattern for creating applications. The ``init_app`` will set the196 configuration for the database, defaulting to an in memory database ifMerge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
lines 197–198why, one step back197 no configuration is supplied. In addition, the ``init_app`` method198 attaches the ``teardown`` handler.Merge pull request #2525 from proog/docs-twisted-portDavid Lordbefore adoptiond24bb9e
lines 199–207why, one step back1993. Next, we define a ``connect`` method that opens a database connection.2004. Finally, we add a ``connection`` property that on first access opens201 the database connection and stores it on the context. This is also202 the recommended way to handling resources: fetch resources lazily the203 first time they are used.204205 Note here that we're attaching our database connection to the top206 application context via ``_app_ctx_stack.top``. Extensions should use207 the top context for storing their own information with a sufficientlyMerge pull request #2647 from pallets/docs-extensionsDavid Lordbefore adoptiond72612d
line 208why, one step back208 complex name.Merge pull request #2525 from proog/docs-twisted-portDavid Lordbefore adoptiond24bb9e
lines 209–226why, one step back209210So why did we decide on a class-based approach here? Because using our211extension looks something like this::212213 from flask import Flask214 from flask_sqlite3 import SQLite3215216 app = Flask(__name__)217 app.config.from_pyfile('the-config.cfg')218 db = SQLite3(app)219220You can then use the database from views like this::221222 @app.route('/')223 def show_all():224 cur = db.connection.cursor()225 cur.execute(...)226Merge pull request #2647 from pallets/docs-extensionsDavid Lordbefore adoptiond72612d
lines 227–228why, one step back227Likewise if you are outside of a request you can use the database by228pushing an app context::Merge pull request #2525 from proog/docs-twisted-portDavid Lordbefore adoptiond24bb9e
lines 229–239why, one step back229230 with app.app_context():231 cur = db.connection.cursor()232 cur.execute(...)233234At the end of the ``with`` block the teardown handles will be executed235automatically.236237Additionally, the ``init_app`` method is used to support the factory pattern238for creating apps::239Merge pull request #3071 from bbbbx/masterHsiaoming Yangbefore adoption33c89aa
line 240why, one step back240 db = SQLite3()Merge pull request #2525 from proog/docs-twisted-portDavid Lordbefore adoptiond24bb9e
lines 241–275why, one step back241 # Then later on.242 app = create_app('the-config.cfg')243 db.init_app(app)244245Keep in mind that supporting this factory pattern for creating apps is required246for approved flask extensions (described below).247248.. admonition:: Note on ``init_app``249250 As you noticed, ``init_app`` does not assign ``app`` to ``self``. This251 is intentional! Class based Flask extensions must only store the252 application on the object when the application was passed to the253 constructor. This tells the extension: I am not interested in using254 multiple applications.255256 When the extension needs to find the current application and it does257 not have a reference to it, it must either use the258 :data:`~flask.current_app` context local or change the API in a way259 that you can pass the application explicitly.260261262Using _app_ctx_stack263--------------------264265In the example above, before every request, a ``sqlite3_db`` variable is266assigned to ``_app_ctx_stack.top``. In a view function, this variable is267accessible using the ``connection`` property of ``SQLite3``. During the268teardown of a request, the ``sqlite3_db`` connection is closed. By using269this pattern, the *same* connection to the sqlite3 database is accessible270to anything that needs it for the duration of the request.271272273Learn from Others274-----------------275Merge branch '1.0.x' into 1.1.xDavid Lordbefore adoptionc42803f
lines 276–283why, one step back276This documentation only touches the bare minimum for extension development.277If you want to learn more, it's a very good idea to check out existing extensions278on the `PyPI`_. If you feel lost there is still the `mailinglist`_ and the279`IRC channel`_ to get some ideas for nice looking APIs. Especially if you do280something nobody before you did, it might be a very good idea to get some more281input. This not only generates useful feedback on what people might want from282an extension, but also avoids having multiple developers working in isolation283on pretty much the same problem.Merge pull request #2525 from proog/docs-twisted-portDavid Lordbefore adoptiond24bb9e
lines 284–285why, one step back284285Remember: good API design is hard, so introduce your project on theMerge branch '1.0.x'David Lordbefore adoption2236ba9
line 286why, one step back286mailing list, and let other developers give you a helping hand withMerge pull request #2525 from proog/docs-twisted-portDavid Lordbefore adoptiond24bb9e
lines 287–296why, one step back287designing the API.288289The best Flask extensions are extensions that share common idioms for the290API. And this can only work if collaboration happens early.291292Approved Extensions293-------------------294295Flask also has the concept of approved extensions. Approved extensions296are tested as part of Flask itself to ensure extensions do not break onMerge branch '1.0.x' into 1.1.xDavid Lordbefore adoptionc42803f
lines 297–298why, one step back297new releases. If you want your own extension to be approved you have to298follow these guidelines:Merge pull request #2525 from proog/docs-twisted-portDavid Lordbefore adoptiond24bb9e
lines 299–309why, one step back2993000. An approved Flask extension requires a maintainer. In the event an301 extension author would like to move beyond the project, the project should302 find a new maintainer including full source hosting transition and PyPI303 access. If no maintainer is available, give access to the Flask core team.3041. An approved Flask extension must provide exactly one package or module305 named ``flask_extensionname``.3062. It must ship a testing suite that can either be invoked with ``make test``307 or ``python setup.py test``. For test suites invoked with ``make308 test`` the extension has to ensure that all dependencies for the test309 are installed automatically. If tests are invoked with ``python setup.pyMerge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
lines 310–311why, one step back310 test``, test dependencies can be specified in the :file:`setup.py` file.311 The test suite also has to be part of the distribution.Merge pull request #2525 from proog/docs-twisted-portDavid Lordbefore adoptiond24bb9e
lines 312–325why, one step back3123. APIs of approved extensions will be checked for the following313 characteristics:314315 - an approved extension has to support multiple applications316 running in the same Python process.317 - it must be possible to use the factory pattern for creating318 applications.3193204. The license must be BSD/MIT/WTFPL licensed.3215. The naming scheme for official extensions is *Flask-ExtensionName* or322 *ExtensionName-Flask*.3236. Approved extensions must define all their dependencies in the324 :file:`setup.py` file unless a dependency cannot be met because it is not325 available on PyPI.Merge branch '1.0.x'David Lordbefore adoption1351d0a
lines 326–327why, one step back3267. The documentation must use the ``flask`` theme from the327 `Official Pallets Themes`_.Merge pull request #2525 from proog/docs-twisted-portDavid Lordbefore adoptiond24bb9e
lines 328–333why, one step back3288. The setup.py description (and thus the PyPI description) has to329 link to the documentation, website (if there is one) and there330 must be a link to automatically install the development version331 (``PackageName==dev``).3329. The ``zip_safe`` flag in the setup script must be set to ``False``,333 even if the extension would be safe for zipping.Merge pull request #2555 from pallets/deprecate-26-33David Lordbefore adoption05e3840
line 334why, one step back33410. An extension currently has to support Python 3.4 and newer and 2.7.Merge pull request #2525 from proog/docs-twisted-portDavid Lordbefore adoptiond24bb9e
lines 335–336why, one step back335336Merge branch '1.0.x' into 1.1.xDavid Lordbefore adoptionc42803f
line 337why, one step back337.. _PyPI: https://pypi.org/search/?c=Framework+%3A%3A+FlaskMerge pull request #2525 from proog/docs-twisted-portDavid Lordbefore adoptiond24bb9e
lines 338–340why, one step back338.. _OAuth extension: https://pythonhosted.org/Flask-OAuth/339.. _mailinglist: http://flask.pocoo.org/mailinglist/340.. _IRC channel: http://flask.pocoo.org/community/irc/Merge branch '1.0.x'David Lordbefore adoption1351d0a
line 341why, one step back341.. _Official Pallets Themes: https://pypi.org/project/Pallets-Sphinx-Themes/