if hasattr(app, teardown_request):
Strictly speaking the above code is wrong, because teardown functions are passed the
exception and typically don’t return anything. However because the return value is
discarded this will just work assuming that the code in between does not touch the
26.7 Learn from Others
This documentation only touches the bare minimum for extension development. If
you want to learn more, it’s a very good idea to check out existing extensions on the
Flask Extension Registry.Ifyoufeellostthereisstillthe mailinglistandthe IRC chan-
before you did, it might be a very good idea to get some more input. This not only
to get an idea about what people might want to have from an extension, but also to
avoid having multiple developers working on pretty much the same side by side.
Remember: good API design is hard, so introduce your project on the mailinglist, and
let other developers give you a helping hand with designing the API.
The best Flask extensions are extensions that share common idioms for the API. And
this can only work if collaboration happens early.
26.8 Approved Extensions
Flask also has the concept of approved extensions. Approved extensions are tested as
part of Flask itself to ensure extensions do not break on new releases. These approved
extensions are listed ontheFlaskExtensionRegistry and marked appropriately. If you
want your own extension to be approved you have to follow these guidelines:
0. An approved Flask extension requires a maintainer. In the event an extension
author would like to move beyond the project, the project should ﬁnd a new
maintainer including full source hosting transition and PyPI access. If no main-
tainer is available, give access to the Flask core team.
1. An approved Flask extension must provide exactly one package or module
named flask_extensionname. They might also reside inside a flaskext names-
pace packages though this is discouraged now.
2. It must ship a testing suite that can either be invoked with make test or python
setup.py test. For test suites invoked with make test the extension has to
ensure that all dependencies for the test are installed automatically. If tests are
invoked with python setup.py test, test dependencies can be speciﬁed in the
setup.pyﬁle. The test suite also has to be part of the distribution.
3. APIs of approved extensions will be checked for the following characteristics:
• an approved extension has to support multiple applications running in the
same Python process.
• it must be possible to use the factory pattern for creating applications.
4. The license must be BSD/MIT/WTFPL licensed.
5. The naming scheme for ofﬁcial extensions is Flask-ExtensionName or
6. Approved extensions must deﬁne all their dependencies in the setup.py ﬁle un-
less a dependency cannot be met because it is not available on PyPI.
7. The extension must have documentation that uses one of the two Flask themes
for Sphinx documentation.
8. The setup.py description (and thus the PyPI description) has to link to the doc-
umentation, website (if there is one) and there must be a link to automatically
install the development version (PackageName==dev).
9. The zip_safe ﬂag in the setup script must be set to False, even if the extension
would be safe for zipping.
10. An extension currently has to support Python 2.6 as well as Python 2.7
26.9 Extension Import Transition
For a while we recommended using namespace packages for Flask extensions. This
turned out to be problematic in practice because many differentcompeting namespace
package systems exist and pip would automatically switch between different systems
and this caused a lot of problems for users.
Instead we now recommend naming packages flask_foo instead of the now depre-
cated flaskext.foo. Flask 0.8introduces a redirect import systemthatlets uses import
from flask.ext.foo and it will try flask_foo ﬁrst and if that fails flaskext.foo.
Flask extensions should urge users to importfromflask.ext.fooinstead of flask_foo
or flaskext_foo so that extensions can transition to the new package name without
C# Imaging - Scan Barcode Image in C#.NET
Recognize PDF-417 2D barcode in .NET WinForms & ASP.NET in .NET WinForms project & ASP.NET web form with C# Mature .NET Code 128 image reader & scanner for C# online form pdf output; pdf data extraction
The Pocoo styleguide is the styleguide for all Pocoo Projects, including Flask. This
styleguide is a requirement for Patches to Flask and a recommendation for Flask ex-
In general the Pocoo Styleguide closely followsPEP8with some small differences and
27.1 General Layout
Indentation: 4real spaces. No tabs, no exceptions.
Maximum line length: 79 characters with a soft limit for 84 if absolutely necessary.
Try to avoid too nested code by cleverly placing break, continue and return state-
Continuing long statements: To continue a statement you can use backslashes in
which case you should align the next line with the last dot or equal sign, or
indent four spaces:
this_is_a_very_long(function_call, with many y parameters) \
MyModel.query.filter(MyModel.scalar > 120) \
If you break in a statement with parentheses or braces, align to the braces:
this_is_a_very_long(function_call, with many y parameters,
23, 42, and even n more)
For lists or tuples with many items, break immediately after the opening brace:
items = [
this is the first, set of items, with more items,
to come in this line, like this
Blank lines: Top level functions and classes are separated by two lines, everything
else by one. Do not use too many blank lines to separate logical segments in
print Hello %s! % name
print See you %s. % name
"""This is a simple docstring"""
def __init__(self, name):
self.name = name
return self.name.upper() + !!!!111
27.2 Expressions and Statements
General whitespace rules:
•No whitespace for unary operators that are not words (e.g.: -, ~etc.) as well
on the inner side of parentheses.
•Whitespace is placed between binary operators.
exp = -1.05
value = (item_value / item_count) ) * offset / exp
value = my_list[index]
value = my_dict[key]
exp = - - 1.05
value = ( item_value / item_count ) ) * offset / exp
value = (item_value/item_count)*offset/exp
value=( item_value/item_count ) ) * offset/exp
value = my_list[ index ]
value = my_dict [key]
Yoda statements are a no-go: Never compare constant with variable, always variable
if method == md5:
if md5 == method:
•against arbitrary types: == and !=
•against singletons with is and is not (eg: foo is not None)
•never compare something with True or False (for example never do foo ==
False, do not foo instead)
Negated containment checks: use foo not in bar instead of not foo in bar
Instance checks: isinstance(a, C)instead of type(A) is C, but try to avoid instance
checks in general. Check for features.
27.3 Naming Conventions
• Class names: CamelCase, with acronyms kept uppercase (HTTPWriter and not
• Variable names: lowercase_with_underscores
• Method and function names: lowercase_with_underscores
• Constants: UPPERCASE_WITH_UNDERSCORES
• precompiled regular expressions: name_re
Protected members are preﬁxed with a single underscore. Double underscores are
reserved for mixin classes.
On classes with keywords, trailing underscores are appended. Clashes with builtins
are allowedand mustnotbe resolved by appending an underlinetothe variable name.
If the function needs to access a shadowed builtin, rebind the builtin to a different
Function and method arguments:
•class methods: cls as ﬁrst parameter
•instance methods: self as ﬁrst parameter
•lambdas for properties might have the ﬁrst parameter replaced with x like
in display_name = property(lambda x: x.real_name or x.username)
Docstring conventions: All docstrings are formatted with reStructuredText as under-
stood by Sphinx. Depending on the number of lines in the docstring, they are
laid out differently. If it’s just one line, the closing triple quote is on the same line
as the opening, otherwise the text is on the same line as the opening quote and
the triple quote that closes the string on its own line:
"""This is a simple docstring"""
"""This is a longer docstring with so much information in there
that it spans three lines. In this case the closing triple quote
is on its own line.
Module header: The module header consists of an utf-8 encoding declaration (if non
ASCII letters are used, but it is recommended all the time) and a standard doc-
# -*- coding: utf-8 -*-
A brief description goes here.
:copyright: (c) YEAR by AUTHOR.
:license: LICENSE_NAME, see LICENSE_FILE for more details.
Please keep in mind that proper copyrights and license ﬁles are a requirement
for approved Flask extensions.
Rules for comments are similar to docstrings. Both are formatted with reStructured-
Text. If a comment is used to document an attribute, put a colon after the opening
pound sign (#):
#: the name of the user as unicode string
name = Column(String)
#: the sha1 hash of the password + inline salt
pw_hash = Column(String)
PYTHON 3 SUPPORT
Flask and all of its dependencies support Python 3 so you can in theory start working
on it already. There are however a few things you should be aware of before you start
using Python 3 for your next project.
If you want to use Flask with Python 3 you will need to use Python 3.3 or higher. 3.2
and older are not supported.
In addition to that you needtouse the latestandgreatestversions ofitsdangerous, Jinja2
28.2 API Stability
Some of the decisions made in regards to unicode and byte untilization on Python 3
make ithard to write low level code. This mainly affects WSGI middlewares and inter-
acting with the WSGI provided information. Werkzeug wraps all that information in
high-level helpers but some of those were speciﬁcally added for the Python 3 support
and are quite new.
Alot of the documentation out there on using WSGI leaves out those details as it was
written before WSGI was updated to Python 3. While the API for Werkzeug and Flask
on Python 2.x should not change much we cannot guarantee that this won’t happen
on Python 3.
28.3 Few Users
Python 3 currently has less than 1% of the users of Python 2 going by PyPI download
stats. As a resultmany of the problems you will encounter are probably hard to search
for on the internet if they are Python 3 speciﬁc.
28.4 Small Ecosystem
The majority of the Flask extensions, all of the documentation and the vastmajority of
the PyPI provided libraries do not support Python 3yet. Even if you start your project
with knowing that all you will need is supported by Python 3 you don’t know what
happens six months from now. If you are adventurous you can start porting libraries
on your own, but that is nothing for the faint of heart.
Unless you are already familiar with the differences in the versions we recommend
sticking to current versions of Python until the ecosystem caught up.
The majority of the upgrade pain is in the lower-level libararies like Flask and
Werkzeug and not in the actual high-level application code. For instance all of the
Flask examples thatare in the Flask repository work out of the box on both 2.x and 3.x
and did not require a single line of code changed.
UPGRADING TO NEWER RELEASES
Flask itself is changing like any software is changing over time. Most of the changes
are the nice kind, the kind where you don’t have to change anything in your code to
proﬁt from a new release.
However every once in a while there are changes that do require some changes in
your code or there are changes that make it possible for you to improve your own
code quality by taking advantage of new features in Flask.
This section of the documentation enumerates all the changes in Flask from release to
release and how you can change your code to have a painless updating experience.
If you want to use the easy_install command to upgrade your Flask installation, make
sure to pass it the -U parameter:
$ easy_install -U Flask
29.1 Version 0.10
The biggest change going from 0.9 to 0.10 is that the cookie serialization format
changed from pickle to aspecialized JSON format. This change has beendone inorder
to avoid the damage an attacker can do if the secret key is leaked. When you upgrade
you will notice two major changes: all sessions that were issued before the upgrade
are invalidated and you can only store a limited amount of types in the session. The
new sessions are by design much more restricted to only allow JSON with a few small
extensions for tuples and strings with HTML markup.
In order to not break people’s sessions it is possible to continue using the old session
system by using theFlask-OldSessionsextension.
Flask also started storing the flask.g object on the application context instead of the
request context. This change should be transparent for you but it means that you now
can store things on the g object when there is no request context yet but an applica-
tion context. The old flask.Flask.request_globals_class attribute was renamed to
29.2 Version 0.9
The behavior of returning tuples from a function was simpliﬁed. If you return a tuple
it no longer deﬁnes the arguments for the response object you’re creating, it’s now
always a tuple in the form (response, status, headers) where at least one item has
to be provided. If you depend onthe old behavior, you can add it easily by subclassing
def make_response(self, rv):
if isinstance(rv, tuple):
return Flask.make_response(self, rv)
If you maintain an extension that was using _request_ctx_stack before, please con-
sider changing to _app_ctx_stack if it makes sense for your extension. For instance,
the app context stack makes sense for extensions which connect to databases. Using
the app context stack instead of the request stack will make extensions more readily
handle use cases outside of requests.
29.3 Version 0.8
Flask introduced a new session interface system. We also noticed that there
was a naming collision between ﬂask.session the module that implements sessions
and flask.session which is the global session object. With that introduction we
moved the implementation details for the session system into a new module called
flask.sessions. If you used the previously undocumented session support we urge
you to upgrade.
If invalid JSON data was submitted Flask will now raise aBadRequest exception in-
stead of letting the defaultValueError bubble up. This has the advantage that you no
longer have to handle that error to avoid an internal server error showing up for the
user. If you were catching this down explicitly in the past as ValueError you will need
to change this.
Due to a bug in the test client Flask 0.7 did not trigger teardown handlers when the
test client was used in a with statement. This was since ﬁxed but might require some
changes in your testsuites if you relied on this behavior.
29.4 Version 0.7
In Flask 0.7 we cleaned up the code base internally a lot and did some backwards in-
compatible changes that make it easier to implement larger applications with Flask.
Because we want to make upgrading as easy as possible we tried to counter the prob-
lems arising from these changes by providing a script that can ease the transition.
Documents you may be interested
Documents you may be interested