You are on page 1of 323

Flask Documentation

Release 0.12
Jan 25, 2017

CONTENTS

I User’s Guide 1
1 Foreword 3

2 Foreword for Experienced Programmers 5

3 Installation 7

4 Quickstart 11

5 Tutorial 29

6 Templates 45

7 Testing Flask Applications 49

8 Application Errors 57

9 Debugging Application Errors 63

10 Configuration Handling 65

11 Signals 73

12 Pluggable Views 77

13 The Application Context 83

14 The Request Context 87

15 Modular Applications with Blueprints 93

16 Flask Extensions 99

17 Command Line Interface 101

18 Development Server 107

19 Working with the Shell 109

i

20 Patterns for Flask 111

21 Deployment Options 169

22 Becoming Big 183

II API Reference 187
23 API 189

III Additional Notes 255
24 Design Decisions in Flask 257

25 HTML/XHTML FAQ 261

26 Security Considerations 267

27 Unicode in Flask 269

28 Flask Extension Development 273

29 Pocoo Styleguide 281

30 Python 3 Support 285

31 Upgrading to Newer Releases 287

32 Flask Changelog 297

33 License 311

ii

Part I
USER’S GUIDE

This part of the documentation, which is mostly prose, begins with some background
information about Flask, then focuses on step-by-step instructions for web develop-
ment with Flask.

1

2

1 What does “micro” mean? “Micro” does not mean that your whole web application has to fit into a single Python file (although it certainly can). with sensible defaults. The “micro” in microframework means Flask aims to keep the core simple but exten- sible. form validation or any- thing else where different libraries already exist that can handle that. 3 . nor does it mean that Flask is lacking in functionality. CHAPTER ONE FOREWORD Read this before you get started with Flask. 1. especially when getting started. various open authentication technologies. and a few conventions when getting started. you usually don’t have to. but it’s ready for production use on a variety of needs. upload handling. Flask supports extensions to add such functionality to your application as if it was imple- mented in Flask itself. so that Flask can be everything you need and nothing you don’t. Those decisions that it does make. with the names templates and static respectively. and when you should or should not be using it.2 Configuration and Conventions Flask has many configuration values. and more. This hopefully answers some questions about the purpose and goals of the project. form val- idation. Everything else is up to you. Instead. Flask won’t make many decisions for you. By convention. Flask does not include a database abstraction layer. are easy to change. 1. templates and static files are stored in subdi- rectories within the application’s Python source tree. such as what database to use. Numerous extensions provide database integration. By default. such as what templating engine to use. While this can be changed. Flask may be “micro”.

the Python web interface. The Flask core team reviews extensions and ensures approved extensions do not break with future releases. check out the Becoming Big chapter. Flask will continue to provide a very simple glue layer to the best that Python has to offer. Flask includes many hooks to customize its behavior. head over to the section about Design Decisions in Flask. or the Foreword for Experienced Programmers. you are free to make the design decisions appropriate for your project. Should you need more cus- tomization. the Quickstart. and take advantage of framework-agnostic tools built for WSGI. the Flask class is built for subclassing. If you are interested in that. Continue to Installation. 4 . You can implement advanced patterns in SQLAlchemy or an- other database tool. introduce non-relational data persistence as appropriate.3 Growing with Flask Once you have Flask up and running. As your codebase grows. you’ll find a variety of extensions available in the community to integrate your project for production.1. If you are curious about the Flask design principles.

Because of that. And don’t think that your application is not important enough to attract an attacker. you are probably allowing users to register and leave their data on your server.1 Thread-Locals in Flask One of the design decisions in Flask was that simple tasks should be simple. does not hide them. Flask has a few design choices that some people might find surprising or unorthodox. 5 . Unless you deliberately mark in- secure HTML as secure. and calls out in the code and documentation where they are used. Flask protects you against one of the most common security problems of modern web applications: cross-site scripting (XSS). Some of these security concerns are far more complex than one might think. they should not take a lot of code and yet they should not limit you. The users are entrusting you with data. But there are many more ways to cause security problems. but requires a valid request context for dependency in- jection or when attempting to reuse code which uses a value pegged to the request.2 Develop for the Web with Caution Always keep security in mind when building web applications. there are many ways the security of a web application can be com- promised. And even if you are the only user that might leave data in your application. This approach is convenient. Flask uses thread-local objects internally so that you don’t have to pass ob- jects around from function to function within a request in order to stay threadsafe. and we all sometimes underestimate the likelihood that a vulnerability will be exploited . The documentation will warn you about aspects of web development that require at- tention to security. The Flask project is honest about thread-locals. For example. Flask and the underlying Jinja2 template engine have you covered. CHAPTER TWO FOREWORD FOR EXPERIENCED PROGRAMMERS 2. 2. Unfortunately. If you write a web application.until a clever attacker figures out a way to exploit our applications. you still want that data to be stored securely.

its dependencies. watching for exploits when building to your requirements. Continue to Installation or the Quickstart. If you want to use Flask with Python 3 have a look at the Python 3 Support page. and most Flask extensions all support Python 3. Flask is no different from any other framework in that you the developer must build with caution.3 Python 3 Support in Flask Flask. links to malicious software. 2.Depending on the kind of attack. chances are that automated bots are probing for ways to fill your database with spam. and the like. 6 .

Let’s face it: quite often libraries break backwards compatibility. so be sure to have an up-to-date Python 2. too. Let’s see how virtualenv works. It doesn’t actually install separate copies of Python.6 or newer to get started. and it’s unlikely that any serious application will have zero dependencies. but it does provide a clever way to keep different project environments isolated. What problem does virtualenv solve? If you like Python as much as I do. chances are you want to use it for other projects besides Flask-based web applications. Werkzeug is a toolkit for WSGI. Jinja2 renders templates. one for each project. So what do you do if two or more of your projects have conflicting dependencies? Virtualenv to the rescue! Virtualenv enables multiple side-by-side installations of Python. If you are on Mac OS X or Linux. or at least different versions of Python libraries. Maybe it’s even in your package manager.x installation. like Werkzeug and Jinja2. So how do you get all that on your computer quickly? There are many ways you could do that. so let’s have a look at that first. 3. But the more projects you have. try: 7 .1 virtualenv Virtualenv is probably what you want to use during development. For using Flask with Python 3 have a look at Python 3 Support. and if you have shell access to your production machines. you’ll probably want to use it there. CHAPTER THREE INSTALLATION Flask depends on some external libraries. chances are that the following command will work for you: $ sudo pip install virtualenv It will probably install virtualenv on your system. the standard Python interface between web applications and a vari- ety of servers for both development and deployment. If you use Ubuntu. the more likely it is that you will be working with different versions of Python itself. but the most kick-ass method is virtualenv. You will need Python 2.

Once you have it installed.. and leave out sudo. but without the sudo prefix. Check the pip and setuptools on Windows section for more information about how to do that.. do the following: $ . Now.. I usually create a project folder and a venv folder within: $ mkdir myproject $ cd myproject $ virtualenv venv New python executable in venv/bin/python Installing setuptools. the following command is for you: $ venv\Scripts\activate Either way.. run it in a command-prompt window with administrator priv- ileges.2 System-Wide Installation This is possible as well. though I do not recommend it. Once you have virtualenv installed.. whenever you want to work on a project.. you should now be using your virtualenv (notice how the prompt of your shell has changed to show the active environment). 3.. run the same commands as above. On OS X and Linux. Now. you must install it first. venv/bin/activate If you are a Windows user...done. the prompt of your shell should be as familiar as before. Enter the following command to get Flask activated in your vir- tualenv: $ pip install Flask A few seconds later and you are good to go. you only have to activate the corre- sponding environment.) 8 . use the following command: $ deactivate After doing this... Just run pip with root privi- leges: $ sudo pip install Flask (On Windows systems. And if you want to go back to the real world. just fire up a shell and create your own environ- ment.$ sudo apt-get install python-virtualenv If you are on Windows and don’t have the easy_install command. let’s move on. pip.

you should be able to navigate to your Python install directory (e.py It should be double-clickable once you download it.py develop . then find the win_add2path.3 Living on the Edge If you want to work with the latest version of Flask. virtualenv is recommended.. Open a new Command Prompt and check that you can now just type python to bring up the interpreter. If you don’t currently have pip.. you can simply run: 9 . pip.. but this might not automatically happen on Windows. To fix this.. Get the git checkout in a new virtualenv and run in development mode: $ git clone http://github. Fortunately there is a “bootstrap script” you can run to install. because it doesn’t know where those executables are (give either a try!). to install virtualenv. setuptools and virtualenv can be a little trickier. then get-pip...done.git/ $ cd flask $ virtualenv venv New python executable in venv/bin/python Installing setuptools. Finished processing dependencies for Flask This will pull in the dependencies and activate the git head as the current version inside the virtualenv. then go to Tools..this will let you install anything else (like virtualenv). once you pull up a command prompt you want to be able to type pip and python which will run those things. or you can tell it to operate on a git checkout. Finally.py file and run that. Either way. get-pip.. $ .git Initialized empty Git repository in ~/dev/flask/.. 3.com/pallets/flask.. The crucial package you will need is pip ... Then all you have to do is run git pull origin to update to the latest version. If you already have pip.g C:Python27). there are two ways: you can either let pip pull in the development version..4 pip and setuptools on Windows Sometimes getting the standard “Python packaging tools” like pip. then Scripts. you can upgrade them by running: > pip install --upgrade pip setuptools Most often. but nothing very hard.py will install it for you.3. venv/bin/activate $ python setup.

> pip install virtualenv Then you can be off on your way following the installation instructions above. 10 .

py because this would conflict with Flask itself. head over to the Installation section. CHAPTER FOUR QUICKSTART Eager to get started? This page gives a good introduction to Flask. 3. An instance of this class will be our WSGI application. For more information have a look at the Flask documentation. First we imported the Flask class. If you are using a single module (as in this example).1 A Minimal Application A minimal Flask application looks something like this: from flask import Flask app = Flask(__name__) @app. World!' So what did that code do? 1. The function is given a name which is also used to generate URLs for that partic- ular function. It assumes you already have Flask installed. and returns the message we want to display in the user’s browser. If you do not. Make sure to not call your application flask. 11 . and so on. Just save it as hello.py or something similar. 4. Next we create an instance of this class. static files. you should use __name__ because depending on if it’s started as ap- plication or imported as module the name will be different ('__main__' versus the actual import name). The first argument is the name of the application’s module or package. 2. We then use the route() decorator to tell Flask what URL should trigger our function. This is needed so that Flask knows where to look for templates. 4.route('/') def hello_world(): return 'Hello.

Now head over to http://127. Alternatively you can use python -m flask: $ export FLASK_APP=hello. 12 . you can make the server publicly available simply by adding --host=0. and neither did python -m flask. which is good enough for testing but prob- ably not what you want to use in production. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer.0.0. For deployment options see Deployment Options. not from any other in the network.0.py $ flask run * Running on http://127.11 use to have different ways to start the application. 4.0. In short.2. If you have the debugger disabled or trust the users on your network.0.1:5000/ If you are on Windows you need to use set instead of export.py $ python -m flask run * Running on http://127. Before you can do that you need to tell your terminal the application to work with by exporting the FLASK_APP environment variable: $ export FLASK_APP=hello. In that case you have two options: either upgrade to newer Flask versions or have a look at the Development Server docs to see the alternative method for running a server.To run the application you can either use the flask command or python’s -m switch with Flask.1:5000/.0 to the command line: flask run --host=0.2 What to do if the Server does not Start In case the python -m flask fails or flask does not exist.0.1 Old Version of Flask Versions of Flask older than 0.0.0 This tells your operating system to listen on all public IPs.0. 4. the flask command did not exist. there are multiple reasons this might be the case.0. and you should see your hello world greet- ing.0.1:5000/ This launches a very simple builtin server. First of all you need to look at the error message. Externally Visible Server If you run the server you will notice that the server is only accessible from your own computer.

This makes it a major security risk and therefore it must never be used on production machines. it enables the debug mode on the Flask application. In case that module is incorrectly named you will get an import error upon start (or if debug is enabled when you navigate to the application).2 Invalid Import Name The FLASK_APP environment variable is the name of the module to import at flask run.4. The most common reason is a typo or because you did not actually create an app object. but you would have to restart it manually after each change to your code. and it will also provide you with a helpful debugger if things go wrong.3 Debug Mode (Want to just log errors and stack traces? See Application Errors) The flask script is nice to start a local development server. This does the following things: 1. That is not very nice and Flask can do better. If you enable debug support the server will reload itself on code changes.2. There are more parameters that are explained in the Development Server docs. It will tell you what it tried to import and why it failed. 4. Attention Even though the interactive debugger does not work in forking environments (which makes it nearly impossible to use on production servers). it activates the debugger 2. To enable debug mode you can export the FLASK_DEBUG environment variable before running the server: $ export FLASK_DEBUG=1 $ flask run (On Windows you need to use set instead of export). it still allows the execution of arbitrary code. it activates the automatic reloader 3. Screenshot of the debugger in action: 13 .

route('/') def index(): return 'Index Page' @app.4 Routing Modern web applications have beautiful URLs. As you have seen above. This helps people remember the URLs. Here are some basic examples: @app. which is especially handy for applications that are used from mobile devices with slower network connections. 4.route('/hello') def hello(): return 'Hello. World' 14 .Have another debugger in mind? See Working with Debuggers. the route() decorator is used to bind a function to a URL. If the user can directly go to the desired page with- out having to hit the index page it is more likely they will like the page and come back next time.

Take these two rules: @app. The idea behind that module is to ensure beautiful and unique URLs based on precedents laid down by Apache and earlier HTTP servers.1 Variable Rules To add variable parts to a URL you can mark these special sections as <variable_name>. the id is an integer return 'Post %d' % post_id The following converters exist: string accepts any text without a slash (the default) int accepts integers float like int but for floating point values path like the default but also accepts slashes any matches one of the items provided uuid accepts UUID strings Unique URLs / Redirection Behavior Flask’s URL rules are based on Werkzeug’s routing module. Here are some nice examples: @app. Optionally a converter can be used by specifying a rule with <converter:variable_name>.route('/about') def about(): return 'The about page' Though they look rather similar. it is similar to a folder on a filesystem. Accessing it without a trailing slash will cause Flask to redirect to the canonical URL with the trailing slash. they differ in their use of the trailing slash in the URL definition.route('/projects/') def projects(): return 'The project page' @app.4. In that sense.route('/post/<int:post_id>') def show_post(post_id): # show the post with the given id. Such a part is then passed as a keyword argument to your function. In the first case. the canonical URL for the projects endpoint has a trailing slash.But there is more to it! You can make certain parts of the URL dynamic and attach multiple rules to a function. 4. 15 .route('/user/<username>') def show_user_profile(username): # show the user profile for that user return 'User %s' % username @app.

route('/user/<username>') .. rather like the pathname of a file on UNIX-like systems. which helps search engines avoid indexing the same page twice. It accepts the name of the function as first argument and a number of keyword arguments..... consistent with how Apache and other servers work. the URLs will stay unique. print url_for('index') .. print url_for('login'. without having to remember to change URLs all over the place. / /login /login?next=/ /user/John%20Doe (This also uses the test_request_context() method. More impor- tantly..4.. Why would you want to build URLs using the URL reversing function url_for() in- stead of hard-coding them into your templates? There are three good reasons for this: 1..route('/login') ..test_request_context(): . It tells Flask to behave as though it is handling a request.In the second case. next='/') . the URL is defined without a trailing slash. Context Locals). can Flask also generate them? Of course it can.. >>> @app. Accessing the URL with a trailing slash will produce a 404 “Not Found” error... >>> with app. username='John Doe') . This behavior allows relative URLs to continue working even if the trailing slash is omitted... Unknown variable parts are appended to the URL as query parameters. it allows you to change URLs in one go.. 4. 16 . >>> @app. print url_for('login') . To build a URL to a specific function you can use the url_for() function.2 URL Building If it can match URLs... however. def index(): pass . explained below. Here are some examples: >>> from flask import Flask.. def login(): pass . each corresponding to the variable part of the URL rule. Reversing is often more descriptive than hard-coding the URLs.. Also. even though we are interacting with it through a Python shell.. Have a look at the explanation below. def profile(username): pass . url_for >>> app = Flask(__name__) >>> @app. print url_for('profile'..route('/') .

Likewise. The following methods are very common: GET The browser tells the server to just get the information stored on that page and send it. POST The browser tells the server that it wants to post some new information to that URL and that the server must ensure the data is stored and only stored once. a route only answers to GET requests.say. here is a quick introduction to HTTP methods and why they matter: The HTTP method (also often called “the verb”) tells the server what the client wants to do with the requested page. but that can be changed by providing the methods argument to the route() decorator. By default. but there are some good reasons to do it this way. not the content of the page. 'POST']) def login(): if request. 4. 2.url_for() will handle that properly for you.method == 'POST': do_the_login() else: show_the_login_form() If GET is present. methods=['GET'. This is probably the most common method. as of Flask 0. This is how HTML forms usually transmit data to the server. It will also make sure that HEAD requests are handled as the HTTP RFC (the document describing the HTTP protocol) demands. Now you might be asking why this is useful. You don’t have to deal with that. so you don’t have to deal with them. HEAD will be added automatically for you.6. You have no idea what an HTTP method is? Worry not.3 HTTP Methods HTTP (the protocol web applications are speaking) knows different methods for ac- cessing URLs. so you can completely ignore that part of the HTTP specification. Consider that the connection is lost during transmission: in this situation a system between the browser and the server might receive the request safely a second time without 17 . HEAD The browser tells the server to get the information. PUT Similar to POST but the server might trigger the store procedure multiple times by overwriting the old values more than once. 3. An application is supposed to handle that as if a GET request was received but to not deliver the actual content. Here are some examples: from flask import request @app. If your application is placed outside the URL root . URL building will handle escaping of special characters and Unicode data trans- parently for you.4. but it is only interested in the headers. OPTIONS is implemented for you automatically as well. the underlying Werkzeug library handles that for you. In Flask you don’t have to deal with that at all. in /myapplication in- stead of / .route('/login'.

the only methods a form can submit to the server are GET and POST. DELETE Remove the information at the given location. So if your application is a module. filename='style. breaking things.5 Static Files Dynamic web applications also need static files.html'. For instance.css. All you have to do is provide the name of the template and the variables you want to pass to the template engine as keyword arguments. if it’s a package it’s actually inside your package: Case 1: a module: 18 . many revision control systems use it. That’s usually where the CSS and JavaScript files are coming from.6 Rendering Templates Generating HTML from within Python is not fun. Here’s a simple example of how to render a template: from flask import render_template @app. But with JavaScript and future HTML standards you can use the other methods as well. use the special 'static' endpoint name: url_for('static'. Ideally your web server is configured to serve them for you.route('/hello/') @app.css') The file has to be stored on the filesystem as static/style. OPTIONS Provides a quick way for a client to figure out which methods are supported by this URL. Starting with Flask 0. Just create a folder called static in your package or next to your module and it will be available at /static on the application. this folder is next to that module. name=name) Flask will look for templates in the templates folder. this is implemented for you automatically. Now the interesting part is that in HTML4 and XHTML1.route('/hello/<name>') def hello(name=None): return render_template('hello. and actually pretty cumbersome be- cause you have to do the HTML escaping on your own to keep the application secure. but during development Flask can do that as well. With POST that would not be possible because it must only be triggered once. Furthermore HTTP has become quite popular lately and browsers are no longer the only clients that are using HTTP. Because of that Flask configures the Jinja2 template engine for you automatically. To generate URLs for static files.6. 4. 4. To render a template you can use the render_template() method.

/application. HTML'). Here is an example template: <!doctype html> <title>Hello from Flask</title> {% if name %} <h1>Hello {{ name }}!</h1> {% else %} <h1>Hello. so if name contains HTML it will be escaped automati- cally. If you want to know how that works. Automatic escaping is enabled. Templates are especially useful if inheritance is used. 19 .hacker&lt. The 1Unsure what that g object is? It’s something in which you can store information for your own needs.striptags() u'Marked up \xbb HTML' Changed in version 0.hacker&lt. navigation and footer).escape('<blink>hacker</blink>') Markup(u'&lt.py /templates /hello.html Case 2: a package: /application /__init__. check the documentation of that object (g) and the Using SQLite 3 with Flask for more information. session and g1 objects as well as the get_flashed_messages() function./blink&gt./blink&gt. If you can trust a variable and you know that it will be safe HTML (for example because it came from a module that converts wiki markup to HTML) you can mark it as safe by using the Markup class or by using the |safe filter in the template.') >>> Markup('<em>Marked up</em> &raquo. Head over to the official Jinja2 Template Documentation for more information.html For templates you can use the full power of Jinja2 templates. Here is a basic introduction to how the Markup class works: >>> from flask import Markup >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>' Markup(u'<strong>Hello &lt. Head over to the Jinja 2 documentation for more examples.blink&gt. World!</h1> {% endif %} Inside templates you also have access to the request.!</strong>') >>> Markup. Basically tem- plate inheritance makes it possible to keep certain elements on each page (like header.5: Autoescaping is no longer enabled for all templates. head over to the Template Inheritance pattern documentation.blink&gt.py /templates /hello.

but not of the usual kind. .7 Accessing Request Data For web applications it’s crucial to react to the data a client sends to the server. When Flask starts its inter- nal request handling it figures out that the current thread is the active context and binds the current application and the WSGI environments to that context (thread). such as basic assertions: assert request. otherwise just skip it. . So what does this mean to you? Basically you can completely ignore that this is the case unless you are doing something like unit testing. The solution is creating a request object yourself and binding it to the context. read this section. Certain objects in Flask are global objects. It does that in an intelligent way so that one application can invoke another application without breaking. 4. Here is an example: from flask import request with app.path == '/hello' assert request. method='POST'): # now you can do something with the request until the # end of the with block.method == 'POST' 20 .1 Context Locals Insider Information If you want to understand how that works and how you can implement tests with context locals. If you have some experience with Python you might be wondering how that object can be global and how Flask manages to still be threadsafe. But that is actually quite easy to understand. . Templates loaded from a string will have autoescaping disabled. The answer is context locals: 4.xml. Imagine the context being the handling thread. the underlying object is capable of dealing with concurrency systems other than threads). In Flask this information is provided by the global request object. In combination with the with statement it will bind a test request so that you can interact with it.following extensions for templates trigger autoescaping: .xhtml. What a mouthful.7. The easiest solution for unit testing is to use the test_request_context() context manager. You will notice that code which depends on a request object will suddenly break because there is no request object.html. A request comes in and the web server decides to spawn a new thread (or something else. These objects are actually proxies to objects that are local to a specific context.htm.test_request_context('/hello'.

route('/login'.method == 'POST' 4.args.The other possibility is passing a whole WSGI environment to the request_context() method: from flask import request with app. To access parameters submitted in the URL (?key=value) you can use the args at- tribute: searchword = request. 21 . a HTTP 400 Bad Request error page is shown instead. 'GET']) def login(): error = None if request.method == 'POST': if valid_login(request. You can catch it like a standard KeyError but if you don’t do that.2 The Request Object The request object is documented in the API section and we will not cover it here in detail (see request).form['password']): return log_the_user_in(request. error=error) What happens if the key does not exist in the form attribute? In that case a special KeyError is raised. '') We recommend accessing URL parameters with get or by catching the KeyError be- cause users might change the URL and presenting them a 400 bad request page in that case is not user friendly. request.html'.form['username'].get('key'.form['username']) else: error = 'Invalid username/password' # the code below is executed if the request method # was GET or the credentials were invalid return render_template('login. First of all you have to import it from the flask module: from flask import request The current request method is available by using the method attribute. methods=['POST'. To access form data (data transmitted in a POST or PUT request) you can use the form attribute. Here is a full example of the two attributes mentioned above: @app.7. For a full list of methods and attributes of the request object.request_context(environ): assert request. So for many situations you don’t have to deal with that problem. Here is a broad overview of some of the most common operations. head over to the request documentation.

'POST']) def upload_file(): if request.. Uploaded files are stored in memory or at a temporary location on the filesystem. Each uploaded file is stored in that dictionary. but it also has a save() method that allows you to store that file on the filesys- tem of the server..7..files['the_file'] f.3 File Uploads You can handle uploaded files with Flask easily. However please keep in mind that this value can be forged so never ever trust that value. It behaves just like a standard Python file object. You can access those files by looking at the files attribute on the request object.4.save('/var/www/uploads/' + secure_filename(f.route('/upload'.7. checkout the Uploading Files pattern.filename)) .. methods=['GET'.files['the_file'] f.utils import secure_filename @app. 4. 'POST']) def upload_file(): if request. The cookies attribute of request objects is a dictionary with all the cookies the client transmits.method == 'POST': f = request.txt') . you can access the filename attribute. If you want to use the file- name of the client to store the file on the server. methods=['GET'. To set cookies you can use the set_cookie method of response objects.4 Cookies To access cookies you can use the cookies attribute. do not use the cookies directly but instead use the Sessions in Flask that add some security on top of cookies for you.save('/var/www/uploads/uploaded_file.route('/upload'. Reading cookies: 22 . If you want to use sessions. otherwise the browser will not transmit your files at all. pass it through the secure_filename() function that Werkzeug provides for you: from flask import request from werkzeug. If you want to know how the file was named on the client before it was uploaded to your application. Here is a simple example showing how that works: from flask import request @app. For some better examples. Just make sure not to forget to set the enctype="multipart/form-data" attribute on your HTML form.method == 'POST': f = request.

route('/') def index(): return redirect(url_for('login')) @app.route('/login') def login(): abort(401) this_is_never_executed() This is a rather pointless example because a user will be redirected from the index to a page they cannot access (401 means access denied) but it shows how that works.)) resp. If you want to customize the error page. you can use the errorhandler() decorator: 23 .cookies.get(key) instead of cookies[key] to not get a # KeyError if the cookie is missing. 'the username') return resp Note that cookies are set on response objects. By default a black and white error page is shown for each error code.set_cookie('username'.8 Redirects and Errors To redirect a user to another endpoint.route('/') def index(): resp = make_response(render_template(.from flask import request @app.get('username') # use cookies. 4. use the abort() function: from flask import abort. Storing cookies: from flask import make_response @app. If you explicitly want to do that you can use the make_response() function and then modify it. use the redirect() function.route('/') def index(): username = request... Since you normally just return strings from the view functions Flask will convert them into response objects for you. url_for @app. Sometimes you might want to set a cookie at a point where the response object does not exist yet. to abort a request early with an error code. This is possible by utilizing the Deferred Request Callbacks pattern. For this also see About Responses. redirect.

Such tuples have to be in the form (response. headers) where at least one item has to be in the tuple.errorhandler(404) def not_found(error): return render_template('error. The status value will override the status code and headers can be a list or dictionary of additional header values. If a tuple is returned the items in the tuple can provide extra information. By default 200 is assumed which translates to: all went well. 3.html'). 4. This tells Flask that the status code of that page should be 404 which means not found. Imagine you have a view like this: @app.9 About Responses The return value from a view function is automatically converted into a response ob- ject for you. headers) or (response.errorhandler(404) def not_found(error): resp = make_response(render_template('error. status. See Error handlers for more details. If the return value is a string it’s converted into a response object with the string as response body.html'). 404 You just need to wrap the return expression with make_response() and get the re- sponse object to modify it.html'). a 200 OK status code and a text/html mimetype.errorhandler(404) def page_not_found(error): return render_template('page_not_found. 2. The logic that Flask applies to converting return values into response objects is as follows: 1. 404 Note the 404 after the render_template() call.from flask import render_template @app. a response object is created with that data and the default param- eters. If it’s a string. If none of that works. Flask will assume the return value is a valid WSGI appli- cation and convert that into a response object. 4. 404) 24 . If you want to get hold of the resulting response object inside the view you can use the make_response() function. then return it: @app. If a response object of the correct type is returned it’s directly returned from the view.

What this means is that the user could look at the contents of your cookie but not modify it. keep this really secret: app. redirect. How to generate good secret keys 25 .headers['X-Something'] = 'A value' return resp 4. This is implemented on top of cookies for you and signs the cookies cryptographically.method == 'POST': session['username'] = request.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/. request app = Flask(__name__) @app. session. escape. url_for.pop('username'. Here is how sessions work: from flask import Flask.form['username'] return redirect(url_for('index')) return ''' <form method="post"> <p><input type=text name=username> <p><input type=submit value=Login> </form> ''' @app. None) return redirect(url_for('index')) # set the secret key. methods=['GET'. unless they know the secret key used for signing.route('/') def index(): if 'username' in session: return 'Logged in as %s' % escape(session['username']) return 'You are not logged in' @app. 'POST']) def login(): if request.10 Sessions In addition to the request object there is also a second object called session which allows you to store information specific to a user from one request to the next. resp. In order to use sessions you have to set a secret key.route('/login'.route('/logout') def logout(): # remove the username from the session if it's there session.?RT' The escape() mentioned here does escaping for you if you are not using the template engine (as in this example).

5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8' Just take that thing and copy/paste it into your code and you're done. To flash a message use the flash() method. if you want to handle sessions on the server-side instead. This is where loggers come in handy.urandom(24) '\xfd{H\xe5<\x95\xf9\xe3\x96. You may still want to log that something fishy happened. but actually is not. Flask provides a really simple way to give feedback to a user with the flashing system. And a secret key should be as random as possible.11 Message Flashing Good applications and user interfaces are all about feedback. 4. but sometimes that won’t do and the code has to continue working. As of Flask 0.12 Logging New in version 0. 4. If the user does not get enough feedback they will probably end up hating the application. The flashing system basically makes it possible to record a message at the end of a request and access it on the next (and only the next) request.The problem with random is that it’s hard to judge what is truly random. Besides the default client-side based sessions. For example you may have some client-side code that sends an HTTP request to the server but it’s obviously malformed. This might be caused by a user tampering with the data. Check out the Mes- sage Flashing for a full example. This is usually combined with a layout template to expose the message. to get hold of the messages you can use get_flashed_messages() which is also available in the templates. A note on cookie-based sessions: Flask will take the values you put into the session object and serialize them into a cookie. check the size of the cookie in your page responses compared to the size supported by web browsers. cookies are indeed enabled. there are several Flask extensions that support this.3 a logger is preconfigured for you to use. Sometimes you might be in a situation where you deal with data that should be correct. or the client code failing. and you are not getting a clear error message. If you are finding some values do not per- sist across requests. 26 . Most of the time it’s okay to reply with 400 Bad Request in that situation.3. Your operating system has ways to generate pretty random stuff based on a cryptographic random generator which can be used to get such a key: >>> import os >>> os.

wsgi_app = LighttpdCGIRootFix(app.13 Hooking in WSGI Middlewares If you want to add a WSGI middleware to your application you can wrap the internal WSGI application.Here are some example log calls: app.15 Deploying to a Web Server Ready to deploy your new Flask app? Go to Deployment Options.logger. 27 .fixers import LighttpdCGIRootFix app.14 Using Flask Extensions Extensions are packages that help you accomplish common tasks. so head over to the official logging documentation for more information.logger. have a look at Flask Extensions.debug('A value for debugging') app. Read more on Application Errors. 4.logger. For more on Flask extensions.warning('A warning occurred (%d apples)'. For example if you want to use one of the middlewares from the Werkzeug package to work around bugs in lighttpd.contrib.wsgi_app) 4. For example.error('An error occurred') The attached logger is a standard logging Logger. 4. 42) app. you can do it like this: from werkzeug. Flask- SQLAlchemy provides SQLAlchemy support that makes it simple and easy to use with Flask.

28 .

SQLite3 will be used directly for this application because it’s good enough for an ap- plication of this size. Let the user sign in and out with credentials specified in the configuration. it makes a lot of sense to use SQLAlchemy. but it still features everything you need to get started.) Essentially. 2. It only supports one user that can create text-only entries and there are no feeds or comments. it will do the following things: 1. but feel free to choose your own less Web-2. check out the example source. as it handles database connections in a more intelligent way. If you want the full source code in advance or for comparison.0-ish name . they can add new entries to the page consisting of a text-only title and some HTML for the text. For larger applications.1 Introducing Flaskr This tutorial will demonstrate a blogging application named Flaskr. Here a screenshot of the final application: 29 . The index page shows all entries so far in reverse chronological order (newest on top) and the user can add new ones from there if logged in. 5. You might also want to consider one of the popular NoSQL databases if your data is more suited for those. however. we will create a simple microblogging application. allowing you to target different relational databases at once and more. Only one user is supported. CHAPTER FIVE TUTORIAL You want to develop an application with Python and Flask? Here you have the chance to learn by example. When the user is logged in. In this tutorial. This HTML is not sanitized because we trust the user here. 3. We will use Flask and SQLite as a database (which comes out of the box with Python) so there is nothing else you need.

the files inside of the static folder are available to users of the application via HTTP. Flask will look for Jinja2 templates. Inside the templates folder. 30 .2 Step 0: Creating The Folders Before getting started. For now go ahead and create the applications directory structure. This is the recommended way to install and run Flask applications.Continue with Step 0: Creating The Folders. In the next few steps you will be creating the database schema as well as the main module. you will need to create the folders needed for this application: /flaskr /flaskr /static /templates The application will be installed and run as Python package. As a quick side note. 5. You will see examples of this later on. You will see exactly how to run flaskr later on in this tutorial. This is the place where CSS and JavaScript files go.

db'). you will create the database schema. All you need to do is put the following contents into a file named schema.config. redirect.config. abort. it is possible to drop the configuration directly into the module. session. 5.join(app. you can create the application module. and a text. url_for. The first several lines of code in the application module are the needed import statements. a cleaner solution is to create a separate . load that.path. 'flaskr.py. 31 .4 Step 2: Application Setup Code Now that the schema is in place. After that there will be a few lines of configuration code.ini or .sql in the flaskr/flaskr folder: drop table if exists entries. Here are the import statements (in flaskr.py # Load default config and override config from an environment variable app. the other two are strings that must not be null. create table entries ( id integer primary key autoincrement. Each row in this table has an id.update(dict( DATABASE=os.py: app = Flask(__name__) # create the application instance :) app. flaskr. and import the values from there. request. Continue with Step 2: Application Setup Code.3 Step 1: Database Schema In this step.py): # all the imports import os import sqlite3 from flask import Flask.py file.root_path. The id is an automatically incrementing integer and a primary key. This file should be placed inside of the flaskr/flaskr folder. g. flaskr. 5. \ render_template. title text not null. flash The next couple lines will create the actual application instance and initialize it with the config from the same file in flaskr. a title. For small applications like flaskr. This schema consists of a single table called entries. Only a single table is needed for this application and it will only support SQLite. However.from_object(__name__) # load config from this file .For now you should continue with Step 1: Database Schema. 'text' text not null ).

Unfortunately.config. you cannot depend on this in web applications because you might have more than one application in the same process. you can use the from_object() method on the config object and provide it with an import name of a module. SECRET_KEY='development key'.config. For a real-world application. only variable names that are uppercase are considered. Database Path Operating systems know the concept of a current working directory for each process. USERNAME='admin'. In addition to that. This enables robust configuration setups. app. it is a good idea to load a separate. Lastly. Choose that key wisely and as hard to guess and complex as possible. Note that in all cases. PASSWORD='default' )) app.""" rv = sqlite3. so it can be updated with new val- ues. The silent switch just tells Flask to not complain if no such environment key is set. we place the database right next to it. In this example. you will add a method that allows for easy connections to the specified database.connect(app.from_envvar('FLASKR_SETTINGS'. def connect_db(): """Connects to the specific database.Row object to represent rows.config['DATABASE']) 32 . You can create a simple database connection through SQLite and then tell it to use the sqlite3. Together with the os.path module. silent=True) The Config object works similarly to a dictionary.root_path attribute can be used to get the path to the applica- tion. it’s recommended to use Instance Folders instead. The SECRET_KEY is needed to keep the client-side sessions secure. Flask allows you to import multiple configurations and it will use the setting defined in the last import. Flask will then initialize the variable from that module. For this reason the app. This can be used to open a connection on request and also from the inter- active Python shell or a script. files can then easily be found. from_envvar() can help achieve this. environment-specific configuration file. silent=True) Simply define the environment variable FLASKR_SETTINGS that points to a config file to be loaded.from_envvar('FLASKR_SETTINGS'. This allows the rows to be treated as if they were dictionaries instead of tuples. This will come in handy later. Usually.

in and add the following lines: 33 .py and MANIFEST. it is also necessary to specify any special files that should be included in your package (in the MANIFEST. ) When using setuptools.Row return rv In the next section you will see how to run the application. packages=['flaskr'].5 Step 3: Installing flaskr as a Package Flask is now shipped with built-in support for Click.py /static /templates flaskr. include_package_data=True. After these changes.py MANIFEST.row_factory = sqlite3. Click provides Flask with en- hanced and extensible command line utilities.in).py schema. rv. the static and templates directories need to be included. setup.sql setup.py file for flaskr is: from setuptools import setup setup( name='flaskr'. 5.in in the projects root directory. A useful pattern to manage a Flask application is to install your app following the Python Packaging Guide. Presently this involves creating two new files. install_requires=[ 'flask'.in The content of the setup. as well as the schema. Later in this tutorial you will see exactly how to extend the flask command line interface (CLI). Continue with Step 3: Installing flaskr as a Package. In this case.py file to make the flaskr/flaskr directory a package. ]. You also need to add an __init__. your code structure should be: /flaskr /flaskr __init__. Create the MANIFEST.

This import statement simplifies the location process. Externally Visible Server Want your server to be publicly available? Check out the externally visible server section for more information. That will be addressed a little later. the Flask development server needs the location of the app instance. Continue with Step 4: Database Connections. The flaskr app is now installed in your virtualenv (see output of pip freeze). 34 . Do this with the following commands: export FLASK_APP=flaskr export FLASK_DEBUG=true flask run (In case you are on Windows you need to use set instead of export).graft flaskr/templates graft flaskr/static include flaskr/schema. flaskr/. With that said. because it will allow users to execute code on the server! You will see a message telling you that server has started along with the address at which you can access it. but first.py: from . With that out of the way. flaskr/__init__.flaskr.sql To simplify locating the application. When you head over to the server in your browser. As usual. go ahead and install the application with: pip install --editable . you will get a 404 error because we don’t have any views yet. Never leave debug mode activated in a production system. you should be able to start up the application. it is recommended to install your Flask application within a virtualenv. The above installation command assumes that it is run within the projects root direc- tory. Without it the export statement a few steps below would need to be export FLASK_APP=flaskr. The editable flag allows editing source code without having to reinstall the Flask app each time you make changes. add the following import statement into this file. When it is time to run the application. you should get the database working. At this point you should be able to install the application.flaskr import app This import statement brings the application instance into the top-level of the appli- cation package. The FLASK_DEBUG flag enables or disables the interactive debugger.

in which case the error is passed to the teardown function. 35 . The first time the function is called. but how can you properly disconnect? For that. 'sqlite_db'): g.close() Functions marked with teardown_appcontext() are called every time the app context tears down. it is not particularly useful. For the time being. so you will need to keep it around for longer. Because database connections encapsulate a transaction.teardown_appcontext def close_db(error): """Closes the database again at the end of the request. whereas g is a general purpose variable associated with the current application con- text. It’s executed every time the application context tears down: @app.6 Step 4: Database Connections You currently have a function for establishing a database connection with connect_db. The tutorial will cover some more details of this later on. A tear- down can happen because of two reasons: either everything went well (the error pa- rameter will be None) or an exception happened. all you have to know is that you can store information safely on the g object. Flask provides two contexts: the application context and the request context. you will need to make sure that only one request at a time uses the connection. For in- stance. Continue to Step 5: Creating The Database. An elegant way to do this is by utilizing the application context. but by itself. """ if not hasattr(g. the app context is created before the request comes in and is destroyed (torn down) whenever the request finishes.sqlite_db. the request variable is the request object associated with the current request.5. So when do you put it on there? To do that you can make a helper function.""" if hasattr(g. Flask provides us with the teardown_appcontext() decorator. all you have to know is that there are special variables that use these. For the time being. 'sqlite_db'): g. and successive calls will return the already established connection: def get_db(): """Opens a new database connection if there is none yet for the current application context. it will create a database connection for the current context. What does this mean? Essentially.sqlite_db Now you know how to connect. Creating and closing database connections all the time is very inefficient.sqlite_db = connect_db() return g. Curious about what these contexts mean? Have a look at the The Application Context documentation to learn more.

take a look at how the example source is organized. you can create a function and hook it into a flask command that initializes the database.cli. you might be wondering where to put the code from this step and the next. which can introduce errors.Hint: Where do I put this code? If you’ve been following along in this tutorial. Flaskr is a database powered application.command() decorator registers a new command with the flask script. A good place to add this function.cursor().executescript(f.sql The downside of this is that it requires the sqlite3 command to be installed. Within the function.command('initdb') def initdb_command(): """Initializes the database. which is not necessarily the case on every system. it is an application powered by a relational database system.sql'. you can then access 36 . it’s a good idea not to.') The app.sql file into the sqlite3 command as follows: sqlite3 /tmp/flaskr. to the application. Before starting the server for the first time. and put your new get_db and close_db functions below your ex- isting connect_db function (following the tutorial line-by-line).db < schema. In Flask.commit() @app. It’s a good idea to add a function that initializes the database for you. mode='r') as f: db. it’s important to create that schema.cli. If you need a moment to find your bearings. This also requires that you provide the path to the database.7 Step 5: Creating The Database As outlined earlier. you can put all of your application code into a single Python module. 5. is just below the connect_db function in flaskr. and more precisely. When the command executes.read()) db. Such systems need a schema that tells them how to store that information. and if your app grows larger. Flask will automatically create an application context which is bound to the right application. and command.py: def init_db(): db = get_db() with app. A logical place is to group these module-level functions together. For now just take a look at the code segment below. You don’t have to. To do this. Such a schema can be created by piping the schema.open_resource('schema.""" init_db() print('Initialized the database.

You will want to keep an actual function around that initializes the database. Troubleshooting If you get an exception later on stating that a table cannot be found. This function opens a file from the resource location (the flaskr/flaskr folder) and allows you to read from it. it is possible to create a database with the flask script: flask initdb Initialized the database. Finally. You will need four of them: 5.8 Step 6: The View Functions Now that the database connections are working. plural. Now.flask. you can start writing the view func- tions. the application context tears down and the database connection is released. The connection object provided by SQLite can give you a cursor object. When the script ends. though. The view function will pass the entries to the show_entries.Row row factory. (For more information see Testing Flask Applications.8. Continue with Step 6: The View Functions 5. so that we can easily create databases in unit tests later on. for example). there is a method to execute a complete script.g and other things as you might expect.1 Show Entries This view shows all the entries stored in the database. On that cur- sor. It is used in this example to execute a script on the database connection. The rows returned from the cursor look a bit like dictionaries because we are using the sqlite3.) The open_resource() method of the application object is a convenient helper function that will open a resource that the application provides.route('/') def show_entries(): 37 . you only have to commit the changes. check that you did execute the initdb command and that your table names are correct (singular vs. The one with the highest id (the newest entry) will be on top.html template and return the rendered one: @app. It listens on the root of the application and will select title and text from the database. SQLite3 and other transactional databases will not commit unless you explicitly tell it to.

method == 'POST': if request. if the logged_in key is present in the session and True). This only responds to POST requests. db = get_db() cur = db.route('/login'. text from entries order by id desc') entries = cur. the template is notified about that.execute('insert into entries (title.2 Add New Entry This view lets the user add new entries if they are logged in.execute('select title. it will flash() an information message to the next request and redirect back to the show_entries page: @app. text) values (?.form['title']. [request.fetchall() return render_template('show_entries. Otherwise.commit() flash('New entry was successfully posted') return redirect(url_for('show_entries')) Note that this view checks that the user is logged in (that is. If everything worked out well. 5.3 Login and Logout These functions are used to sign the user in and out.8. Login checks the username and password against the ones from the configuration and sets the logged_in key for the session. 'POST']) def login(): error = None if request. that key is set to True. request. as done in the example above.get('logged_in'): abort(401) db = get_db() db. your app will be vulnerable to SQL injection when you use string formatting to build SQL statements.config['USERNAME']: 38 . the actual form is shown on the show_entries page. and the user is asked again: @app. ?)'. methods=['GET'. See Using SQLite 3 with Flask for more. In addition. a message is flashed that informs the user that he or she was logged in successfully. If an error occurred. entries=entries) 5.form['text']]) db. If the user logged in successfully. Security Note Be sure to use question marks when building SQL statements.route('/add'.8. methods=['POST']) def add_entry(): if not session.html'.form['username'] != app. and the user is redi- rected back to the show_entries page.

removes that key from the session again. There are also many general python libraries that can be used for hashing. This means that unless you mark a value in the code with Markup or with the |safe filter in the template. If you plan to release a project based off this tutorial out into the world.config['PASSWORD']: error = 'Invalid password' else: session['logged_in'] = True flash('You were logged in') return redirect(url_for('show_entries')) return render_template('login.form['password'] != app. This is helpful because now it is not necessary to check if the user was logged in. 5. if you make requests with the app running.route('/logout') def logout(): session. passwords should be both hashed and salted before being stored in a database or file. the method will delete the key from the dictionary if present or do nothing when that key is not in there. You can find a list of recommended Flask extensions here Continue with Step 7: The Templates.pop('logged_in'. error = 'Invalid username' elif request. This tutorial uses plain text passwords for simplicity. Jinja2 will ensure that special characters such as < or > are escaped with their XML equivalents. @app.9 Step 7: The Templates Now it is time to start working on the templates. error=error) The logout function. there are Flask extensions for the purpose of hashing passwords and veri- fying passwords against hashes. Fortunately. None) flash('You were logged out') return redirect(url_for('show_entries')) Security Note Passwords should never be stored in plain text in a production system.html'. There is a neat trick here: if you use the pop() method of the dict and pass a second parameter to it (the default). 39 . As you may have noticed. you will get an exception that Flask cannot find the templates. We are also using template inheritance which makes it possible to reuse the layout of the website in all pages. so adding this functionality is fairly straight forward. The templates are using Jinja2 syntax and have autoescaping enabled by default. on the other hand.

9. Notice that the form is configured to to submit to the add_entry view function and use POST as HTTP method: {% extends "layout.→') }}"> <div class=page> <h1>Flaskr</h1> <div class=metanav> {% if not session.9. Note that the for loop iterates over the messages we passed in with the render_template() function. The session dict is available in the template as well and you can use that to check if the user is logged in or not.html" %} {% block body %} {% if session.1 layout. Note that in Jinja you can access missing attributes and items of objects / dicts which makes the following code work.Put the following templates into the templates folder: 5.logged_in %} <a href="{{ url_for('login') }}">log in</a> {% else %} <a href="{{ url_for('logout') }}">log out</a> {% endif %} </div> {% for message in get_flashed_messages() %} <div class=flash>{{ message }}</div> {% endfor %} {% block body %}{% endblock %} </div> 5.logged_in %} <form action="{{ url_for('add_entry') }}" method=post class=add-entry> <dl> <dt>Title: <dd><input type=text size=30 name=title> <dt>Text: 40 .2 show_entries. It also displays the flashed messages if there are any.html template from above to display the mes- sages.html This template extends the layout. filename='style.css .html This template contains the HTML skeleton. the header and a link to log in (or log out if the user was already logged in). even if there is no 'logged_in' key in the session: <!doctype html> <title>Flaskr</title> <link rel=stylesheet type=text/css href="{{ url_for('static'. The {% block body %} block can be replaced by a block of the same name (body) in a child template.

text|safe }} {% else %} <li><em>Unbelievable.3 login.css in the static folder: body { font-family: sans-serif.title }}</h2>{{ entry. h2 { color: #377ba8.2em.html This is the login template. serif. background: #eee. No entries here so far</em> {% endfor %} </ul> {% endblock %} 5. h2 { font-family: 'Georgia'.html" %} {% block body %} <h2>Login</h2> {% if error %}<p class=error><strong>Error:</strong> {{ error }}{% endif %} <form action="{{ url_for('login') }}" method=post> <dl> <dt>Username: <dd><input type=text name=username> <dt>Password: <dd><input type=password name=password> <dd><input type=submit value=Login> </dl> </form> {% endblock %} Continue with Step 8: Adding Style. } h1. } a.9.10 Step 8: Adding Style Now that everything else works. h1. which basically just displays a form to allow the user to login: {% extends "layout. } 41 . } h1 { border-bottom: 2px solid #eee. <dd><textarea name=text rows=5 cols=40></textarea> <dd><input type=submit value=Share> </dl> </form> {% endif %} <ul class=entries> {% for entry in entries %} <li><h2>{{ entry. margin: 0. Just create a stylesheet called style. it’s time to add some style to the application. } h2 { font-size: 1. 5.

metanav { text-align: right.. you might be wondering about ways to organize the project.9em. } . margin: 0. The application above is used as a basic example of how to perform unit testing in the Testing Flask Applications section of the documentation.add-entry dl { font-weight: bold.in For now go ahead a create the tests/ directory as well as the test_flaskr. border-bottom: 1px solid #ccc. } . } . padding: 0. } .py setup.1 Adding tests to flaskr Assuming you have seen the Testing Flask Applications section and have either written your own tests for flaskr or have followed along with the examples provided. padding: 0. } .11.3em.5em.2em. border: 1px solid #aacbe2. border: 5px solid #ccc.8em.entries li { margin: 0.8em.add-entry { font-size: 0.py file. } . background: white. Go there to see how easy it is to test Flask applications. padding: 0.8em 1.2 Running the tests At this point you can run the tests. } .py MANIFEST. width: 35em. Here pytest will be used. One possible and recommended project structure is: flaskr/ flaskr/ __init__. } Continue with Bonus: Testing the Application.error { background: #f0d6d6.flash { background: #cee5F5. it’s probably not a bad idea to add automated tests to simplify modifications in the future. 5. 42 .entries { list-style: none. font-size: 0. padding: 0. margin-bottom: 1em.py static/ templates/ tests/ test_flaskr.5em.entries li h2 { margin-left: -1em. background: #fafafa.11.11 Bonus: Testing the Application Now that you have finished the application and everything works as expected. padding: 0. 5.page { margin: 2em auto. } . 5.

].py file and creating a new file setup. within the top-level flaskr/ directory as: py.py script has been called. run.test 5. Here that requires adding a couple of lines to the setup. (Recall the setup_requires ar- gument in setup. ) Now create setup.py): [aliases] test=pytest Now you can run: python setup.py file to contain: from setuptools import setup setup( name='flaskr'. Otherwise pytest test will not be able to import the required components to test the application: pip install -e . as the setup. and hopefully pass. install_requires=[ 'flask'. pip install pytest Run and watch the tests pass. setup_requires=[ 'pytest-runner'.cfg which in turn runs pytest via pytest-runner.cfg in the project root (alongside setup. packages=['flaskr']. 43 . ]. tests_require=[ 'pytest'. Go ahead and update the setup.11.Note: Make sure that pytest is installed in the same virtualenv as flaskr.cfg. ]. One benefit of running the tests this way is that you do not have to install pytest. include_package_data=True.py) Following the standard rules of test-discovery your tests will be found.3 Testing + setuptools One way to handle testing is to integrate it with setuptools.py test This calls on the alias created in setup.

This is one possible way to run and manage testing. Here pytest is used. Integrating testing with setuptools is convenient because it is not necessary to actually download pytest or any other testing framework one might use. 44 . but there are other options such as nose.

1 Jinja Setup Unless customized. 6. This requirement is necessary to enable rich extensions.xhtml when using render_template().10: This is now always available. Changed in version 0. 6.6. An extension can depend on Jinja2 being present. even in imported tem- plates.xml as well as .html. You are obviously free to use a different tem- plate engine.htm.2 Standard Context The following global variables are available within Jinja2 templates by default: config The current configuration object (flask. 45 . • Flask inserts a couple of global functions and helpers into the Jinja2 context. This section only gives a very quick introduction into how Jinja2 is integrated into Flask. • a template has the ability to opt in/out autoescaping with the {% autoescape %} tag. .config) New in version 0. but you still have to install Jinja2 to run Flask itself. Jinja2 is configured by Flask as follows: • autoescaping is enabled for all templates ending in . • autoescaping is enabled for all strings when using render_template_string(). CHAPTER SIX TEMPLATES Flask leverages Jinja2 as template engine. . head over to the official Jinja2 Template Documentation for more information. If you want information on the template engine’s syntax itself. ad- ditionally to the values that are present by default.

that needs to access the request object you have two possibilities: 1.g).3 Standard Filters These filters are available in Jinja2 additionally to the filters provided by Jinja2 itself: tojson() This function converts the given object into JSON representation.session). g The request-bound object for global variables (flask. The difference is that by default these will not show up in the context of imported templates.10 if you intend to use it inside script tags: 46 . Note that inside script tags no escaping must take place.request). so make sure to disable escaping with |safe before Flask 0. partially to keep things explicit. get_flashed_messages() The flask. or the attribute of the request object you are interested in. The Jinja Context Behavior These variables are added to the context of variables.get_flashed_messages() function. What does this mean for you? If you have a macro you want to import. 2. you explicitly pass the request to the macro as parameter. Importing with context looks like this: {% from '_helpers. you import the macro “with context”. This variable is unavailable if the template was rendered without an active request context. This variable is unavailable if the template was rendered without an active request context. they are not global variables. url_for() The flask.html' import my_macro with context %} 6. This variable is unavail- able if the template was rendered without an active request context. This is for example very helpful if you try to generate JavaScript on the fly.url_for() function. session The current session object (flask.request The current request object (flask. This is partially caused by performance considerations.

To disable the autoescape system in templates.template_filter('reverse') def reverse_filter(s): 47 . but can also lead to security problems. • Inside the template. wrap the HTML string in a Markup object before passing it to the template. for example if they come from a system that generates secure HTML like a markdown to HTML converter. Because these characters carry specific meanings in documents on their own you have to replace them by so called “entities” if you want to use them for text.5 Registering Filters If you want to register your own filters in Jinja2 you have two ways to do that. <.username|tojson|safe }}). please be very cautious about the variables you are using in this block. <script type=text/javascript> doSomethingWith({{ user. and thus XHTML) are &. There are three ways to accomplish that: • In the Python code. >. you can use the {% autoescape %} block: {% autoescape false %} <p>autoescaping is disabled here <p>{{ will_not_be_escaped }} {% endautoescape %} Whenever you do this. Spe- cial characters in the sense of HTML (or XML. Not doing so would not only cause user frustration by the inability to use these characters in text. 6. This is in general the recommended way.4 Controlling Autoescaping Autoescaping is the concept of automatically escaping special characters for you. This can be the case if you want to explicitly inject HTML into pages. (see Cross-Site Scripting (XSS)) Sometimes however you will need to disable autoescaping in templates. You can either put them by hand into the jinja_env of the application or use the template_filter() decorator. use the |safe filter to explicitly mark a string as safe HTML ({{ myvariable|safe }}) • Temporarily disable the autoescape system altogether. </script> 6. " as well as '. The two following examples work the same and both reverse an object: @app.

filters['reverse'] = reverse_filter In case of the decorator the argument is optional if you want to use the function name as name of the filter.6 Context Processors To inject new variables automatically into the context of a template. for example if you have a Python list in context called mylist: {% for x in mylist | reverse %} {% endfor %} 6.2f}{1}'.33) }} You could also build format_price as a template filter (see Registering Filters).context_processor def utility_processor(): def format_price(amount.user) The context processor above makes a variable called user available in the template with the value of g. The keys and values of this dictionary are then merged with the template context. you can use the filter in your templates in the same way as Jinja2’s builtin filters. return s[::-1] def reverse_filter(s): return s[::-1] app. but it gives an idea how this works. currency=u''): return u'{0:. currency) return dict(format_price=format_price) The context processor above makes the format_price function available to all templates: {{ format_price(0. context processors exist in Flask. for all templates in the app: @app. A context processor is a function that returns a dictionary. a context processor can also make functions avail- able to templates (since Python allows passing around functions): @app. This example is not very interesting because g is available in templates anyways. Context processors run before the template is rendered and have the ability to inject new values into the template context. Variables are not limited to values.context_processor def inject_user(): return dict(user=g.jinja_env. Once registered. but this demonstrates how to pass functions in a context processor.format(amount.user. 48 .

app = flaskr.2 The Testing Skeleton In order to test the application. CHAPTER SEVEN TESTING FLASK APPLICATIONS Something that is untested is broken. we need an application to test. flaskr. get the sources from the examples. If you don’t have that application yet. we add a second module (flaskr_tests.config['DATABASE'] = tempfile.py) and create a unittest skeleton there: import os import flaskr import unittest import tempfile class FlaskrTestCase(unittest. we will use the application from the Tutorial. you can safely make changes and instantly know if anything breaks. 7.1 The Application First. If an application has automated tests.app. The origin of this quote is unknown and while it is not entirely correct.app.test_client() 49 .config['TESTING'] = True self. Untested applications make it hard to improve existing code and developers of untested applications tend to become pretty paranoid. In this documentation we will use the unittest package that comes pre-installed with Python. it is also not far from the truth. 7.db_fd.app.mkstemp() flaskr. Flask provides a way to test your application by exposing the Werkzeug test Client and handling the context locals for you.TestCase): def setUp(self): self. You can then use that with your favourite testing solution.

config['DATABASE']) if __name__ == '__main__': unittest.000s OK Even though it did not run any actual tests. Additionally during setup the TESTING config flag is activated. and the client will also keep track of cookies for us.unlink(flaskr.db_fd. To do this. We can trigger test requests to the application. we add a new test method to our class.init_db() def tearDown(self): os.test_client() 50 .app = flaskr.py ---------------------------------------------------------------------- Ran 0 tests in 0. the latter we use as database name.TestCase): def setUp(self): self. flaskr.config['DATABASE'] = tempfile. Let’s check that the application shows “No entries here so far” if we access the root of the application (/). This test client will give us a simple interface to the application.mkstemp() self. To delete the database after the test.3 The First Test Now it’s time to start testing the functionality of the application.close(self. with flaskr.app.db_fd) os. 7.app_context(): flaskr. This function is called before each individual test function is run.app.app. otherwise the import would have died with an exception. Because SQLite3 is filesystem-based we can easily use the tempfile module to create a temporary database and initialize it. What it does is disable the error catching during request handling so that you get bet- ter error reports when performing test requests against the application. If we now run the test suite. The mkstemp() function does two things for us: it returns a low-level file handle and a random file name. we already know that our flaskr applica- tion is syntactically valid.main() The code in the setUp() method creates a new test client and initializes a new database. we should see the following output: $ python flaskr_tests.app. like this: class FlaskrTestCase(unittest. close() function to close the file. we close the file and remove it from the filesystem in the tearDown() method. We just have to keep the db_fd around so that we can use the os.

flaskr.init_db()

def tearDown(self):
os.close(self.db_fd)
os.unlink(flaskr.app.config['DATABASE'])

def test_empty_db(self):
rv = self.app.get('/')
assert b'No entries here so far' in rv.data

Notice that our test functions begin with the word test; this allows unittest to auto-
matically identify the method as a test to run.
By using self.app.get we can send an HTTP GET request to the application with the
given path. The return value will be a response_class object. We can now use the
data attribute to inspect the return value (as string) from the application. In this case,
we ensure that 'No entries here so far' is part of the output.
Run it again and you should see one passing test:

$ python flaskr_tests.py
.
----------------------------------------------------------------------
Ran 1 test in 0.034s

OK

7.4 Logging In and Out

The majority of the functionality of our application is only available for the adminis-
trative user, so we need a way to log our test client in and out of the application. To do
this, we fire some requests to the login and logout pages with the required form data
(username and password). And because the login and logout pages redirect, we tell
the client to follow_redirects.
Add the following two methods to your FlaskrTestCase class:

def login(self, username, password):
return self.app.post('/login', data=dict(
username=username,
password=password
), follow_redirects=True)

def logout(self):
return self.app.get('/logout', follow_redirects=True)

Now we can easily test that logging in and out works and that it fails with invalid
credentials. Add this new test to the class:

51

def test_login_logout(self):
rv = self.login('admin', 'default')
assert b'You were logged in' in rv.data
rv = self.logout()
assert b'You were logged out' in rv.data
rv = self.login('adminx', 'default')
assert b'Invalid username' in rv.data
rv = self.login('admin', 'defaultx')
assert b'Invalid password' in rv.data

7.5 Test Adding Messages

We should also test that adding messages works. Add a new test method like this:

def test_messages(self):
self.login('admin', 'default')
rv = self.app.post('/add', data=dict(
title='<Hello>',
text='<strong>HTML</strong> allowed here'
), follow_redirects=True)
assert b'No entries here so far' not in rv.data
assert b'&lt;Hello&gt;' in rv.data
assert b'<strong>HTML</strong> allowed here' in rv.data

Here we check that HTML is allowed in the text but not in the title, which is the in-
tended behavior.
Running that should now give us three passing tests:

$ python flaskr_tests.py
...
----------------------------------------------------------------------
Ran 3 tests in 0.332s

OK

For more complex tests with headers and status codes, check out the MiniTwit Exam-
ple from the sources which contains a larger test suite.

7.6 Other Testing Tricks

Besides using the test client as shown above, there is also the test_request_context()
method that can be used in combination with the with statement to activate a request
context temporarily. With this you can access the request, g and session objects like
in view functions. Here is a full example that demonstrates this approach:

52

import flask

app = flask.Flask(__name__)

with app.test_request_context('/?name=Peter'):
assert flask.request.path == '/'
assert flask.request.args['name'] == 'Peter'

All the other objects that are context bound can be used in the same way.
If you want to test your application with different configurations and there does not
seem to be a good way to do that, consider switching to application factories (see
Application Factories).
Note however that if you are using a test request context, the before_request()
and after_request() functions are not called automatically. However
teardown_request() functions are indeed executed when the test request con-
text leaves the with block. If you do want the before_request() functions to be called
as well, you need to call preprocess_request() yourself:
app = flask.Flask(__name__)

with app.test_request_context('/?name=Peter'):
app.preprocess_request()
...

This can be necessary to open database connections or something similar depending
on how your application was designed.
If you want to call the after_request() functions you need to call into
process_response() which however requires that you pass it a response object:
app = flask.Flask(__name__)

with app.test_request_context('/?name=Peter'):
resp = Response('...')
resp = app.process_response(resp)
...

This in general is less useful because at that point you can directly start using the test
client.

7.7 Faking Resources and Context

New in version 0.10.
A very common pattern is to store user authorization information and database con-
nections on the application context or the flask.g object. The general pattern for this is
to put the object on there on first usage and then to remove it on a teardown. Imagine
for instance this code to get the current user:

53

def get_user():
user = getattr(g, 'user', None)
if user is None:
user = fetch_current_user_from_database()
g.user = user
return user

For a test it would be nice to override this user from the outside without hav-
ing to change some code. This can be accomplished with hooking the flask.
appcontext_pushed signal:

from contextlib import contextmanager
from flask import appcontext_pushed, g

@contextmanager
def user_set(app, user):
def handler(sender, **kwargs):
g.user = user
with appcontext_pushed.connected_to(handler, app):
yield

And then to use it:

from flask import json, jsonify

@app.route('/users/me')
def users_me():
return jsonify(username=g.user.username)

with user_set(app, my_user):
with app.test_client() as c:
resp = c.get('/users/me')
data = json.loads(resp.data)
self.assert_equal(data['username'], my_user.username)

7.8 Keeping the Context Around

New in version 0.4.
Sometimes it is helpful to trigger a regular request but still keep the context around
for a little longer so that additional introspection can happen. With Flask 0.4 this is
possible by using the test_client() with a with block:

app = flask.Flask(__name__)

with app.test_client() as c:
rv = c.get('/?tequila=42')
assert request.args['tequila'] == '42'

54

If you were to use just the test_client() without the with block, the assert would
fail with an error because request is no longer available (because you are trying to use
it outside of the actual request).

7.9 Accessing and Modifying Sessions

New in version 0.8.
Sometimes it can be very helpful to access or modify the sessions from the test client.
Generally there are two ways for this. If you just want to ensure that a session has
certain keys set to certain values you can just keep the context around and access
flask.session:

with app.test_client() as c:
rv = c.get('/')
assert flask.session['foo'] == 42

This however does not make it possible to also modify the session or to access the ses-
sion before a request was fired. Starting with Flask 0.8 we provide a so called “session
transaction” which simulates the appropriate calls to open a session in the context of
the test client and to modify it. At the end of the transaction the session is stored. This
works independently of the session backend used:

with app.test_client() as c:
with c.session_transaction() as sess:
sess['a_key'] = 'a value'

# once this is reached the session was stored

Note that in this case you have to use the sess object instead of the flask.session
proxy. The object however itself will provide the same interface.

55

56

It’s available as an Open Source project on GitHub and is also available as a hosted version which you can try for free.1 Error Logging Tools Sending error mails. and sends you mails based on new errors or frequency thresholds. This is why we recommend using Sentry for dealing with application errors.3. Flask will display a very simple page for you and log the exception to the logger. you will still see exceptions from time to time. Even if your code is 100% correct. can become overwhelming if enough users are hitting the error and log files are typically never looked at. Applications fail. But there is more you can do. Here are some situations where perfectly fine code can lead to server errors: • the client terminated the request early and the application was still reading from the incoming data • the database server was overloaded and could not handle the query • a filesystem is full • a harddrive crashed • a backend server overloaded • a programming error in a library you are using • network connection of the server to another system failed And that’s just a small sample of issues you could be facing. CHAPTER EIGHT APPLICATION ERRORS New in version 0. Why? Because everything else involved will fail. servers fail. To use Sentry you need to install the raven client: 57 . even if just for critical ones. captures the full stack trace and local variables for debugging. and we will cover some better setups to deal with errors. Sooner or later you will see an exception in production. 8. So how do we deal with that sort of problem? By default if your application runs in production mode. Sentry aggregates duplicate errors.

register_error_handler(400. return app The YOUR_DSN_HERE value needs to be replaced with the DSN value you get from your Sentry installation.BadRequest) def handle_bad_request(e): return 'bad request!' app. Afterwards failures are automatically reported to Sentry and from there you can re- ceive error notifications.1 Registering Register error handlers using errorhandler() or register_error_handler(): @app..2 Error handlers You might want to show custom error pages to the user when an error occurs. This can be done by registering error handlers.flask import Sentry sentry = Sentry(app..exceptions. 8. they are registered for exceptions that are raised while trying to do something else.init_app(app) .errorhandler(werkzeug. code == 400). HTTPException subclasses like BadRequest from the example and their HTTP codes are interchangeable when handed to the registration methods or decorator (BadRequest.flask import Sentry sentry = Sentry(dsn='YOUR_DSN_HERE') def create_app(): app = Flask(__name__) sentry.exceptions. Note that werkzeug. but the first one is more clear and leaves you with a function to call on your whim (and in tests). lambda e: 'bad request!') Those two ways are equivalent. 8.contrib.contrib.2.$ pip install raven And then add this to your Flask app: from raven. dsn='YOUR_DSN_HERE') Or if you are using factories you can also init it later: from raven. Error handlers are normal Pluggable Views but instead of being registered for routes. 58 .

'server-error@example. ADMINS.com'. if an instance of ConnectionRefusedError is raised.addHandler(mail_handler) So what just happened? We created a new SMTPHandler that will send mails with the mail server listening on 127.handlers import SMTPHandler mail_handler = SMTPHandler('127. 59 .com with the subject “YourApplication Failed”.0.setLevel(logging.com'] if not app.3 Error Mails If the application runs in production mode (which it will do on your server) you might not see any log messages.g. these can also be provided. For that check out the documentation for the SMTPHandler. E. and searched for in the exception classes for which handlers are registered. The most specific handler is selected.0. 'YourApplication Failed') mail_handler.1 to all the ADMINS from the address server- error@example. 8.2 Handling Once an exception instance is raised. 8.logger. Flask uses the Python builtin logging system. Then you get an alert and you can do something about it. and its response is shown to the user.1'.debug: import logging from logging.11: Errorhandlers are now prioritized by specificity of the excep- tion classes they are registered for instead of the order they are registered in. I can pretty much promise you however that if you only use a logfile for the application errors you will never look at it except for debugging an issue when a user reported it for you. its class hierarchy is traversed. and a handler is registered for ConnectionError and ConnectionRefusedError. Often it’s in your webserver’s log files.2.0. Here is how you can configure the Flask logger to send you mails for exceptions: ADMINS = ['yourname@example. Changed in version 0. If your mail server re- quires credentials. Where this ends up is sometimes hard to find. What you probably want instead is a mail the second the exception happened. the more specific ConnectionRefusedError handler is called on the exception instance. and it can actually send you mails for errors which is probably what you want.0. The reason for that is that Flask by default will just report to the WSGI error stream or stderr (depending on what’s available).You are however not limited to HTTPException or HTTP status codes but can register a handler for every exception class you like.ERROR) app.

debug: import logging from themodule import TheHandlerYouWant file_handler = TheHandlerYouWant(. errors are logged to your webserver’s log automatically. A log record stores more information. Warnings however are not. Before you run that in production.WARNING) app.addHandler(file_handler) 8. By default as of Flask 0. just make sure to use a lower setting (I would recommend WARNING): if not app. Because we certainly don’t want to get a mail for warnings or other useless logs that might happen during request handling. If you are deploying on a Windows box. Note that tracebacks are ap- pended to the log entry automatically.) file_handler.logs messages to a file on the filesystem.will log to the system event log of a Windows system. The most interesting are probably the following: • FileHandler .setLevel(logging. where it did.logger.logs messages to a file on the filesystem and will rotate after a certain number of messages. Once you picked your log handler.5 Controlling the Log Format By default a handler will only write the message string into a file or send you that message as mail.. please also look at Controlling the Log Format to put more information into that error mail.4 Logging to a File Even if you get mails. 8. • RotatingFileHandler . do like you did with the SMTP handler above. A formatter can be instantiated with a format string. so it’s your responsibility to warn in the code if something seems odd. and more importantly. • SysLogHandler .We also tell the handler to only send errors and more critical messages.sends logs to a UNIX syslog. Please note that Flask itself will not issue any warnings in the core system. That will save you from a lot of frustration.11. You don’t have to do that in the log formatter format string. There are a couple of handlers provided by the logging system out of the box but not all of them are useful for basic error logging. 60 .. and it makes a lot of sense to configure your logger to also contain that information so that you have a better idea of why that error happened. It’s a good idea to keep as much information around that might be required to debug a problem. • NTEventLogHandler . you probably also want to log warnings. this is what you want to use.

Here are some example setups: 8.2 File logging from logging import Formatter file_handler.setFormatter(Formatter( '%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]' )) 8.3 Complex Log Formatting Here is a list of useful formatting variables for the format string.1 Email from logging import Formatter mail_handler. Note that this list is not complete.5.setFormatter(Formatter(''' Message type: %(levelname)s Location: %(pathname)s:%(lineno)d Module: %(module)s Function: %(funcName)s Time: %(asctime)s Message: %(message)s ''')) 8. consult the official documentation of the logging package for a full list. 61 .5.5.

6 Other Libraries So far we only configured the logger your application created itself. If you want a different time format you can override this method. %(pathname)s Full pathname of the source file where the logging call was issued (if available). Other libraries might log themselves as well. Instead. For more information. For example. you can subclass the formatter. I would recommend figuring out which loggers you are interested in. 'INFO'. 'ERROR'. It is passed a LogRecord object and has to return the formatted string. %(funcName)s Name of function containing the logging call. getLogger('sqlalchemy').addHandler(file_handler) 62 .896" (the num- bers after the comma are millisecond portion of the time). SQLAlchemy uses logging heavily in its core. formatTime(): called for asctime formatting.logger. formatException() called for exception formatting. This can be changed by subclassing the formatter and overriding the formatTime() method. It is passed an exc_info tuple and has to return a string. %(module)s Module (name portion of filename). 'WARNING'. There might be a situation in which you want to have multiple separate applications running side by side in the same Python interpreter and then it becomes impossible to have different logging setups for those. computed as msg % args If you want to further customize the formatting. %(asctime)s Human-readable time when the LogRecord was created. The default is usually fine. getting the loggers with the getLogger() function and iterating over them to attach handlers: from logging import getLogger loggers = [app. %(message)s The logged message. you don’t have to override it. By de- fault this is of the form "2003-07-08 16:49:45. head over to the official documentation. getLogger('otherlibrary')] for logger in loggers: logger. 'CRITICAL'). Format Description %(levelname)s Text logging level for the message ('DEBUG'. %(lineno)d Source line number where the logging call was issued (if avail- able). %(filename)s Filename portion of pathname.addHandler(mail_handler) logger. The formatter has three interesting methods: format(): handles the actual formatting. 8. While there is a method to configure all loggers at once in the logging package. I would not recommend using it.

2 Working with Debuggers To dig deeper. of course): 63 . This section provides pointers when debugging deployment configuration and digging deeper with a full-featured Python debugger. You can use Flask’s builtin development server with debug=True on your production host. If you would like to use another Python debugger.. which is helpful in catching configuration issues. 9. note that debuggers interfere with each other.yaml (change the block as appropriate for your application.whether to reload and fork the process on exception debug must be True (i. Flask provides a debugger out of the box (see Debug Mode). 9. exceptions must be caught) in order for the other two options to have any value. verify that you can run your application manually from the shell in the deployment environment. Be sure to run under the same user account as the configured deployment to troubleshoot permission issues.whether to enable debug mode and catch exceptions • use_debugger . configure your application with logging and notifications as described in Application Errors.1 When in Doubt. If you’re using Aptana/Eclipse for debugging you’ll need to set both use_debugger and use_reloader to False. Do not run in production with debug=True. You have to set some options in order to use your favorite debugger: • debug . CHAPTER NINE DEBUGGING APPLICATION ERRORS For production applications.whether to use the internal Flask debugger • use_reloader . but be sure to do this temporarily in a controlled environment. A possible useful pattern for configuration is to set the following in your config. possibly to trace code execution. Run Manually Having problems getting your application configured for production? If you have shell access to your host.e.

yaml") if app.py).FLASK: DEBUG: True DEBUG_WITH_APTANA: True Then in your application’s entry-point (main.config. set use_debugger=False app = create_app(config="config. use_reloader=use_debugger.get('DEBUG_WITH_APTANA')) except: pass app. debug=app. you could have something like: if __name__ == "__main__": # To allow aptana to receive errors.debug: use_debugger = True try: # Disable Flask's debugger if external debugger is requested use_debugger = not(app.0.0') 64 .debug.run(use_debugger=use_debugger.0. host='0.

update() method: app.. There are different settings you might want to change depending on the application environment like toggling the debug mode.3. This is the place where Flask itself puts certain configuration values and also where exten- sions can put their configuration values. setting the secret key. CHAPTER TEN CONFIGURATION HANDLING New in version 0.config['DEBUG'] = True Certain configuration values are also forwarded to the Flask object so you can read and write them from there: app. but there are better ways. there is a config object available which holds the loaded configuration values: The config attribute of the Flask object.1 Configuration Basics The config is actually a subclass of a dictionary and can be modified just like any dictionary: app = Flask(__name__) app. You can hardcode the configuration in the code.debug = True To update multiple keys at once you can use the dict. Applications need some kind of configuration. and other such environment-specific things.update( DEBUG=True.. SECRET_KEY='. which for many small applications is not actually that bad. 10. The way Flask is designed usually requires the configuration to be available when the application starts up. But this is also where you can have your own configuration.' ) 65 .config. Independent of how you load your config.

10.2 Builtin Configuration Values The following configuration values are used internally by Flask: 66 .

If this is not set. If this is not set the cookie will be valid for all of APPLICATION_ROOT or if that is not set for '/'.8 this can also be an integer represent- ing seconds. SESSION_COOKIE_SECURE controls if the cookie should be set with the secure flag. APPLICATION_ROOT If the application does not occupy a whole do- . 'debug' will only activate logging in debug mode. This can be disabled by this key. SECRET_KEY the secret key SESSION_COOKIE_NAME the name of the session cookie SESSION_COOKIE_DOMAIN the domain for the session cookie. The default is 'always' which means that the default logging handler is always active. If set to True (which is the de- fault) then the cookie is refreshed each request which automatically bumps the lifetime. dev:5000') Note that localhost does not sup- port subdomains so setting this to “localhost” does not help. PERMANENT_SESSION_LIFETIME the lifetime of a permanent session as datetime. Setting a SERVER_NAME also by67 default enables URL generation without a re- quest context but with an application context. SESSION_COOKIE_HTTPONLY controls if the cookie should be set with the httponly flag. If set to False a set-cookie header is only sent if the session is modified. PRESERVE_CONTEXT_ON_EXCEPTION By default if the application is in debug mode the request context is not popped on excep- tions to enable debuggers to introspect the data. Defaults to True. If not set or explicitly set to None this is implicitly true if either TESTING or DEBUG is true. You can also use this setting to force-enable it for non debug execution which might be useful to debug production applications (but also very risky). SESSION_REFRESH_EACH_REQUEST this flag controls how permanent sessions are refreshed. 'production' will only log in produc- tion and 'never' disables it entirely.g. Re- quired for subdomain support (e. Non permanent sessions are not affected by this. SERVER_NAME the name and port number of the server.timedelta object. Defaults to False.DEBUG enable/disable debug mode TESTING enable/disable testing mode PROPAGATE_EXCEPTIONS explicitly enable or disable the propagation of exceptions. Starting with Flask 0. the cookie will be valid for all subdomains of SERVER_NAME. USE_X_SENDFILE enable/disable x-sendfile LOGGER_NAME the name of the logger LOGGER_HANDLER_POLICY the policy of the default logging handler. SESSION_COOKIE_PATH the path for the session cookie.: 'myapp.

config. SESSION_COOKIE_DOMAIN.9: PREFERRED_URL_SCHEME New in version 0. TEMPLATES_AUTO_RELOAD. SESSION_COOKIE_HTTPONLY. APPLICATION_ROOT.5: SERVER_NAME New in version 0.11: SESSION_REFRESH_EACH_REQUEST. Most modern web browsers will not allow cross-subdomain cookies to be set on a server name without dots in it. ideally located outside the actual application package. So a common pattern is this: app = Flask(__name__) app.from_object('yourapplication. SESSION_COOKIE_SECURE New in version 0.10: JSON_AS_ASCII. This is also used for the session cookie.6: MAX_CONTENT_LENGTH New in version 0. TRAP_HTTP_EXCEPTIONS. JSONIFY_PRETTYPRINT_REGULAR New in version 0. LOGGER_HANDLER_POLICY. PRESERVE_CONTEXT_ON_EXCEPTION New in version 0.local' and add this name + the subdomains you want to use into your host config or setup a local bind. JSON_SORT_KEYS. New in version 0. This environment variable can be set on Linux or OS X with the export command in the shell before starting the server: 68 . your web browser does as well.More on SERVER_NAME The SERVER_NAME key is used for the subdomain support. SESSION_COOKIE_PATH. Because Flask cannot guess the subdomain part without the knowledge of the actual server name. this is required if you want to work with subdomains.4: LOGGER_NAME New in version 0.config.default_settings module and then overrides the values with the contents of the file the YOURAPPLICATION_SETTINGS environment variable points to.default_settings') app. Please keep in mind that not only Flask has the problem of not knowing what sub- domains are. Please choose a different server name in that case.from_envvar('YOURAPPLICATION_SETTINGS') This first loads the configuration from the yourapplication.7: PROPAGATE_EXCEPTIONS. EXPLAIN_TEMPLATE_LOADING 10.3 Configuring from Files Configuration becomes more useful if you can store it in a separate file. like 'myapplication. So if your server name is 'localhost' you will not be able to set a cookie for 'localhost' and every subdomain of it. This makes packaging and distributing your application possible via various package handling tools (Deploying with Setuptools) and finally modifying the configuration file afterwards.8: TRAP_BAD_REQUEST_ERRORS.

That way you can create multiple instances of your application with different configura- tions attached which makes unittesting a lot easier.w\xee\x8d$0\x13\x8b83' Make sure to load the configuration very early on. Create your application in a function and register blueprints on it. If you limit your- self to request-only accesses to the configuration you can reconfigure the object later on as needed..py * Running on http://127. You can use this to pass in configuration as needed. There should be at least separate configurations for the production server and the one used during development.1:5000/ * Restarting with reloader.cfg $ python run-app. So make sure to use uppercase letters for your config keys. For a complete reference. so that extensions have the ability to access the configuration when starting up. but there are a couple of things you can keep in mind to improve that experience: 1.\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab. 10.0.$ export YOURAPPLICATION_SETTINGS=/path/to/settings.5 Development / Production Most applications need more than one configuration. The easiest way to handle this is to use a default configuration that is always loaded and part of the version control. On Windows systems use the set builtin instead: >set YOURAPPLICATION_SETTINGS=\path\to\settings..cfg The configuration files themselves are actual Python files. Here is an example of a configuration file: # Example configuration DEBUG = False SECRET_KEY = '?\xbf.4 Configuration Best Practices The downside with the approach mentioned earlier is that it makes testing a little harder. Only values in uppercase are actually stored in the config object later on. There are other methods on the config object as well to load from individual files.0. 2. and a separate configuration that overrides the values as necessary as mentioned in the example above: 69 . Do not write code that needs the configuration at import time. read the Config object’s documentation. There is no single 100% solution for this problem in general. 10.

ProductionConfig') There are many different ways and it’s up to you how you want to manage your con- figuration files. You could also inspect an environment vari- able like YOURAPPLICATION_MODE and set that to production. 70 . However here a list of good recommendations: • Keep a default configuration in version control. Either populate the config with this default configuration or import it in your own configuration files before overriding values.default_settings import * to the top of the file and then overriding the changes by hand. • Use an environment variable to switch between the configurations. For some details about how to do that. If you are working often on dif- ferent projects you can even create your own script for sourcing that activates a virtualenv and exports the development configuration for you. • Use a tool like fabric in production to push code and configurations separately to the production server(s).config. However there are alternative ways as well.py file and export YOURAPPLICATION_SETTINGS=/path/to/config.app = Flask(__name__) app. For example you could use imports or subclassing.from_object('configmodule. head over to the Deploying with Fabric pattern. An interesting pattern is also to use classes and inheritance for configuration: class Config(object): DEBUG = False TESTING = False DATABASE_URI = 'sqlite://:memory:' class ProductionConfig(Config): DATABASE_URI = 'mysql://user@localhost/foo' class DevelopmentConfig(Config): DEBUG = True class TestingConfig(Config): TESTING = True To enable such a config you just have to call into from_object(): app. development etc and import different hardcoded files based on that. What is very popular in the Django world is to make the import explicit in the config file by adding from yourapplication.config.config.py and you are done. This can be done from outside the Python interpreter and makes development and deploy- ment much easier because you can quickly and easily switch between different configs without having to touch the code at all.default_settings') app.from_object('yourapplication.from_envvar('YOURAPPLICATION_SETTINGS') Then you just have to add a separate config.

Unfortu- nately however this only works well if applications are not packages in which case the root path refers to the contents of the package. This can be /usr or the path to your virtualenv.py /instance • Uninstalled package: /myapp /__init__. Flask 0.root_path). This was also how many developers loaded configurations stored next to the application. You can either explicitly provide the path of the instance folder when creating the Flask application or you can let Flask autodetect the instance folder. For explicit con- figuration use the instance_path parameter: app = Flask(__name__.8 a new attribute was introduced: Flask. If the instance_path parameter is not provided the following default locations are used: • Uninstalled module: /myapp.prefix to see what the prefix is set to.10. Since the config object provided loading of configuration files from relative filenames we made it possible to change the loading via filenames to be relative to the instance path if wanted.instance_path. instance_path='/path/to/instance/folder') Please keep in mind that this path must be absolute when provided.6 Instance Folders New in version 0. The instance folder is designed to not be under version control and be deployment specific.X/site-packages/myapp $PREFIX/var/myapp-instance $PREFIX is the prefix of your Python installation.8. Flask for a long time made it possible to refer to paths relative to the application’s folder directly (via Flask. It refers to a new concept called the “instance folder”.py /instance • Installed module or package: $PREFIX/lib/python2. It’s the perfect place to drop things that either change at runtime or configuration files. You can print the value of sys. With Flask 0.8 introduces instance folders. The behavior of relative paths in config files can be flipped between “relative to the application root” (the default) to “relative to instance folder” via the instance_relative_config switch to the application constructor: 71 .

Example usage for both: filename = os.open_instance_resource('application. instance_relative_config=True) Here is a full example of how to configure Flask to preload the config from a module and then override the config from a file in the config folder if it exists: app = Flask(__name__.instance_path.from_object('yourapplication.from_pyfile('application.default_settings') app.path.cfg') as f: config = f.read() # or via open_instance_resource: with app.instance_path.config. 'application. instance_relative_config=True) app.cfg') with open(filename) as f: config = f. Flask also provides a shortcut to open a file from the instance folder with Flask.config.cfg'.read() 72 .app = Flask(__name__. silent=True) The path to the instance folder can be found via the Flask. open_instance_resource().join(app.

These temporary subscriptions are helpful for unittesting for example. In short. This is especially true if you are developing an extension. The first ar- gument is the function that should be called when the signal is emitted.6.1 Subscribing to Signals To subscribe to a signal. you can use the connect() method of a signal. Flask comes with a couple of signals and other extensions might provide more. 11. The big advantage of signals over handlers is that you can safely subscribe to them for just a split second. You will notice that there are signals that appear to do the same thing like some of the builtin decorators do (eg: request_started is very similar to before_request()). The core before_request() handler. Also keep in mind that signals are intended to notify subscribers and should not encourage subscribers to modify data. When you subscribe to a signal. you can use the disconnect() method. the sender is the application that issued the signal. In contrast all signal handlers are executed in undefined order and do not modify any data. Starting with Flask 0. To unsubscribe from a signal. the optional second argument specifies a sender. However. is executed in a specific order and is able to abort the request early by returning a response.6. 73 . CHAPTER ELEVEN SIGNALS New in version 0. For all core Flask signals. Say you want to know what templates were rendered as part of a request: signals allow you to do exactly that. there are differences in how they work. What are signals? Signals help you decouple applications by sending notifications when actions occur elsewhere in the core framework or another Flask extensions. there is integrated support for signalling in Flask. be sure to also provide a sender unless you really want to listen for signals from all applications. for example. This support is provided by the excellent blinker library and will gracefully fall back if it is not available. signals allow certain senders to notify subscribers that something happened.

templates.. Whenever a template is rendered. context = templates[0] 74 .connect(record.connected_to(record. the template object as well as context are appended to it. app) try: yield recorded finally: template_rendered.. **extra): def record(sender. Because the return value of the context manager cannot be specified that way. context)) template_rendered.get('/') assert rv.name == 'index. here is a helper context manager that can be used in a unittest to deter- mine which templates were rendered and what variables were passed to the template: from flask import template_rendered from contextlib import contextmanager @contextmanager def captured_templates(app): recorded = [] def record(sender.test_client(). you have to pass the list in as an argument: from flask import template_rendered def captured_templates(app. app) The example above would then look like this: templates = [] with captured_templates(app. template. All the template rendering in the code issued by the application app in the body of the with block will now be recorded in the templates variable.disconnect(record. Additionally there is a convenient helper method (connected_to()) that allows you to temporarily subscribe a function to a signal with a context manager on its own.append((template. context)) return template_rendered. **extra): recorded.For example. app) This can now easily be paired with a test client: with captured_templates(app) as templates: rv = app.append((template. context.status_code == 200 assert len(templates) == 1 template.html' assert len(context['items']) == 10 Make sure to subscribe with an extra **extra argument so that your calls don’t fail if Flask introduces new arguments to the signals. context = templates[0] assert template. **extra): . recorded. context): recorded. template. template.

This is what is recommended most of the time: from blinker import Namespace my_signals = Namespace() Now you can create new signals like this: model_saved = my_signals. The most common use case are named signals in a custom Namespace.signals. If you have a class that is emitting a signal. It accepts a sender as first argument and optionally some keyword arguments that are forwarded to the signal subscribers: class Model(object): .. you can do so by using the flask._get_current_object() as sender. you can pass current_app. pass self as sender. you can use the blinker library directly.. You can access the name of the signal with the name attribute. def save(self): model_saved.signal('model-saved') The name for the signal here makes it unique and also simplifies debugging.Namespace class.Blinker API Changes The connected_to() method arrived in Blinker with version 1. Passing Proxies as Senders 75 . you can do so by calling the send() method.. For Extension Developers If you are writing a Flask extension and you want to gracefully degrade for missing blinker installations. 11.1.2 Creating Signals If you want to use signals in your own application. 11.3 Sending Signals If you want to emit a signal. If you are emitting a signal from a random function.send(self) Try to always pick a good sender.

6 Core Signals Take a look at Signals for a list of all builtin signals.connect_via(app) def when_template_rendered(sender.name. template. **extra): print 'Template %s is rendered with %s' % (template. _get_current_object() instead. 11. 11.Never pass current_app as sender to a signal.1 you can also easily subscribe to signals by using the new connect_via() decorator: from flask import template_rendered @template_rendered.g and others as needed. context. Context-local vari- ables are consistently available between request_started and request_finished. The reason for this is that current_app is a proxy and not the real application object.5 Decorator Based Signal Subscriptions With Blinker 1. Note the limitations described in Send- ing Signals and the request_tearing_down signal. context) 11. 76 .4 Signals and Flask’s Request Context Signals fully support The Request Context when receiving signals. Use current_app. so you can rely on flask.

html'.query. 12. but if you want to provide this view in a generic fashion that can be adapted to other models and templates as well you might want more flex- ibility. The string you pass to that function is the name of the endpoint that view will then have.route('/users/') def show_users(page): users = User. so let’s refactor the code a bit: 77 .7 introduces pluggable views inspired by the generic views from Django which are based on classes instead of functions. users=users) This is simple and flexible. Flask 0.all() return render_template('users. view_func=ShowUsers.7. Then we have to convert that class into an actual view function by using the as_view() class method.View and im- plement dispatch_request(). As the first step to convert this into a class based view you would do this: from flask.views import View class ShowUsers(View): def dispatch_request(self): users = User.add_url_rule('/users/'.views. The main intention is that you can replace parts of the implementations and this way have customizable pluggable views. This is where pluggable class-based views come into place.query. CHAPTER TWELVE PLUGGABLE VIEWS New in version 0.as_view('show_users')) As you can see what you have to do is to create a subclass of flask.1 Basic Principle Consider you have a function that loads a list of objects from the database and renders into a template: @app. But this by itself is not helpful.html'. objects=users) app.all() return render_template('users.

The way this works is that whenever the request is dispatched a new instance of the class is created and the dispatch_request() method is called with the parameters from the URL rule.as_view( 'about_page'.all() This of course is not that helpful for such a small example.template_name) And then you can register it like this: app. **context) def dispatch_request(self): context = {'objects': self. template_name='about. When you have a class-based view the question comes up what self points to.get_objects()} return self.views import View class ListView(View): def get_template_name(self): raise NotImplementedError() def render_template(self.render_template(context) class UserView(ListView): def get_template_name(self): return 'users.from flask.get_template_name(). In order to move that information to the class you can provide a methods attribute that has this information: 78 . context): return render_template(self.add_url_rule('/about'.html' def get_objects(self): return User.html')) 12. template_name): self. view_func=RenderTemplateView.2 Method Hints Pluggable views are attached to the application like a regular function by either using route() or better add_url_rule(). For instance you can write a class like this: class RenderTemplateView(View): def __init__(self.query.template_name = template_name def dispatch_request(self): return render_template(self. That however also means that you would have to provide the names of the HTTP methods the view supports when you attach this. The class itself is instantiated with the parameters passed to the as_view() function. but it’s good enough to explain the basic principle.

query. app. Instead you either have to decorate the return value of as_view() by hand: def user_required(f): """Checks whether user is logged in or raises error 401. app.as_view('users')) That way you also don’t have to provide the methods attribute.4 Decorating Views Since the view class itself is not the view function that is added to the routing system it does not make much sense to decorate the class itself..form) .from_form_data(request. It’s automatically set based on the methods defined in the class. Each HTTP method maps to a function with the same name (just in lowercase): from flask.class MyView(View): methods = ['GET'.as_view('myview')) 12.method == 'POST': .views import MethodView class UserAPI(MethodView): def get(self): users = User.user: abort(401) return f(*args.MethodView you can easily do that...all() .add_url_rule('/myview'. view_func=MyView. 12.. **kwargs) return decorator 79 ..3 Method Based Dispatching For RESTful APIs it’s especially helpful to execute a different function for each HTTP method. def post(self): user = User. **kwargs): if not g. With the flask..""" def decorator(*args.add_url_rule('/users/'.. 'POST'] def dispatch_request(self): if request. view_func=UserAPI. .views..

keep this in mind. That said. For instance consider that you are exposing a user object on the web: URL Method Description /users/ GET Gives a list of all users /users/ POST Creates a new user /users/<id> GET Shows a single user /users/<id> PUT Updates a single user /users/<id> DELETE Deletes a single user So how would you go about doing that with the MethodView? The trick is to take advantage of the fact that you can provide multiple rules to the same view. you will notice that the API will require different URL rules that go to the same method view most of the time.5 Method Views for APIs Web APIs are often working very closely with HTTP verbs so it makes a lot of sense to implement such an API based on the MethodView.8 there is also an alternative way where you can specify a list of decorators to apply in the class declaration: class UserAPI(MethodView): decorators = [user_required] Due to the implicit self from the caller’s perspective you cannot use regular view dec- orators on the individual methods of the view however. Let’s assume for the moment the view would look like this: class UserAPI(MethodView): def get(self. user_id): # delete a single user pass 80 .view = user_required(UserAPI.as_view('users')) app.add_url_rule('/users/'. user_id): if user_id is None: # return a list of users pass else: # expose a single user pass def post(self): # create a new user pass def delete(self. 12. view_func=view) Starting with Flask 0.

pk_type.add_url_rule(url. view_func=view_func. user_id): # update a single user pass So how do we hook this up with the routing system? By adding two rules and explic- itly mentioning the methods for each: user_view = UserAPI. view_func=view_func. methods=['POST'. methods=['GET'. 'PUT'.as_view(endpoint) app. 'user_api'.as_view('user_api') app. methods=['GET'. pk_type='int'): view_func = view. url. view_func=view_func. defaults={pk: None}.add_url_rule('/users/'. '/users/'. methods=['GET'. 'DELETE']) If you have a lot of APIs that look similar you can refactor that registration code: def register_api(view. view_func=user_view. methods=['POST'. methods=['GET'. 'DELETE']) register_api(UserAPI. pk='id'.]) app.add_url_rule('/users/'. defaults={'user_id': None}.]) app. pk). endpoint. view_func=user_view. def put(self. view_func=user_view.]) app.add_url_rule('/users/<int:user_id>'. pk='user_id') 81 .]) app.add_url_rule(url. 'PUT'.add_url_rule('%s<%s:%s>' % (url.

82 .

• no request handling happened so far • you have to have a reference to the application object in order to modify it. that you’re sitting in an interactive Python shell and interacting with the application. just that there is no request active.request and others) point to the current request.9. or a command line application. • any code can get hold of these objects at any time. It starts when the Flask object is instantiated. 13. One of the design ideas behind Flask is that there are two different “states” in which code is executed. Since one of the pillars of Flask’s design is that you can have more than one application in the same Python process. Consider. There is a third state which is sitting in between a little bit. While the application is in this state a few assumptions are true: • the programmer can modify the application object safely. 83 . CHAPTER THIRTEEN THE APPLICATION CONTEXT New in version 0. a couple of other rules exist: • while a request is active. The application setup state in which the application implicitly is on the module level. during request handling. The application context is what powers the current_app context local. In contrast. for instance.1 Purpose of the Application Context The main reason for the application’s context existence is that in the past a bunch of functionality was attached to the request context for lack of a better solution. there is no magic proxy that can give you a reference to the application object you’re currently creating or modifying. the context local objects (flask. Sometimes you are dealing with an application in a way that is similar to how you interact with applications during request handling. and it implicitly ends when the first request comes in.

which was bound to the current request’s application reference._app_ctx_stack. Since creating such a request context is an unnecessarily expensive operation in case there is no request around. A common workaround for that problem was to use the current_app proxy later on. As a result. the application context was introduced. As such it is the perfect place to store database connection information and other things. you can ignore the existence of the application context unless you need it. instead of on the flask. If no request context has been pushed and an application context has not been explic- itly set. current_app points to app.2 Creating an Application Context There are two ways to make an application context. The first one is implicit: whenever a request context is pushed. The second way is the explicit way using the app_context() method: from flask import Flask.name The application context is also used by the url_for() function in case a SERVER_NAME was configured. see Flask Extension Development. It never moves between threads and it will not be shared between requests.So how does the code find the “right” application? In the past we recommended pass- ing applications around explicitly. For more information about that. current_app app = Flask(__name__) with app. 13. but that caused issues with libraries that were not designed with that in mind. This allows you to generate URLs even in the absence of a request. print current_app. Extensions are free to store additional information on the topmost level. an application context will be created alongside if this is necessary. 84 .3 Locality of the Context The application context is created and destroyed as necessary. RuntimeError: Working outside of application context. a RuntimeError will be raised. assuming they pick a sufficiently unique name and should put their information there. The internal stack object is called flask. 13.g object which is reserved for user code.app_context(): # within this block.

The most common usage is to split resource management into two parts: 1. None) if db is not None: db. 85 . When storing things on the application context unique names should be chosen as this is a place that is shared between Flask applications and extensions. an implicit resource caching on the context.13. This is an example that connects to a database: import sqlite3 from flask import g def get_db(): db = getattr(g._database = connect_to_database() return db @app. 2.close() The first time get_db() is called the connection will be established. and a teardown_X() function that is registered as teardown handler.local import LocalProxy db = LocalProxy(get_db) That way a user can directly access db which internally calls get_db(). None) if db is None: db = g. a context teardown based resource deallocation. '_database'.4 Context Usage The context is typically used to cache resources that need to be created on a per-request or usage case. For instance. '_database'. database connections are destined to go there. To make this im- plicit a LocalProxy can be used: from werkzeug.teardown_appcontext def teardown_db(exception): db = getattr(g. Generally there would be a get_X() function that creates resource X if it does not ex- ist yet and otherwise returns the same resource.

86 .

com/') This context can be used in two ways. line 1.args.1 Diving into Context Locals Say you have a utility function that returns the URL the user should be redirected to. Imagine it would always redirect to the URL’s next parameter or the HTTP referrer or the index page: from flask import request. 14. in <module> AttributeError: 'NoneType' object has no attribute 'request' That makes a lot of sense because we currently do not have a request we could access.get('next') or \ request. So we have to make a request and bind it to the current context.7 which is mostly in line with the old behavior but has some small.referrer or \ url_for('index') As you can see. Either with the with statement or by calling the push() and pop() methods: 87 .test_request_context('/?next=http://example. If you try to run this from a plain Python shell. url_for def redirect_url(): return request. CHAPTER FOURTEEN THE REQUEST CONTEXT This document describes the behavior in Flask 0. The test_request_context method can create us a RequestContext: >>> ctx = app. subtle differences. it accesses the request object. this is the exception you will see: >>> redirect_url() Traceback (most recent call last): File "<stdin>". It is recommended that you read the The Application Context chapter first.

The request context internally works like a stack: The topmost level on the stack is the current active request. For more information of how to utilize the request context from the interactive Python shell.pop() Because the request context is internally maintained as a stack you can push and pop multiple times. 14. head over to the Working with the Shell chapter. environ): with self.push() From that point onwards you can work with the request object: >>> redirect_url() u'http://example. Another thing of note is that the request context will automatically also create an appli- cation context when it’s pushed and there is no application context for that application so far. push() adds the context to the stack on the very top.full_dispatch_request() except Exception as e: response = self.com/' Until you call pop: >>> ctx. Everything that is called from the same thread from this point onwards until the end of the with statement will have access to the request globals (flask.>>> ctx.make_response(self. This is very handy to implement things like internal redirects.request and others).2 How the Context Works If you look into how the Flask WSGI application internally works. you will find a piece of code that looks very much like this: def wsgi_app(self.request_context(environ): try: response = self. On popping the application’s teardown_request() functions are also executed. pop() removes it from the stack again. start_response) The method request_context() returns a new RequestContext object and uses it in combination with the with statement to bind the context.handle_exception(e)) return response(environ. 88 .

2. the teardown_request() functions are called.7 because we wanted to make it easier to understand what is actually happening. Before each request. Strictly speaking they are independent of the actual request handling as they are bound to the lifecycle of the RequestContext object. This is important to know if the life of the request context is prolonged by using the test client in a with statement or when using the request context from the command line: with app. The new behavior is quite simple: 1. In any case however the return value is treated as a replacement for the view’s return value.7 is that the internal server error is now no longer post processed by the after request callbacks and after request callbacks are no longer guar- anteed to be executed.get('/foo') # the teardown functions are still not called at that point 89 . 4. Now what happens on errors? In production mode if an exception is not caught. The return value of the view is then converted into an actual response object and handed over to the after_request() functions which have the chance to replace it or modify it in place.3 Callbacks and Errors What happens if an error occurs in Flask during request processing? This particular behavior changed in 0. If one of these functions return a response.4 Teardown Callbacks The teardown callbacks are special callbacks in that they are executed at a different point. That way things like the interactive debugger can provide helpful debug information. This always happens. At the end of the request the teardown_request() functions are executed. An important change in 0. This way the internal dispatching code looks cleaner and is easier to customize and understand. 14.test_client() as client: resp = client. 3. the regular request handling kicks in and the view function that was matched has the chance to return a response. even in case of an unhandled exception down the road or if a before-request handler was not executed yet or at all (for example in test envi- ronments sometimes you might want to not execute before-request callbacks). the other functions are no longer called.14. before_request() functions are executed. The new teardown functions are supposed to be used as a replacement for things that absolutely need to happen at the end of request. the 500 internal server handler is called. When the request context is popped. If the before_request() functions did not return a response. In development mode however the exception is not further processed and bubbles up to the WSGI server.

>>> ctx = app.5 Notes On Proxies Some of the objects provided by Flask are proxies to other objects.pop() this runs after request >>> Keep in mind that teardown callbacks are always executed. # even though the response ended and you have the response # object in your hand # only when the code reaches this point the teardown functions # are called. Certain parts of the test sys- tem might also temporarily create a request context without calling the before-request handlers. so if you want to perform actual instance checks. you have to do that on the instance that is being proxied (see _get_current_object below).. you can use the _get_current_object() method: app = current_app.test_request_context() >>> ctx. even if before-request call- backs were not executed yet but an exception happened. print 'this runs after request' ..push() >>> ctx. The reason behind this is that these proxies are shared between threads and they have to dispatch to the actual object bound to a thread behind the scenes as necessary. 14. Make sure to write your teardown-request handlers in a way that they will never fail.teardown_request ... Most of the time you don’t have to care about that.send(app) 90 . def teardown_request(exception=None): . • if the object reference is important (so for example for sending Signals) If you need to get access to the underlying object that is proxied. Alternatively the same thing happens if another # request was triggered from the test client It’s easy to see the behavior from the command line: >>> app = Flask(__name__) >>> @app..._get_current_object() my_signal. but there are some exceptions where it is good to know that this object is an actual proxy: • The proxy objects do not fake their inherited types.

By default it’s linked to the setting of DEBUG.6 and earlier in debug mode. in pro- duction mode it’s not.7 you have finer control over that behavior by setting the PRESERVE_CONTEXT_ON_EXCEPTION configuration variable. at the end of the request the request context is popped and all data associated with it is destroyed.14. if an exception occurred. In Flask 0. 91 . During development however that can be problematic as you might want to have the information around for a longer time in case an exception occurred.6 Context Preservation on Error If an error occurs or not. the request context was not popped so that the interactive debugger can still provide you with important information. However it can be useful during development to get the same error preserving behavior as in development mode when attempting to debug an error that only occurs under production settings. Starting with Flask 0. If the application is in debug mode the context is preserved. Do not force activate PRESERVE_CONTEXT_ON_EXCEPTION in production mode as it will cause your application to leak memory on exceptions.

92 .

Flask uses a concept of blueprints for making application components and supporting common patterns within an application or across applications. static files.1 Why Blueprints? Blueprints in Flask are intended for these cases: • Factor an application into a set of blueprints. A blueprint does not have to implement applications or view func- tions. 93 . Blueprints can greatly simplify how large applications work and provide a central means for Flask extensions to register operations on applications.7. Pa- rameters in the URL prefix/subdomain become common view arguments (with defaults) across all view functions in the blueprint. 15. A blueprint in Flask is not a pluggable app because it is not actually an application – it’s a set of operations which can be registered on an application. and register a collection of blueprints. This is ideal for larger applications. initialize several extensions. A Blueprint object works similarly to a Flask application object. but your applications will have separate configs and will be managed at the WSGI layer. and other utilities through blueprints. • Register a blueprint multiple times on an application with different URL rules. CHAPTER FIFTEEN MODULAR APPLICATIONS WITH BLUEPRINTS New in version 0. templates. a project could instantiate an application object. • Provide template filters. Why not have multiple application objects? You can do that (see Application Dispatching). • Register a blueprint on an application at a URL prefix and/or subdomain. but it is not actually an application. even multiple times. • Register a blueprint on an application for any of these cases when initializing a Flask extension. Rather it is a blueprint of how to construct or extend an application.

register_blueprint(simple_page) 94 . render_template.simple_page import simple_page app = Flask(__name__) app.2 The Concept of Blueprints The basic concept of blueprints is that they record operations to execute when reg- istered on an application. and can change an application object as necessary with being registered. template_folder='templates') @simple_page. defaults={'page': 'index'}) @simple_page.4 Registering Blueprints So how do you register that blueprint? Like this: from flask import Flask from yourapplication. The downside is that you cannot unregister a blueprint once an application was created without having to destroy the whole application object.3 My First Blueprint This is what a very basic blueprint looks like. __name__. 15.html' % page) except TemplateNotFound: abort(404) When you bind a function with the help of the @simple_page.Blueprints instead provide separation at the Flask level. share application config. 15. Additionally it will prefix the endpoint of the function with the name of the blueprint which was given to the Blueprint constructor (in this case also simple_page). Flask associates view functions with blueprints when dis- patching requests and generating URLs from one endpoint to another. abort from jinja2 import TemplateNotFound simple_page = Blueprint('simple_page'. 15.route decorator the blueprint will record the intention of registering the function show on the application when it’s later registered.route('/<page>') def show(page): try: return render_template('pages/%s.route('/'. In this case we want to implement a blueprint that does simple rendering of static templates: from flask import Blueprint.

OPTIONS. The folder is inferred from the second argument to Blueprint which is usually __name__. If it points to an actual Python package that package (which is a folder on the filesystem) is the resource folder. GET) -> simple_page. As you can see. Sometimes you might want to introduce a blueprint only for the resources it provides. Blueprints however can also be mounted at different locations: app. <Rule '/pages/' (HEAD.register_blueprint(simple_page. <Rule '/' (HEAD. <Rule '/<page>' (HEAD. GET) -> simple_page. OPTIONS. GET) -> static>. GET) -> static>. You can access the Blueprint. This argument specifies what logical Python module or package corre- sponds to the blueprint.1 Blueprint Resource Folder Like for regular applications. OPTIONS. GET) -> simple_page. blueprints are considered to be contained in a folder. OPTIONS. url_prefix='/pages') And sure enough.show>] On top of that you can register blueprints multiple times though not every blueprint might respond properly to that.).5 Blueprint Resources Blueprints can provide resources as well. it does not have to be the case and it’s usually not recommended. OPTIONS.show>] The first one is obviously from the application itself for the static files. these are the generated rules: [<Rule '/static/<filename>' (HEAD.root_path '/Users/username/TestProject/yourapplication' To quickly open sources from this folder you can use the open_resource() function: 95 . The other two are for the show function of the simple_page blueprint. In fact it depends on how the blueprint is imple- mented if it can be mounted more than once.5. the package the mod- ule is contained in will be the resource folder. they are also prefixed with the name of the blueprint and separated by a dot (. <Rule '/pages/<page>' (HEAD.If you check the rules registered on the application. 15. OPTIONS.show>.show>. While multiple blueprints can originate from the same folder. If it’s a module. GET) -> simple_page. you will find these: [<Rule '/static/<filename>' (HEAD.root_path property to see what the resource folder is: >>> simple_page. 15.

the path can be absolute or relative to the blueprint resource folder.html in the actual application template folder. static_folder='static') By default the rightmost part of the path is where it is exposed on the web.html' and you have provided templates as a tem- plate_folder you will have to create a file like this: yourapplication/admin/templates/ admin/index. That way you can easily override templates that a blueprint provides in the actual application.html which is specific to this blueprint.static'.open_resource('static/style.2 Static Files A blueprint can expose a folder with static files by providing a path to a folder on the filesystem via the static_folder keyword argument.css') 15.5. The endpoint is named blueprint_name. Because the folder is called static here it will be available at the location of the blueprint + /static.with simple_page. template_folder='templates') For static files. So if you have a blueprint in the folder yourapplication/admin and you want to ren- der the template 'admin/index. filename='style. The reason for the extra admin folder is to avoid getting our tem- plate overridden by a template named index.3 Templates If you want the blueprint to expose templates you can do that by providing the tem- plate_folder parameter to the Blueprint constructor: admin = Blueprint('admin'.static so you can generate URLs to it like you would do to the static folder of the application: url_for('admin. When mul- tiple blueprints provide the same relative template path the first blueprint registered takes precedence over the others. To further reiterate this: if you have a blueprint named admin and you want to render a template called index. make sure that no other blueprint or actual application template has the same relative path. It can either be an absolute path or one relative to the folder of the blueprint: admin = Blueprint('admin'. This also means that if you don’t want a blueprint template to be accidentally overridden.css') as f: code = f. the best idea is to lay out your templates like this: 96 . __name__. The template folder is added to the search path of templates but with a lower prior- ity than the actual application’s template folder.5. __name__.html. Say the blueprint is registered for /admin the static folder will be at /admin/ static.read() 15.

html as the name to look up the template by. you can use relative redi- rects by prefixing the endpoint with a dot only: url_for('.): url_for('admin.index') This will link to admin. Here is an example for a “404 Page Not Found” exception: @simple_page.7 Error Handlers Blueprints support the errorhandler decorator just like the Flask application object.html') More information on error handling see Custom Error Pages. so it is easy to make Blueprint-specific custom error pages. 15.index for instance in case the current request was dispatched to any other admin blueprint endpoint. 15.yourpackage/ blueprints/ admin/ templates/ admin/ index.6 Building URLs If you want to link from one page to another you can use the url_for() function just like you normally would do just that you prefix the URL endpoint with the name of the blueprint and a dot (.index') Additionally if you are in a view function of a blueprint or a rendered template and you want to link to another endpoint of the same blueprint. If you encounter problems loading the correct templates enable the EXPLAIN_TEMPLATE_LOADING config variable which will instruct Flask to print out the steps it goes through to locate templates on every render_template call.html __init__. 97 .py And then when you want to render the template. use admin/index.errorhandler(404) def page_not_found(e): return render_template('pages/404.

98 .

txt or setup.3 Building Extensions While Flask Extension Registry contains many Flask extensions. you can always create your own.4 Flask Before 0. There are no general rules in how extensions are supposed to behave but they are imported from common locations. instead you have to import from flaskext. 16.1 Finding Extensions Flask extensions are listed on the Flask Extension Registry and can be downloaded with easy_install or pip.foo or flask_foo depending on how the extension is 99 . 16.8 If you are using Flask 0. If you have an extension called Flask-Foo or Foo-Flask it should be always importable from flask_foo: import flask_foo 16. For in- stance they add support for databases and other common tasks. CHAPTER SIXTEEN FLASK EXTENSIONS Flask extensions extend the functionality of Flask in various different ways. Consider reading Flask Extension Development to develop your own Flask extension. you may not find an extension that fits your need. 16.ext package will not exist. If this is the case.7 or earlier the flask.py file they are usually installed with a simple command or when your application installs.2 Using Extensions Extensions typically have documentation that goes along that shows how to use it. If you add a Flask extension as dependency to your requirements.

100 .py And here is how you can use it: import flaskext_compat flaskext_compat.ext import foo Once the flaskext_compat module is activated the flask. We provide you with a compatibility module that provides this package for older versions of Flask.activate() from flask. If you want to develop an application that supports Flask 0.ext package.7 or earlier you should still import from the flask.distributed.ext will exist and you can start importing from there. You can download it from GitHub: flaskext_compat.

This is achieved by exporting the FLASK_APP environment variable. an application needs to be discovered. For the flask script to work.11. It can be either set to an import path or to a filename of a Python module that contains a Flask application. Given a hello. In that imported file the name of the app needs to be called app or optionally be speci- fied after a colon.11 is the built-in integration of the click com- mand line interface. One of the nice new features in Flask 0. Environment variables (On Windows use set instead of export): export FLASK_APP=hello flask run Or with a filename: export FLASK_APP=/path/to/hello.py flask run 101 . Flask extensions can also register more commands there if they desire so. 17. This enables a wide range of new features for the Flask ecosystem and your own applications. CHAPTER SEVENTEEN COMMAND LINE INTERFACE New in version 0. The way this script works is by providing access to all the commands on your Flask application’s Flask.1 Basic Usage After installation of Flask you will now find a flask script installed into your vir- tualenv.cli instance as well as some built-in commands that are always there.py file with the application in it named app this is how it can be run. For instance mymodule:application would tell it to use the application object in the mymodule.py file. If you don’t want to install Flask or you have a special use-case you can also use python -m flask to accomplish exactly the same.

17.echo('Init the db') The command will then show up on the command line: 102 .5 Custom Commands If you want to add more commands to the shell script you can do this easily.""" click.2 Virtualenv Integration If you are constantly working with a virtualenv you can also put the export FLASK_APP into your activate script by adding it to the bottom of the file.command() def initdb(): """Initialize the database.3 Debug Flag The flask script can also be instructed to enable the debug mode of the application automatically by exporting FLASK_DEBUG. For instance if you want a shell command to initialize the database you can do this: import click from flask import Flask app = Flask(__name__) @app. Flask uses click for the command interface which makes creating custom commands very easy. By default you have access to your app and g.cli. If set to 1 debug is enabled or 0 disables it: export FLASK_DEBUG=1 17. This is done by invoking the Flask. 17.4 Running a Shell To run an interactive Python shell you can use the shell command: flask shell This will start up an interactive Python shell. make_shell_context() method of the application. That way every time you activate your virtualenv you automatically also activate the correct application name. 17. setup the correct application context and setup the local variables in the shell.

7 Factory Functions In case you are using factory functions to create your application (see Application Facto- ries) you will discover that the flask command cannot work with them directly.6 Application Context Most commands operate on the application so it makes a lot of sense if they have the application context setup. This is not the only way to make this work. 103 . if you register a callback on app.command(with_appcontext=False) def example(): pass 17. with_appcontext() which informs the cli system to ensure that an application con- text is set up. Because of this. Be- cause of this reason the recommendation is to create a separate file that instantiates applications.cli.py From this point onwards flask will find your application. This behavior is not available if a command is added later with add_command() or through other means.environ['YOURAPPLICATION_CONFIG']) Once this has happened you can make the flask command automatically pick it up: export YOURAPPLICATION_CONFIG=/path/to/config. This could be a file named autoapp. It can also be disabled by passing with_appcontext=False to the decorator: @app.$ flask initdb Init the db 17. Another is the Custom Scripts support.py with these contents: import os from yourapplication import create_app app = create_app(os.cfg export FLASK_APP=/path/to/autoapp. Flask won’t be able to figure out how to instantiate your application properly by itself. cli with the command() the callback will automatically be wrapped through cli. For instance if you have a factory function that creates an application from a filename you could make a separate file that creates such an application from an environment variable.

here is an example manage.8 Custom Scripts While the most common way is to use the flask command.FlaskGroup click group.py script that manages a hypothetical wiki application.py')) @click.get('WIKI_CONFIG'. 2. To explain all of this. 3. We will go through the details afterwards: import os import click from flask. If you use the flask script you specify the application to work with on the command line or environment variable as an import name. that commands registered to Flask. create_app=create_wiki_app) def cli(): """This is a management script for the wiki application. There is one big caveat and that is. With a custom script you don’t have this problem as you can fully customize how the application will be created. Next step is to create a FlaskGroup. This is very useful if you write reusable applications that you want to ship to users and they should be presented with a custom management script.""" if __name__ == '__main__': cli() That’s a lot of code for not much. This is necessary so that the commands know which Flask application they have to work with.17. The next thing we do is defining a function that is invoked with the script info object (ScriptInfo) from Flask and its purpose is to fully import and create the application.group(cls=FlaskGroup. you can also make your own “driver scripts”. Primarily we are here interested in the FlaskGroup click group.environ. This is simple but it has some limitations. so let’s go through all parts step by step. Primarily it does not work with application factory functions (see Application Factories). In this case we just make an empty function with a help doc string that just does nothing and then pass the create_wiki_app 104 . First we import the click library as well as the click extensions from the flask. 1. 'wikiconfig. Since Flask uses click for the scripts there is no reason you cannot hook these scripts into any click application.cli.cli will expect to be (indirectly at least) launched from a flask. In this case we load the config from an environment vari- able.cli import FlaskGroup def create_wiki_app(info): from yourwiki import create_app return create_app( config=os. This can either directly import an application object or create it (see Application Factories). cli package. To understand why you might want custom scripts you need to understand how click finds and executes the Flask application.

) Inside mypackage/commands... However there is a second way to add CLI plugins to Flask which is through setuptools.py you can then export a Click object: import click @click. 105 .""" Once that package is installed in the same virtualenv as Flask itself you can run flask my-command to invoke your command. . Whenever click now needs to operate on a Flask application it will call that func- tion with the script info and ask for it to be created.9 CLI Plugins Flask extensions can always patch the Flask. This is useful to provide extra functionality that Flask itself cannot ship.py file that declares an entrypoint that points to a click command: Example setup. 17. If you make a Python package that should export a Flask command line plugin you can ship a setup.commands] my-command=mypackage.commands:cli '''. entry_points=''' [flask. 4.py: from setuptools import setup setup( name='flask-my-extension'. function as a factory function.command() def cli(): """This is an example command. All is rounded up by invoking the script.cli instance with more commands if they want.

106 .

18. For instance the reloader can be disabled: $ flask run --no-reload 18.2 In Code The alternative way to start the application is through the Flask. The best one is the flask command line utility but you can also continue using the Flask. the reloader and then start the server on http://localhost:5000/. This will immediately launch a local server exactly the same way the flask script does. CHAPTER EIGHTEEN DEVELOPMENT SERVER Starting with Flask 0. Example: if __name__ == '__main__': app. The reason for this 107 . The basic usage is like this: $ export FLASK_APP=my_application $ export FLASK_DEBUG=1 $ flask run This will enable the debugger. The individual features of the server can be controlled by passing more arguments to the run option.run() This works well for the common case but it does not work well for development which is why from Flask 0.run() method.1 Command Line The flask command line script (Command Line Interface) is strongly recommended for development because it provides a superior reload experience due to how it loads the application.run() method.11 onwards the flask method is recommended.11 there are multiple built-in ways to run a development server.

is that due to how the reload mechanism works there are some bizarre side-effects (like executing certain code twice. sometimes crashing without message or dying when a syntax or import error happens). 108 . It is however still a perfectly valid method for invoking a non automatic reloading application.

1 Command Line Interface Starting with Flask 0. For more information see Command Line Interface. For instance the shell is automatically initialized with a loaded application context. 19.test_request_context() 109 . It basically allows you to execute Python commands in real time and immediately get results back. The main issue with interactive console sessions is that you’re not triggering a request like a browser does which means that g. Keep in mind however that these functions are not only there for interactive shell usage. because it does not require any specific setup upfront. Flask itself does not come with an interactive shell.11 the recommended way to work with the shell is the flask shell command which does a lot of this automatically for you. But the code you want to test might depend on them. One of the reasons everybody loves Python is the interactive shell. There are however some handy helpers to make playing around in the shell a more pleasant experience.2 Creating a Request Context The easiest way to create a proper request context from the shell is by using the test_request_context method which creates us a RequestContext: >>> ctx = app. but also for unittesting and other situations that require a faked request context. CHAPTER NINETEEN WORKING WITH THE SHELL New in version 0.3. so what can you do? This is where some helper functions come in handy. 19. request and others are not available. just import your application and start playing around. Generally it’s recommended that you read the The Request Context chapter of the doc- umentation first.

3 Firing Before/After Request By just creating a request context. So this is the perfect place to automatically tear down resources that were needed by the request context (such as database connections). There you could also define some more helper methods for common things such as initializing the database.Normally you would use the with statement to make this request object active. This might result in your database being unavailable if you are connecting to the database in a before-request callback or the current user not being stored on the g object etc.response_class()) <Response 0 bytes [200 OK]> >>> ctx. Just put them into a module (like shelltools) and import from there: >>> from shelltools import * 110 . but in the shell it’s easier to use the push() and pop() methods by hand: >>> ctx. 19.process_response(app. To shutdown a request. in that case just ignore it. This however can easily be done yourself.preprocess_request() Keep in mind that the preprocess_request() function might return a response object.pop() 19. create yourself a module with stuff you want to star import into your interactive session. you still don’t have run the code that is normally run before a request.push() From that point onwards you can work with the request object until you call pop: >>> ctx. Just call preprocess_request(): >>> ctx = app. you need to trick a bit before the after request functions (trig- gered by process_response()) operate on a response object: >>> app.test_request_context() >>> ctx. dropping tables etc.push() >>> app.pop() The functions registered as teardown_request() are automatically called when the context is popped.4 Further Improving the Shell Experience If you like the idea of experimenting in a shell.

There are more user contributed snippets and patterns in the Flask Snippet Archives. In that case. 20. otherwise things would most likely break) You should then end up with something like that: /yourapplication /yourapplication 111 .1 Simple Packages To convert that into a larger one.html login. chances are they will open a database connection at the beginning of the request and get the information of the currently logged in user..py.pyc files first. 20.1. (Make sure to delete all .py to __init__.html . For example quite a lot of applications are using relational databases and user authentication. At the end of the request. That is quite simple. the database connection is closed again. just create a new folder yourapplication inside the existing one and move everything below it. CHAPTER TWENTY PATTERNS FOR FLASK Certain things are common enough that the chances are high you will find them in most web applications.1 Larger Applications For larger applications it’s a good idea to use a package instead of a module..html index.py /static style. Then rename yourapplication. Imagine a small application looks like this: /yourapplication yourapplication.css /templates layout.

Let’s just say that Python does not want modules in pack- ages to be the startup file. all the view functions (the ones with a route() decorator on top) have to be imported in the __init__. But that is not a big problem.py file. __init__.html login. Similiarly you can turn on “debug mode” with this environment variable: export FLASK_DEBUG=true In order to install and run the application you need to issue the following commands: pip install -e . packages=['yourapplication']. 2. Import the view module after the application object is created. Not the object itself. install_requires=[ 'flask'.py file.. flask run What did we gain from this? Now we can restructure the application a bit into multiple modules. include_package_data=True.py next to the inner yourapplication folder with the following contents: from setuptools import setup setup( name='yourapplication'.py /static style. ]. But how do you run your application now? The naive python yourapplication/ __init__. That way each module can import it safely and the __name__ variable will resolve to the correct package. The only thing you have to remember is the following quick checklist: 1. the Flask application object creation has to be in the __init__. but the module it is in. just add a new file called setup.css /templates layout.html index.py will not work..html . 112 . ) In order to run the application you need to export an environment variable that tells Flask where to find the application instance: export FLASK_APP=yourapplication If you are outside of the project directory make sure to provide the exact path to your application directory.

html . Be advised that this is a bad idea in general but here it is actually fine.py: from flask import Flask app = Flask(__name__) import yourapplication.. The reason for this is that we are not actually using the views in __init__. 20.py depends on __init__. For a gentle intro- duction into this topic refer to the Modular Applications with Blueprints chapter of the documentation.html index.route('/') def index(): return 'Hello World!' You should then end up with something like that: /yourapplication setup.html login. Check out the Becoming Big section for some inspiration how to deal with that. 113 .py and just ensuring the module is imported and we are doing that at the bottom of the file.py views.py /yourapplication __init__.views And this is what views. Circular Imports Every Python programmer hates them.2 Working with Blueprints If you have larger applications it’s recommended to divide them into smaller groups where each group is implemented with the help of a blueprint. There are still some problems with that approach but if you want to use decorators there is no way around that.1.py would look like: from yourapplication import app @app.Here’s an example __init__.css /templates layout.py).. In this case views. and yet we just added some: circular imports (That’s when two modules depend on each other.py /static style.

So how would you then actually implement that? 20.register_blueprint(frontend) return app The downside is that you cannot use the application object in the blueprints at import time. you can have multiple instances of the same application running in the same application process which can be handy.init_app(app) from yourapplication. Of course you could have multiple instances with different configs set up in your webserver. you can then create multiple instances of this app later. 2. Multiple instances. Like this: def create_app(config_filename): app = Flask(__name__) app.register_blueprint(admin) app. Blueprint. You can have instances of the application with different settings to test every case.from_pyfile(config_filename) from yourapplication.admin import admin from yourapplication. render_template admin = Blueprint('admin'.20.frontend import frontend app.model import db db. So why would you want to do this? 1. A common pattern is creating the application object when the blueprint is imported.views. Testing. url_prefix='/admin') @admin.1 Basic Factories The idea is to set up the application in a function. Imagine you want to run different versions of the same ap- plication.config. but if you use factories.2 Application Factories If you are already using packages and blueprints for your application (Modular Appli- cations with Blueprints) there are a couple of really nice ways to further improve the experience.route('/') def index(): return render_template(current_app. __name__. But if you move the creation of this object into a function. How do you get access to the application with the config? Use current_app: from flask import current_app.2.config['INDEX_TEMPLATE']) 114 . You can however use it from within a request.views.

config.2. Using Flask-SQLAlchemy.2 Factories & Extensions It’s preferable to create your extensions and app factories so that the extension object does not initially get bound to the application.init_app(app) Using this design pattern.model import db db. in model.from_pyfile(config_filename) from yourapplication. 20. so one extension object can be used for multiple apps. as an example.Here we look up the name of a template in the config. For more information about the design of extensions refer to Flask Extension Development. rather.config.py (or equivalent): def create_app(config_filename): app = Flask(__name__) app.2.py file that creates such an application: from yourapplication import create_app app = create_app('/path/to/config.cfg') It can then be used with the flask command: export FLASK_APP=exampleapp flask run 115 .from_pyfile(config_filename) db = SQLAlchemy(app) But. 20.3 Using Applications So to use such an application you then have to create the application first in a sep- arate file otherwise the flask command won’t be able to find it. Here an example exampleapp. you should not do something along those lines: def create_app(config_filename): app = Flask(__name__) app.py (or equivalent): db = SQLAlchemy() and in your application. no application-specific state is stored on the extension ob- ject.

For development. For production.1 Working with this Document Each of the techniques and examples below results in an application object that can be run with any WSGI server. debugging must be enabled both on the ap- plication and the simple server. Add in WSGI middlewares when the application is creating if necessary. 20.debug = True 116 .3. They run different configurations and are dispatched on the WSGI level. You can combine not only Flask applications but any WSGI application. use_reloader=True) Note that run_simple is not intended for use in production.2. In order to use the interactive debugger. 20. see Deployment Options.20. run_simple(): from werkzeug. you can improve it.) 3. Werkzeug provides a builtin server for development available at werkzeug. 5000. make it possible to pass in configuration values for unittests so that you don’t have to create config files on the filesystem 2.3 Application Dispatching Application dispatching is the process of combining multiple Flask applications on the WSGI level.serving import run_simple app = Flask(__name__) app. application. Here is the “hello world” example with debugging and run_simple: from flask import Flask from werkzeug.serving import run_simple run_simple('localhost'. The usefulness of this depends on how the applications work internally.4 Factory Improvements The factory function from above is not very clever so far. call a function from a blueprint when the application is setting up so that you have a place to modify attributes of the application (like hooking in before / after request handlers etc. Use a full-blown WSGI server. The fundamental difference from the module approach is that in this case you are run- ning the same or different Flask applications that are entirely isolated from each other.serving. The following changes are straightforward and possible: 1. This would allow you to run a Django and a Flask application in the same interpreter side by side if you want.

In order to develop your application to support creating new instances in functions have a look at the Application Factories pattern. For instance you configure your webserver to dispatch all requests for all subdomains to your application and you then use the subdomain information to create user-specific in- stances. Assuming the application is created inside a function and you can call that function to instantiate it.2 Combining Applications If you have entirely separated applications and you want them to work next to each other in the same Python interpreter process you can take advantage of the werkzeug. For example you could have your main application run on / and your backend inter- face on /backend: from werkzeug. use_debugger=True. use_evalex=True) 20.3. 5000. The idea here is that each Flask application is a valid WSGI application and they are combined by the dispatcher middleware into a larger one that is dispatched based on prefix. app.3.wsgi import DispatcherMiddleware from frontend_app import application as frontend from backend_app import application as backend application = DispatcherMiddleware(frontend.@app.3 Dispatch by Subdomain Sometimes you might want to use multiple instances of the same application with different configurations.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': run_simple('localhost'. A very common example would be creating applications per subdomain. If that application does not exist yet. wsgi.DispatcherMiddleware. Once you have your server set up to listen on all subdomains you can use a very simple WSGI application to do the dynamic application creation. use_reloader=True. You write your own WSGI application that looks at the request that comes and delegates it to your Flask application. that is really easy to implement. it is dynamically created and remem- bered: 117 . The perfect level for abstraction in that regard is the WSGI layer. { '/backend': backend }) 20.

endswith(self. # We can then just return the NotFound() exception as # application which will render a default 404 page. host): host = host.instances[subdomain] = app return app def __call__(self. 'Configuration error' subdomain = host[:-len(self. create_app): self.get_application(environ['HTTP_HOST']) return app(environ.domain = domain self. get_user_for_subdomain from werkzeug. make_app) 20. start_response) This dispatcher can then be used like this: from myapplication import create_app.create_app(subdomain) self.lock = Lock() self.from threading import Lock class SubdomainDispatcher(object): def __init__(self.4 Dispatch by Path Dispatching by a path on the URL is very similar. environ.domain)]. # You might also redirect the user to the main page then return NotFound() # otherwise create the application for the specific user return create_app(user) application = SubdomainDispatcher('example.split(':')[0] assert host.lock: app = self.rstrip('.exceptions import NotFound def make_app(subdomain): user = get_user_for_subdomain(subdomain) if user is None: # if there is no user for that subdomain we still have # to return a WSGI application that handles that request.3. start_response): app = self.') with self. domain.instances. Instead of looking at the Host header to figure out the subdomain one simply looks at the request path up to the first slash: 118 .com'.get(subdomain) if app is None: app = self.create_app = create_app self.domain).instances = {} def get_application(self.

make_app) 20.create_app(prefix) if app is not None: self. One of the first things that developers run into is the realization that the builtin exceptions are not expressive enough for APIs and that the content type of text/html they are emitting is not very useful for API consumers.4 Implementing API Exceptions It’s very common to implement RESTful APIs on top of Flask.default_app return app(environ. get_user_for_prefix def make_app(prefix): user = get_user_for_prefix(prefix) if user is not None: return create_app(user) application = PathDispatcher(default_app.default_app = default_app self.create_app = create_app self.get(prefix) if app is None: app = self.instances[prefix] = app return app def __call__(self.lock = Lock() self.from threading import Lock from werkzeug. default_app.lock: app = self. environ. peek_path_info class PathDispatcher(object): def __init__(self. default_app. create_app): self. start_response): app = self.wsgi import pop_path_info.instances. prefix): with self.get_application(peek_path_info(environ)) if app is not None: pop_path_info(environ) else: app = self.instances = {} def get_application(self. start_response) The big difference between this and the subdomain one is that this one falls back to another application if the creator function returns None: from myapplication import create_app. The better solution than using abort to signal errors for invalid API usage is to im- 119 .

3 Usage in Views Here is how a view can use that functionality: 120 . That however is easy to add: @app.__init__(self) self. 20. a status code for the error and some optional payload to give more context for the error.2 Registering an Error Handler At that point views can raise that error. message.status_code = error.1 Simple Exception Class The basic idea is to introduce a new exception that can take a proper human readable message.message = message if status_code is not None: self. but it would immediately result in an internal server error.to_dict()) response.payload or ()) rv['message'] = self.plement your own exception type and install an error handler for it that produces the errors in the format the user is expecting.status_code return response 20.4.4. The reason for this is that there is no handler registered for this error class. This is a simple example: from flask import jsonify class InvalidUsage(Exception): status_code = 400 def __init__(self. status_code=None.payload = payload def to_dict(self): rv = dict(self.4. Additionally some extra payload can be provided as a dictionary through the payload parameter.status_code = status_code self.errorhandler(InvalidUsage) def handle_invalid_usage(error): response = jsonify(error.message return rv A view can now raise that exception with an error message. payload=None): Exception. 20.

. values): if 'lang_code' in values or not g.lang_code: 121 . @app.7 introduces the concept of URL processors. The code below checks if the language code is not yet in the dictionary of URL values and if the endpoint wants a value named 'lang_code': @app.lang_code = lang_code .. status_code=410) 20. URL processors are especially helpful when combined with blueprints. but if you want to generate URLs from one function to another you would have to still provide the language code explicitly which can be annoying.route('/<lang_code>/') def index(lang_code): g.5.route('/foo') def get_foo(): raise InvalidUsage('This view is gone'.1 Internationalized Application URLs Consider an application like this: from flask import Flask. 20.@app. They can automatically inject values into a call for url_for() automatically.route('/<lang_code>/about') def about(lang_code): g. This is an awful lot of repetition as you have to handle the language code setting on the g object yourself in every single function. Sure.. The idea is that you might have a bunch of resources with common parts in the URL that you don’t always explicitly want to provide. Flask 0. this is where url_defaults() functions come in. g app = Flask(__name__) @app. For instance you might have a bunch of URLs that have the language code in it but you don’t want to have to handle it in every single function yourself.. a decorator could be used to simplify this.7. We will handle both application specific URL processors here as well as blueprint specifics.5 Using URL Processors New in version 0.url_defaults def add_language_code(endpoint.lang_code = lang_code . For the latter.

20. You can further improve that by writing your own decorator that prefixes URLs with the language code. g app = Flask(__name__) @app. values): if 'lang_code' in values or not g..pop('lang_code'. Furthermore blueprints can have per- 122 .lang_code The method is_endpoint_expecting() of the URL map can be used to figure out if it would make sense to provide a language code for the given endpoint. but the more beautiful solution is using a blueprint. 'lang_code'): values['lang_code'] = g.lang_code = values..pop('lang_code'. 'lang_code'): values['lang_code'] = g.is_endpoint_expecting(endpoint. return if app. values): g. The idea is that they pull information out of the values dictionary and put it somewhere else: @app.is_endpoint_expecting(endpoint. values): g. @app.. Once the 'lang_code' is popped from the values dictionary and it will no longer be forwarded to the view function reducing the code to this: from flask import Flask.lang_code @app..url_value_preprocessor def pull_lang_code(endpoint.url_value_preprocessor def pull_lang_code(endpoint.url_defaults def add_language_code(endpoint.route('/<lang_code>/') def index(): .2 Internationalized Blueprint URLs Because blueprints can automatically prefix all URLs with a common string it’s easy to automatically do that for every function. They are executed right after the request was matched and can execute code based on the URL values.5.url_map. None) That way you no longer have to do the lang_code assignment to g in every function.lang_code: return if app. None) @app.url_map.lang_code = values.route('/<lang_code>/about') def about(): . The reverse of that function are url_value_preprocessor()s.

url_defaults def add_language_code(endpoint. you will already have pip and setuptools on your system..4) installed from python. If you have Python 2 (>=2. Flask itself.route('/about') def about(): .lang_code = values.url_value_preprocessor def pull_lang_code(endpoint.9) or Python 3 (>=3.route('/') def index(): . g bp = Blueprint('frontend'. Otherwise. you will need to install them yourself. and all the libraries you can find on PyPI are distributed with either setup- tools or distutils.lang_code) @bp. 123 .6 Deploying with Setuptools Setuptools. a basic module installation system shipped with Python to also support various more complex constructs that make larger applications easier to distribute: • support for dependencies: a library or application can declare a list of other libraries it depends on which will be installed automatically for you. 20. The best known feature of this system is the entry point sup- port which allows one package to declare an “entry point” that another package can hook into to extend the other package. __name__. url_prefix='/<lang_code>') @bp. is an extension library that is commonly used to distribute Python libraries and extensions.org.. values): values. • package registry: setuptools registers your package with your Python installa- tion. g.setdefault('lang_code'. It extends distutils..pop('lang_code') @bp. values): g. This makes it possible to query information provided by one package from another package. @bp. • installation manager: pip can install other libraries for you.blueprint URL processors which removes a whole lot of logic from the url_defaults() function because it no longer has to check if the URL is really interested in a 'lang_code' parameter: from flask import Blueprint..7.

py next to your application.In this case we assume your application is called yourapplication. The zip_safe flag can be used to force or prevent zip Archive creation. but a package. Flask already depends upon setuptools. you better not change it. If you want setuptools to lookup the packages for you automatically. zip_safe=False. A working deployment with setuptools is the first step into more complex and more automated deployment scenarios. In general you probably don’t want your packages to be installed as zip files because some tools do not support them and they make debugging a lot harder. packages=['yourapplication']. but because everybody will look for a file with that name. also read the Deploying with Fabric chapter.py and you are not using a module. Your setup code always goes into a file named setup. The name of the file is only convention.6. packages=find_packages() ) Most parameters to the setup function should be self explanatory. head over to the Larger Applications pattern to see how this can be done. A basic setup. install_requires=['Flask'] ) Please keep in mind that you have to list subpackages explicitly.0'. find_packages setup( . include_package_data and zip_safe might not be. If you have not yet converted your application into a package. 20.in file and install all the entries that match as package data.. include_package_data=True. you can use the find_packages function: from setuptools import setup. long_description=__doc__.. you have setuptools available on your system. Standard disclaimer applies: you better use a virtualenv. include_package_data tells setuptools to look for a MANIFEST.1 Basic Setup Script Because you have Flask installed. version='1. If you want to fully automate the process. 124 .py file for a Flask application looks like this: from setuptools import setup setup( name='Your Application'. We will use this to distribute the static files and templates along with the Python module (see Distributing Resources).

7.tar.3 Distributing Resources If you try to install the package you just created. This file lists all the files that should be added to your tarball: recursive-include yourapplication/templates * recursive-include yourapplication/static * Don’t forget that even if you enlist them in your MANIFEST.<=1.0' ] As mentioned earlier. The reason for this is that setuptools does not know which files to add for you. Add a setup.gz.20. py release sdist will create a release package with only the version: flaskr-1. Running python setup.6.dev tag_date = 1 [aliases] release = egg_info -RDb ‘’ Running python setup. Here some examples: install_requires=[ 'Flask>=0.com/yourfiles'] 125 . 20. dependencies are pulled from PyPI. you will notice that folders like static or templates are not installed for you. Each item in that list is the name of a package that should be pulled from PyPI on installation. they won’t be in- stalled for you unless you set the include_package_data parameter of the setup function to True! 20.dev20160314. By default it will always use the most recent version.cfg file to configure these options.tar.py file.6'. 'BrokenPackage>=0. gz. but you can also provide minimum and maximum version requirements. is to create a MANIFEST. What if you want to depend on a package that cannot be found on PyPI and won’t be because it is an internal package you don’t want to share with anyone? Just do it as if there was a PyPI entry and provide a list of alternative locations where setuptools should look for tarballs: dependency_links=['http://example.4 Declaring Dependencies Dependencies are declared in the install_requires parameter as a list.dev” and the current date appended: flaskr-1. What you should do.py sdist will create a development package with ”.6.2 Tagging Builds It is useful to distinguish between release and development builds.in file. 'SQLAlchemy>=0. [egg_info] tag_build = .6.2'.0.0.in file next to your setup.

provide the URL to that server. You can of course use your own favourite server there. All the functions defined in that file will show up as fab subcom- 126 .0 has to be installed locally. This tutorial assumes the latest version of Fabric.Make sure that page has a directory listing and the links on the page are pointing to the actual tarballs with their correct filenames as this is how setuptools will find the files. • In the following example we are using mod_wsgi for the remote servers.py install If you are developing on the package and also want the requirements to be installed. • The application already has to be a package and requires a working setup. It will install your application into the virtualenv’s site- packages folder and also download and install all dependencies: $ python setup. but for this example we chose Apache + mod_wsgi because it’s very easy to setup and has a simple way to reload applications without root access.py develop This has the advantage of just installing a link to the site-packages folder instead of copying the data over.7. If you have an internal company server that contains the packages.1 Creating the first Fabfile A fabfile is what controls what Fabric executes. 20.5 Installing / Developing To install your application (ideally into a virtualenv) just run the setup.6. Before we get started. here a quick checklist of things we have to ensure upfront: • Fabric 1. 20.py and executed by the fab command. You can then continue to work on the code without having to run install again after each change.py script with the install parameter. In combination with a properly set up Python package (Larger Applications) and a good concept for configurations (Configuration Handling) it is very easy to deploy Flask applications to external servers.7 Deploying with Fabric Fabric is a tool for Python similar to Makefiles but with the ability to execute com- mands on a remote server. you can use the develop command instead: $ python setup. It is named fabfile. 20.py file (Deploying with Setuptools).

strip() filename = '%s.example. If we just have one application server (which the majority of applications will have).wsgi file to trigger a reload in mod_wsgi run('touch /var/www/yourapplication.api import * # the user to use for the remote commands env. They are executed on one or more hosts. Fur- thermore are we not creating the configuration or . In this case we will add them to the fabfile. capture=False) def deploy(): # figure out the package name and version dist = local('python setup.wsgi') 20. These hosts can be defined either in the fabfile or on the command line.7.wsgi file on the server.py --fullname'.2 Running Fabfiles Now how do you execute that fabfile? You use the fab command. In that case you 127 . But obviously you can do that. capture=True).example.hosts = ['server1.user = 'appuser' # the servers where the commands are executed env. To deploy the current version of the code on the remote server you would use this command: $ fab pack deploy However this requires that our server already has the /var/www/yourapplication folder created and /var/www/yourapplication/env to be a virtual environment. 'server2.com'.py sdist --formats=gztar'.gz' % dist # upload the package to the temporary folder on the server put('dist/%s' % filename.tar.mands.com'] def pack(): # build the package local('python setup. This is a basic first example that has the ability to upload the current source code to the server and install it into a pre-existing virtual environment: from fabric. '/tmp/%s' % filename) # install the package in the application's virtualenv with pip run('/var/www/yourapplication/env/bin/pip install /tmp/%s' % filename) # remove the uploaded package run('rm -r /tmp/%s' % filename) # touch the . creating a command in the fabfile for this is overkill. So how do we bootstrap a new server into our infrastructure? This now depends on the number of servers we want to set up.

wsgi file so that we can automatically reload the application by touching it.7. Create a new Apache config for yourapplication and activate it. Make sure to ac- tivate watching for changes of the .config.environ['YOURAPPLICATION_CONFIG'] = '/var/www/yourapplication/application. (See mod_wsgi (Apache) for more information) So now the question is.default_config') app. Create the directory structure in /var/www: $ mkdir /var/www/yourapplication $ cd /var/www/yourapplication $ virtualenv --distribute env 2. where do the application.would probably call it setup or bootstrap and then pass the servername explicitly on the command line: $ fab -H newserver.example. So we have to put the configuration in a place where the application will able to find it. 20. the application will find the correct configuration file by looking up the YOURAPPLICATION_CONFIG environment variable.cfg) 3. Configuration files 128 .7. This is a short example that does exactly that: import os os.4 The Configuration File Now as mentioned above.config.cfg' from yourapplication import app The application itself then has to initialize itself like this to look for the config at that environment variable: app = Flask(__name__) app.wsgi file to the server and the configuration file for the application (eg: application.from_envvar('YOURAPPLICATION_CONFIG') This approach is explained in detail in the Configuration Handling section of the docu- mentation.from_object('yourapplication.wsgi and application.3 The WSGI File The WSGI file has to import the application and also to set an environment variable so that the application knows where to look for the config.cfg files come from? 20. Upload a new application.com bootstrap To setup a new server you would roughly do these steps: 1.

That way you can also easily go back to older versions. in our case here we only expect one or two servers and we can upload them ahead of time by hand. We have set up the servers so that they have their virtual environments and activated apache configs. A popular approach is to store configuration files for different servers in a sepa- rate version control repository and check them out on all servers. 20. First it will execute pack so that we have our tarball ready and then it will execute deploy and upload the source code to all servers and install it there. Then symlink the file that is active for the server into the location where it’s expected (eg: /var/www/ yourapplication). Now we can pack up the application and deploy it: $ fab pack deploy Fabric will now connect to all servers and run the commands as written down in the fabfile. Working with Fabric is fun and you will notice that it’s quite magical to type fab deploy and see your application being deployed automatically to one or more remote servers.5 First Deployment Now we can do our first deployment. It could initialize a new virtual environment. Either way. 129 . 20. so you do not version them usually.7.have the unfriendly quality of being different on all computers. Thanks to the setup. • Put configuration files into a separate version control repository and symlink the active configs into place. • hook in testing functionality so that you can deploy to an external server and run the test suite. setup apache appropriately etc.6 Next Steps From that point onwards there is so much that can be done to make deployment actu- ally fun: • Create a bootstrap command that initializes new servers.py file we will automatically pull in the required libraries into our virtual environment.7. • You could also put your application code into a repository and check out the latest version on the server and then install.

top instead of g as the flask.20. Example: @app.close() Now.9 or older you need to use flask._database = sqlite3.8 Using SQLite 3 with Flask In Flask you can easily implement the opening of database connections on demand and closing them when the context dies (usually at the end of the request).route('/') def index(): cur = get_db(). Because of this we have to make sure here that the database is there before we close it. '_database'. Whenever the context is destroyed the database connection will be terminated. even if a before-request handler failed or was never executed._app_ctx_stack.1 Connect on Demand The upside of this approach (connecting on first use) is that this will only open the connection if truly necessary.. Note: if you use Flask 0.g object was bound to the request and not application context. At that point the get_db function can be used to get the current database connec- tion.db' def get_db(): db = getattr(g. Note: Please keep in mind that the teardown request and appcontext functions are al- ways executed.8.cursor() . the application must either have an active application con- text (which is always true if there is a request in flight) or create an application context itself.connect(DATABASE) return db @app. to use the database. If you want to use this code outside a request context you can use it in a Python shell by opening the application context by hand: 130 . None) if db is None: db = g. None) if db is not None: db.. 20.teardown_appcontext def close_connection(exception): db = getattr(g. '_database'. Here is a simple example of how you can use SQLite 3 with Flask: import sqlite3 from flask import g DATABASE = '/path/to/database.

this could be inserted into the get_db function we created above: def make_dicts(cursor. and MiddleInitial: >>> # You can get values based on the row's name >>> r['FirstName'] John >>> # Or. These are namedtuple s. args) rv = cur.execute(query.row_factory = sqlite3. print(value) 1 John Doe M Additionally. value in enumerate(row)) db.. as- suming we have a sqlite3.2 Easy Querying Now in each request handling function you can access g. a row factory function is use- ful.Row called r for the rows id. Even more simply. args=().8. To simplify working with SQLite. For instance.Row This would use Row objects rather than dicts to return the results of queries. in order to get dictionaries instead of tuples. row): return dict((cursor. one=False): cur = get_db().db to get the current open database connection. we could place this in get_db instead: db. For example. executing and fetching the results: def query_db(query. it is a good idea to provide a query function that combines getting the cursor.description[idx][0]. It is executed for every result returned from the database to convert the result. LastName.row_factory = make_dicts This will make the sqlite3 module return dicts for this database connection.app_context(): # now you can use get_db() 20. which are much nicer to deal with. FirstName. you can get them based on index >>> r[1] John # Row objects are also iterable: >>> for value in r: .fetchall() cur.with app. value) for idx.close() return (rv[0] if rv else None) if one else rv 131 . so we can access them either by index or by key..

sql file that creates the database.cursor().executescript(f. user['user_id'] Or if you just want a single result: user = query_db('select * from users where username = ?'.open_resource('schema. Never directly add them to the SQL statement with string formatting because this makes it possible to attack the application using SQL Injections.8.app_context(): db = get_db() with app. Here is how you can use it: for user in query_db('select * from users'): print user['username']. one=True) if user is None: print 'No such user' else: print the_username. [the_username]. in combination with a row factory.commit() You can then create such a database from the Python shell: >>> from yourapplication import init_db >>> init_db() 20. 'has the id'. It’s a good idea to provide a function that creates the database based on that schema. This function can do that for you: def init_db(): with app.sql'. user['user_id'] To pass variable parts to the SQL statement.This handy little function.9 SQLAlchemy in Flask Many people prefer SQLAlchemy for database access. so applications often ship a schema. mode='r') as f: db. 20. In this case it’s encouraged to use a package instead of a module for your flask application and drop the models into 132 .3 Initial Schemas Relational databases need schemas. makes working with the database much more pleasant than it is by just using the raw cursor and connection objects. use a question mark in the statement and pass in the arguments as a list. 'has the id'.read()) db.

There are four very common ways to use SQLAlchemy.9. sessionmaker from sqlalchemy. you just have to put the following code into your application module. just subclass the Base class that was created by the code above.query = db_session. If you are wondering why we don’t have to care about threads here (like we did in the SQLite3 example above with the g object): that’s because SQLAlchemy does that for us already with the scoped_session. This is recommended if you want to get started quickly.models Base. In addition to the following text I recommend the official documenta- tion on the declarative extension.9. similar to how Django works. autoflush=False.2 Declarative The declarative extension in SQLAlchemy is the most recent method of using SQLAlchemy. bind=engine)) Base = declarative_base() Base. I will outline each of them here: 20. Flask will automatically remove database sessions at the end of the request or when the application shuts down: 133 .create_all(bind=engine) To define your models.ext. Here’s the example database. While that is not necessary. convert_unicode=True) db_session = scoped_session(sessionmaker(autocommit=False.query_property() def init_db(): # import all modules here that might define models so that # they will be registered properly on the metadata.declarative import declarative_base engine = create_engine('sqlite:////tmp/test. there is a Flask extension that handles that for you. You can download Flask-SQLAlchemy from PyPI.metadata.py module for your application: from sqlalchemy import create_engine from sqlalchemy. To use SQLAlchemy in a declarative way with your application.db'.a separate module (Larger Applications). Otherwise # you will have to import them first before calling init_db() import yourapplication.orm import scoped_session. it makes a lot of sense. It allows you to define tables and models in one go. 20.1 Flask-SQLAlchemy Extension Because SQLAlchemy is a common database abstraction layer and object relational mapper that requires a little bit of configuration effort.

name) To create the database you can use the init_db function: >>> from yourapplication.first() <User u'admin'> 20.py. It’s more flexible but a little more to type.): from sqlalchemy import Column. name=None.all() [<User u'admin'>] >>> User. unique=True) email = Column(String(120).from yourapplication.name == 'admin').models import User >>> u = User('admin'. String from yourapplication. primary_key=True) name = Column(String(50).filter(User.database import db_session @app. Integer.database import init_db >>> init_db() You can insert entries into the database like this: >>> from yourapplication.commit() Querying is simple as well: >>> User.query. e.query.g.name = name self. unique=True) def __init__(self.email = email def __repr__(self): return '<User %r>' % (self.add(u) >>> db_session.3 Manual Object Relational Mapping Manual object relational mapping has a few upsides and a few downsides versus the declarative approach from above.database import Base class User(Base): __tablename__ = 'users' id = Column(Integer. 'admin@localhost') >>> db_session. The main difference is that you define tables and classes separately and map them together. 134 . email=None): self.9.remove() Here is an example model (put this into models.database import db_session >>> from yourapplication.teardown_appcontext def shutdown_session(exception=None): db_session.

name) users = Table('users'. Column('name'. name=None. sessionmaker engine = create_engine('sqlite:////tmp/test. convert_unicode=True) metadata = MetaData() db_session = scoped_session(sessionmaker(autocommit=False. autoflush=False. Column('email'. so make sure to also split up your application into multiple modules in a package. Column. String(120).create_all(bind=engine) As in the declarative approach. primary_key=True). Put this into your application module: from yourapplication. String(50).orm import mapper from yourapplication. bind=engine)) def init_db(): metadata. MetaData from sqlalchemy. 135 . Here is an example database.email = email def __repr__(self): return '<User %r>' % (self.name = name self. Integer. String from sqlalchemy.database import db_session @app. Column('id'. users) Querying and inserting works exactly the same as in the example above. db_session class User(object): query = db_session.remove() Here is an example table and model (put this into models.orm import scoped_session. you need to close the session after each request or application context shutdown.py module for your application: from sqlalchemy import create_engine.In general it works like the declarative approach.db'.py): from sqlalchemy import Table. email=None): self. unique=True).query_property() def __init__(self.teardown_appcontext def shutdown_session(exception=None): db_session. unique=True) ) mapper(User. metadata.database import metadata. Integer.

u'admin'.execute(users.first() (1.first() (1.select(users.execute(). 20. Table engine = create_engine('sqlite:////tmp/test. u'admin@localhost') These results are also dict-like tuples: >>> r = users. A <form> tag is marked with enctype=multipart/form-data and an <input type=file> is placed in that form. We have to get a connection first so that we can use a transaction: >>> con = engine.db'.execute('select * from users where id = :1'.id == 1). [1]). the good old problem of file uploads.first() >>> r['name'] u'admin' You can also pass strings of SQL statements to the execute() method: >>> engine. name='admin'. convert_unicode=True) metadata = MetaData(bind=engine) Then you can either declare the tables in your code like in the examples above. metadata. It basically works like this: 1. To query your database.20. or automatically load them: from sqlalchemy import Table users = Table('users'. u'admin@localhost') For more information about SQLAlchemy. 136 . MetaData.c. email='admin@localhost') SQLAlchemy will automatically commit for us. u'admin'.insert(). autoload=True) To insert data you can use the insert method.c.9.execute(). head over to the website.4 SQL Abstraction Layer If you just want to use the database system (and SQL) abstraction layer you basically only need the engine: from sqlalchemy import create_engine.id == 1).connect() >>> con. you use the engine directly or use a connection: >>> users.select(users. The basic idea of file uploads is actually quite simple.10 Uploading Files Ah yes.

lower() in ALLOWED_EXTENSIONS @app. Also make sure to disallow . browser also # submit a empty part without filename if file. right? :) Next the functions that check if an extension is valid and that uploads the file and redirects the user to the URL for the uploaded file: def allowed_file(filename): return '. Why do we limit the extensions that are allowed? You probably don’t want your users to be able to upload everything there if the server is directly sending out the data to the client.' in filename and \ filename. That way you can make sure that users are not able to upload HTML files that would cause XSS problems (see Cross-Site Scripting (XSS)).config['UPLOAD_FOLDER'] = UPLOAD_FOLDER So first we need a couple of imports. 'jpeg'. 'gif']) app = Flask(__name__) app.'.utils import secure_filename UPLOAD_FOLDER = '/path/to/the/uploads' ALLOWED_EXTENSIONS = set(['txt'.files['file'] # if user does not select file. 'jpg'. 1)[1]. Most should be straightforward. The UPLOAD_FOLDER is where we will store the uploaded files and the ALLOWED_EXTENSIONS is the set of allowed file exten- sions. but who has PHP installed on their server.10. The application accesses the file from the files dictionary on the request object.rsplit('. request. 'png'. 'pdf'. 2.1 A Gentle Introduction Let’s start with a very basic application that uploads a file to a specific upload folder and displays a file to the user. 3.method == 'POST': # check if the post request has the file part if 'file' not in request. 'POST']) def upload_file(): if request.route('/'.url) file = request. redirect.files: flash('No file part') return redirect(request. url_for from werkzeug. secure_filename() is explained a little bit later. Let’s look at the bootstrapping code for our application: import os from flask import Flask. methods=['GET'. 20. use the save() method of the file to save the file permanently somewhere on the filesystem. the werkzeug.filename == '': 137 .php files if the server executes them.

join(app. So we write the uploaded_file() function to return the file of that name.. In the upload_file() we redirect the user to url_for('uploaded_file'.config['UPLOAD_FOLDER']./home/username/.filename): filename = secure_filename(file. For the moment just remember: always use that function to secure a filename before storing it directly on the filesystem./ is correct and you would join this with the UPLOAD_FOLDER the user might have the ability to modify a file on the server’s filesystem he or she should not modify. but trust me. filename)) return redirect(url_for('uploaded_file'./.5 we can use a function that does that for us: from flask import send_from_directory @app.bashrc" Assuming the number of ..bashrc') 'home_username_./.. hackers are patient :) Now let’s look how that function works: >>> secure_filename('..... and filenames can be dan- gerous. As of Flask 0. This does require some knowledge about how the application looks like.path.url) if file and allowed_file(file.. / uploads/filename. filename=filename).filename) file.route('/uploads/<filename>') 138 .save(os. This is also true for the filename of an uploaded file. that is. flash('No selected file') return redirect(request.bashrc' Now one last thing is missing: the serving of the uploaded files./home/username/. filename=filename)) return ''' <!doctype html> <title>Upload new File</title> <h1>Upload new File</h1> <form method=post enctype=multipart/form-data> <p><input type=file name=file> <input type=submit value=Upload> </form> ''' So what does that secure_filename() function actually do? Now the problem is that there is that principle called “never trust user input”././. All submitted form data can be forged. Information for the Pros So you’re interested in what that secure_filename() function does and what the prob- lem is if you’re not using it? So just imagine someone would send the following infor- mation as filename to your application: filename = "./../.

This also works with older versions of Flask: from werkzeug import SharedDataMiddleware app.config['UPLOAD_FOLDER'].config['UPLOAD_FOLDER'] }) If you now run the application everything should work as expected. { '/uploads': app. 139 .add_url_rule('/uploads/<filename>'.wsgi_app. but you can limit that by setting the MAX_CONTENT_LENGTH config key: from flask import Flask.10. So how exactly does Flask handle uploads? Well it will store them in the webserver’s memory if the files are reasonable small otherwise in a temporary location (as returned by tempfile. 20. 20.3 Upload Progress Bars A while ago many developers had the idea to read the incoming file in small chunks and store the upload progress in the database to be able to poll the progress with JavaScript from the client.2 Improving Uploads New in version 0.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 The code above will limited the maximum allowed payload to 16 megabytes.6 but can be achieved in older versions as well by subclassing the request object. This feature was added in Flask 0. filename) Alternatively you can register uploaded_file as build_only rule and use the SharedDataMiddleware. Request app = Flask(__name__) app. For more information on that consult the Werkzeug documentation on file handling.wsgi_app = SharedDataMiddleware(app. If a larger file is transmitted.6. But how do you specify the maximum file size after which an upload is aborted? By default Flask will happily accept file uploads to an un- limited amount of memory.gettempdir()).def uploaded_file(filename): return send_from_directory(app.10. build_only=True) app. 'uploaded_file'. Long story short: the client asks the server every 5 seconds how much it has transmitted already. Flask will raise an RequestEntityTooLarge exception. Do you realize the irony? The client is asking for something it should already know.

Well. What does a cache do? Say you have a function that takes some time to complete but the results would still be good enough if they were 5 min- utes old.contrib. If you are using the development server you can create a SimpleCache object. that one is a simple cache that keeps the item stored in the memory of the Python interpreter: from werkzeug.cache import MemcachedCache cache = MemcachedCache(['127.0. there is also a Flask extension called Flask-Uploads that implements a full fledged upload mechanism with white and blacklisting of exten- sions and more. Because the common pattern for file uploads exists almost unchanged in all applica- tions dealing with uploads.0. 20. normally you want to use a memcached server.cache import GAEMemcachedCache cache = GAEMemcachedCache() 140 .contrib.1:11211']) If you are using App Engine. Flask itself does not provide caching for you.contrib.10. at least it’s the easiest way to speed up things.1 Setting up a Cache You create a cache object once and keep it around. one of the libraries it is based on. but Werkzeug. So then the idea is that you actually put the result of that calculation into a cache for some time.11.20. you can connect to the App Engine memcache server easily: from werkzeug.11 Caching When your application runs slow. make sure to have one of the memcache modules supported (you get them from PyPI) and a memcached server running somewhere. similar to how Flask objects are created. has some very basic cache support. There are JavaScript libraries like jQuery that have form plugins to ease the construction of progress bar.4 An Easier Solution Now there are better solutions that work faster and are more reliable. throw some caches in. This is how you connect to such an memcached server then: from werkzeug.cache import SimpleCache cache = SimpleCache() If you want to use memcached. It supports multiple cache backends. 20.

user and is None if there is no-one logged in. url_for def login_required(f): 141 . But there are use cases for implementing your own decorator. The route() decorator is the one you probably used already. This allows some really neat things for web applications. The first argument is the key and the second the value that should be set. Because each view in Flask is a function. For instance. This is a good example of a use case where a decorator is an excellent solution. If something is in the cache.2 Using a Cache Now how can one use such a cache? There are two very important operations: get() and set().11. A decorator is a function that wraps and replaces another function. Otherwise that function will return None: rv = cache.get('my-item') To add items to the cache. they should be redirected to the login page. Here a full example how this looks like normally: def get_my_item(): rv = cache.set('my-item'. 20. redirect. This example assumes that the login page is called 'login' and that the current user is stored in g.get('my-item') if rv is None: rv = calculate_value() cache. Also a timeout can be provided after which the cache will automatically remove item. Use functools. This is how to use them: To get an item from the cache call get() with a string as key name. you need to remember to copy the original function’s information to the new function. from functools import wraps from flask import g. If a user goes to the site and is not logged in. timeout=5 * 60) return rv 20. use the set() method instead.1 Login Required Decorator So let’s implement such a decorator. rv. Since the original function is replaced. it is returned. request. dec- orators can be used to inject additional functionality to one or more functions.wraps() to handle this for you. imagine you have a view that should only be used by people that are logged in.12.20.12 View Decorators Python has a really interesting feature called function decorators.

**kwargs): if g. Sounds aw- ful? Unfortunately it is a little bit more complex.2 Caching Decorator Imagine you have a view function that does an expensive calculation and because of that you would like to cache the generated results for a certain amount of time. then retrieve it from request. but the code should still be straight- forward to read. When apply- ing further decorators.url)) return f(*args. It generates the cache key from a specific prefix (actually a format string) and the current path of the request. <input type="hidden" value="{{ request. @wraps(f) def decorated_function(*args. A decorator would be nice for that. 2. otherwise the original function is called and the return value is stored in the cache for the timeout provided (by default 5 minutes).get('next'. apply it as innermost decorator to a view function. **kwargs) return decorated_function To use the decorator. always remember that the route() decorator is the outermost.form when logging the user in.12. If the cache returned something we will return that value.user is None: return redirect(url_for('login'. The decorated function will then work as follows 1. get the value for that key from the cache. '') }}"/> 20.route('/secret_page') @login_required def secret_page(): pass Note: The next value will exist in request. Notice that we are using a function that first creates the decorator that then decorates the function.args. Here is an example cache function. 3. You’ll have to pass it along when sending the POST request from the login form. We’re assuming you have set up a cache like mentioned in Caching. get the unique cache key for the current request base on the current path. Here the code: 142 . @app. next=request.args after a GET request for the login page. You can do this with a hidden input tag.

Otherwise the provided template name is used. if no template name is provided it will use the endpoint of the URL map with dots converted to slashes + '.path rv = cache. timeout=timeout) return rv return decorated_function return decorator Notice that this assumes an instantiated cache object is available. With that.html'. the dictionary returned is passed to the template rendering function.html'. the following three examples do exactly the same: @app.html') def index(): return dict(value=42) @app. When the decorated function returns. an empty dictionary is assumed. key='view/%s'): def decorator(f): @wraps(f) def decorated_function(*args.3 Templating Decorator A common pattern invented by the TurboGears guys a while back is a templating decorator.route('/') def index(): return render_template('index. value=42) @app. If None is returned.set(cache_key. Here is the code for that decorator: 143 . if something else than a dictionary is returned we return it from the function unchanged. **kwargs) cache.route('/') @templated() def index(): return dict(value=42) As you can see. rv.get(cache_key) if rv is not None: return rv rv = f(*args.route('/') @templated('index. see Caching for more information.12. 20. **kwargs): cache_key = key % request. That way you can still use the redirect function or return simple strings. The idea of that decorator is that you return a dictionary with the values passed to the template from the view function and the template is automatically ren- dered.from functools import wraps from flask import request def cached(timeout=5 * 60.

render_template def templated(template=None): def decorator(f): @wraps(f) def decorated_function(*args. There are libraries out there designed to make this process easier to manage.endpoint('index') def my_index(): return "Hello world" 20. endpoint='index')) @app. When you are working with WTForms you have to define your forms as classes first.13 Form Validation with WTForms When you have to work with form data submitted by a browser view. **ctx) return decorated_function return decorator 20.4 Endpoint Decorator When you want to use the werkzeug routing system for more flexibility you need to map the endpoint as defined in the Rule to a view function. One of them is WTForms which we will handle here. dict): return ctx return render_template(template_name.add(Rule('/'. If you find yourself in the situation of having many forms.12. 144 . This is possible with this decorator. I recommend breaking up the application into multiple modules (Larger Applications) for that and adding a separate module for the forms.'. you might want to give it a try.endpoint \ .from functools import wraps from flask import request.routing import Rule app = Flask(__name__) app. '/') + '. code quickly becomes very hard to read. **kwargs): template_name = template if template_name is None: template_name = request.url_map. For example: from flask import Flask from werkzeug.replace('. **kwargs) if ctx is None: ctx = {} elif not isinstance(ctx.html' ctx = f(*args.

Adapt the code as necessary. [validators.form) if request. 2. max=25)]) email = StringField('Email Address'.1 The Forms This is an example form for a typical registration page: from wtforms import Form. methods=['GET'. form. but that’s not a requirement. create the form from the request form value if the data is submitted via the HTTP POST method and args if the data is submitted as GET. False otherwise.password. call the validate() method. the usage of this form looks like this: @app.Getting the most out of WTForms with an Extension The Flask-WTF extension expands on this pattern and adds a few little helpers that make working with forms and Flask more fun.13.data. 20. Things to remember: 1.2 In the View In the view function.add(user) flash('Thanks for registering') return redirect(url_for('login')) return render_template('register. You can get it from PyPI.DataRequired()]) 20. 'POST']) def register(): form = RegistrationForm(request. form=form) Notice we’re implying that the view is using SQLAlchemy here (SQLAlchemy in Flask).email. which will return True if the data validates. validators. [ validators. to validate the data.username.data. BooleanField. [validators. form.data. 145 .Length(min=4. PasswordField.<NAME>.data) db_session.route('/register'. max=35)]) password = PasswordField('New Password'. message='Passwords must match') ]) confirm = PasswordField('Repeat Password') accept_tos = BooleanField('I accept the TOS'. [validators.html'.DataRequired(). to access individual values from the form.13. validators class RegistrationForm(Form): username = StringField('Username'. of course.method == 'POST' and form.EqualTo('confirm'.Length(min=6. StringField.validate(): user = User(form. access form. 3.

So.errors %} <li>{{ error }}</li> {% endfor %} </ul> {% endif %} </dd> {% endmacro %} This macro accepts a couple of keyword arguments that are forwarded to WTForm’s field function. 146 .confirm) }} {{ render_field(form. Here’s an example _formhelpers.accept_tos) }} </dl> <p><input type=submit value=Register> </form> For more information about WTForms. Look at the following example template to see how easy this is.username) }} {{ render_field(form. Note that WTForms returns standard Python unicode strings.username.html template for the function we used above. which takes ad- vantage of the _formhelpers. Here is the register.label }} <dd>{{ field(**kwargs)|safe }} {% if field. you can easily render them there.20. WTForms does half the form generation for us already.13.html" import render_field %} <form method=post> <dl> {{ render_field(form.errors %} <ul class=errors> {% for error in field. The keyword arguments will be inserted as HTML attributes. so we have to tell Jinja2 that this data is already HTML-escaped with the |safe filter. To make it even nicer. When you pass the form to the templates. which renders the field for us. we can write a macro that renders a field with label and a list of errors if there are any. for example.password) }} {{ render_field(form.3 Forms in Templates Now to the template side.html template with such a macro: {% macro render_field(field) %} <dt>{{ field.email) }} {{ render_field(form. head over to the WTForms website. class='username') to add a class to the input element. you can call render_field(form.html template: {% from "_formhelpers.

filename='style. Template inheritance allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override. Sounds complicated but is very basic.html. Copyright 2010 by <a href="http://domain.1 Base Template This template. } </style> 147 . which we’ll call layout.invalid/">you</a>. It’s the job of “child” tem- plates to fill the empty blocks with content: <!doctype html> <html> <head> {% block head %} <link rel="stylesheet" href="{{ url_for('static'. 20. {% endblock %} </div> </body> </html> In this example.My Webpage</title> {% endblock %} </head> <body> <div id="content">{% block content %}{% endblock %}</div> <div id="footer"> {% block footer %} &copy.14 Template Inheritance The most powerful part of Jinja is template inheritance. defines a simple HTML skeleton docu- ment that you might use for a simple two-column page.14. All the block tag does is tell the template engine that a child template may override those portions of the template.20.css') }}"> <title>{% block title %}{% endblock %} .html" %} {% block title %}Index{% endblock %} {% block head %} {{ super() }} <style type="text/css"> . 20.important { color: #336699.2 Child Template A child template might look like this: {% extends "layout. the {% block %} tags define four blocks that child templates can fill in. It’s easiest to understand it by starting with an example.14.

This means that flashing messages that are too large for session cookies causes message flashing to fail silently.form['password'] != 'secret': error = 'Invalid credentials' else: flash('You were successfully logged in') 148 . {% endblock %} The {% extends %} tag is the key here.15 Message Flashing Good applications and user interfaces are all about feedback. use {{ super() }}. To render the contents of a block defined in the parent template. When the template system evaluates this template. 20. first it locates the parent. \ request. The flashing system basically makes it possible to record a message at the end of a request and access it next request and only next request. methods=['GET'. render_template.secret_key = 'some_secret' @app.1 Simple Flashing So here is a full example: from flask import Flask.{% endblock %} {% block content %} <h1>Index</h1> <p class="important"> Welcome on my awesome homepage. Note that browsers and sometimes web servers enforce a limit on cookie sizes.route('/') def index(): return render_template('index.route('/login'.html') @app.form['username'] != 'admin' or \ request. url_for app = Flask(__name__) app. 'POST']) def login(): error = None if request. 20. Flask provides a really simple way to give feedback to a user with the flashing system. It tells the template engine that this template “extends” another template. This is usually combined with a layout template that does this. flash. If the user does not get enough feedback they will probably end up hating the application.method == 'POST': if request.15. redirect. The extends tag must be the first tag in the template.

username }}"> <dt>Password: <dd><input type=password name=password> </dl> <p><input type=submit value=Login> </form> {% endblock %} 20.html template which does the magic: <!doctype html> <title>My Application</title> {% with messages = get_flashed_messages() %} {% if messages %} <ul class=flashes> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> {% endif %} {% endwith %} {% block body %}{% endblock %} Here is the index.html: {% extends "layout.html: {% extends "layout.html'.html" %} {% block body %} <h1>Login</h1> {% if error %} <p class=error><strong>Error:</strong> {{ error }} {% endif %} <form method=post> <dl> <dt>Username: <dd><input type=text name=username value="{{ request. error=error) And here is the layout.3.html template which inherits from layout.html template which also inherits from layout.2 Flashing With Categories New in version 0.15.html" %} {% block body %} <h1>Overview</h1> <p>Do you want to <a href="{{ url_for('login') }}">log in?</a> {% endblock %} And here is the login. 149 .form. return redirect(url_for('index')) return render_template('login.

message in messages %} <li class="{{ category }}">{{ message }}</li> {% endfor %} </ul> {% endif %} {% endwith %} This is just one example of how to render these flashed messages. This is useful if you wish to render each category in a sepa- rate block.15. The loop looks slightly different in that situation then: {% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} <ul class=flashes> {% for category. To flash a message with a different category. 20.for msg in errors %} <li>{{ msg }}</li> {% endfor -%} </ul> </div> {% endif %} {% endwith %} 150 . For example error messages could be displayed with a red background. {% with errors = get_flashed_messages(category_filter=["error"]) %} {% if errors %} <div class="alert-message block-message error"> <a class="close" href="#">×</a> <ul> {%. The default cate- gory if nothing is provided is 'message'. 'error') Inside the template you then have to tell the get_flashed_messages() function to also return the categories.It is also possible to provide categories when flashing a message. One might also use the category to add a prefix such as <strong>Error:</strong> to the message. Alternative categories can be used to give the user better feedback.9. Optionally you can pass a list of categories which filters the results of get_flashed_messages().3 Filtering Flash Messages New in version 0. just use the second argument to the flash() function: flash(u'Invalid password provided'.

so how can we do that? A simple method would be to add a script tag to our page that sets a global variable to the prefix to the root of the application. filename='jquery.16.2 Where is My Site? Do you know where your application is? If you are developing the answer is quite simple: it’s on localhost port something and directly on the root of that server.1/jquery.com/myapp? On the server side this never was a problem because we were using the handy url_for() function that could answer that question for us.js') }}"></script> Another method is using Google’s AJAX Libraries API to load jQuery: <script src="//ajax.write('<script src="{{ url_for('static'. filename='jquery. </script> 151 .16 AJAX with jQuery jQuery is a small JavaScript library commonly used to simplify working with the DOM and JavaScript in general. But what if you later decide to move your application to a different location? For example to http://example.9. Something like this: <script type=text/javascript> $SCRIPT_ROOT = {{ request. you have to download it first and place it in the static folder of your application and then ensure it’s loaded. but if we are using jQuery we should not hardcode the path to the application but make that dynamic. 20.com/ajax/libs/jquery/1. very similar to how Python primi- tives (numbers. This has the advantage that your website will probably load faster for users if they went to at least one other website before using the same jQuery version from Google because it will already be in the browser cache.min. JSON itself is a very lightweight transport format. Ideally you have a layout template that is used for all pages where you just have to add a script statement to the bottom of your <body> to load jQuery: <script type=text/javascript src="{{ url_for('static'.script_root|tojson|safe }}. dicts and lists) look like which is widely supported and very easy to parse. strings.16.20. It is the perfect tool to make web applications more dynamic by exchanging JSON between server and client. It became popular a few years ago and quickly replaced XML as trans- port format in web applications. but it will first try to load it directly from Google.js"></script> <script>window. 20.googleapis.jQuery || document.js') }}">\x3C/script>')</script> In this case you have to put jQuery into your static folder as a fallback.1 Loading jQuery In order to use jQuery.

render_template.10 it goes a step further and escapes all HTML tags with unicode escapes. Information for Pros In HTML the script tag is declared CDATA which means that entities will not be parsed.The |safe is necessary in Flask before 0.args. This also means that there must never be any </ between the script tags. but a simple example that shows how you would use jQuery and Flask nonetheless: from flask import Flask.3 JSON View Functions Now let’s create a server side function that accepts two URL arguments of numbers which should be added together and then sent back to the application in a JSON object. type=int) b = request.get('b'. 0.10 so that Jinja does not escape the JSON encoded string with HTML rules. This tem- plate will load jQuery as above and have a little form we can add two numbers and a link to trigger the function on the server side. JavaScript etc. In Flask 0. If the key is missing a default value (here 0) is returned.route('/_add_numbers') def add_numbers(): a = request. Note that we are using the get() method here which will never fail. Furthermore it can convert values to a specific type (like in our case int). request app = Flask(__name__) @app. 20. Everything until </script> is handled as script.args.get('a'. 0. jsonify. 152 .) because you don’t need special error reporting in that case. type=int) return jsonify(result=a + b) @app.route('/') def index(): return render_template('index.html') As you can see I also added an index method here that renders a template. but we are inside a script block here where different rules apply. This is especially handy for code that is triggered by a script (APIs. Usually this would be necessary. |tojson is kind enough to do the right thing here and escape slashes for you ({{ "</script>"|tojson|safe }} is rendered as "<\/ script>").16. This is a really ridiculous example and is something you usually would do on the client side alone. This makes it possible for Flask to automatically mark the result as HTML safe.

or do that on the top. }).text(data. If that function returns false. just a very quick explanation of the little bit of code above: 1. navigate to the # URL). data. func) specifies a function that should run when the user clicked on the element. }) specifies code that should run once the browser is done loading the basic parts of the page.html). function() { $.html template either has to extend a layout. { a: $('input[name="a"]'). func) sends a GET request to url and will send the con- tents of the data object as query parameters.. 153 . Notice that we also drop the script directly into the HTML here. 3. it will call the given function with the return value as argument.result). It is usually a better idea to have that in a separate script file: <script type=text/javascript> $(function() { $('a#calculate'). </script> <h1>jQuery Example</h1> <p><input type=text size=5 name=a> + <input type=text size=5 name=b> = <span id=result>?</span> <p><a href=# id=calculate>calculate server side</a> I won’t go into detail here about how jQuery works. If you don’t get the whole picture. 4. }).16.val(). element. Note that we can use the $SCRIPT_ROOT variable here that we set earlier. Here’s the HTML code needed for our little application (index.. }).getJSON(url. 2.html template with jQuery loaded and the $SCRIPT_ROOT variable set.val() }. $(function() { .bind('event'.bind('click'. $('selector') selects an element and lets you operate on it. Once the data arrived.4 The HTML Your index. b: $('input[name="b"]'). $. return false.20. function(data) { $("#result"). the default behavior will not kick in (in this case.getJSON($SCRIPT_ROOT + '/_add_numbers'. download the sourcecode for this example from GitHub.

the thing I was looking for is not there. but in one case it can be a different error: a handler for internal server errors will be passed other exception instances as well if they are uncaught. so make sure to also provide the HTTP status code when returning a response. 20. at least a link back to the index. Flask will not trigger it if it’s running in Debug mode. 410 Gone Did you know that there the “404 Not Found” has a brother named “410 Gone”? Few people actually implement that. 20. If you are not deleting documents permanently from the database but just mark them as deleted. 500 Internal Server Error Usually happens on programming errors or if the server is overloaded. Keep in mind that Flask will not set the error code for you.1 Common Error Codes The following error codes are some that are often displayed to the user. Here an example implementation for a “404 Page Not Found” exception: 154 . So common that even novices to the internet know that 404 means: damn. Depending on the error code it is less or more likely for the user to actually see such an error.20.17 Custom Error Pages Flask comes with a handy abort() function that aborts a request with an HTTP error code early. It’s a very good idea to make sure there is actually something useful on a 404 page. but nothing fancy. The error is most likely a HTTPException. even if the application behaves correctly: 404 Not Found The good old “chap. because your application will fail sooner or later (see also: Application Errors). A terribly good idea is to have a nice page there. It will also provide a plain black and white error page for you with a basic description. So make sure the user is not lost when they try to access a forbidden resource.17. An error handler is registered with the errorhandler() decorator and the error code of the exception. you made a mistake typing that URL” message. you will have to send a 403 code for disallowed resources. do the user a favour and use the 410 code instead and display a message that what they were looking for was deleted for all eternity.17. just like a view function.2 Error Handlers An error handler is a function. 403 Forbidden If you have some kind of access control on your website. Please note that if you add an error handler for “500 Internal Server Error”. but the idea is that resources that previously existed and got deleted answer with 410 instead of 404. but it is called when an error happens and is passed that error.

It might have to do that on systems like Google’s App Engine or other systems.18. The system that enables having a central URL map is the add_url_rule() function. However there is a downside to this approach: it means all your code that uses decorators has to be imported upfront or Flask will never actually find your function. <p><a href="{{ url_for('index') }}">go somewhere nice</a> {% endblock %} 20.1 Converting to Centralized URL Map Imagine the current application looks somewhat like this: from flask import Flask app = Flask(__name__) @app.html" %} {% block title %}Page Not Found{% endblock %} {% block body %} <h1>Page Not Found</h1> <p>What you were looking for is just not there.route('/') def index(): pass @app.from flask import render_template @app.route('/user/<username>') def user(username): pass 155 .html').errorhandler(404) def page_not_found(e): return render_template('404. 404 An example template might be this: {% extends "layout. Decorators are simple and you have the URL right next to the function that is called for that specific URL. This can be a problem if your application has to import quick. you have a file that sets up the application with all URLs. So if you suddenly notice that your application outgrows this approach you can fall back to a centralized URL mapping.18 Lazily Loading Views Flask is usually used with the decorators. 20. Instead of using decorators.

**kwargs): return self.18.2 Loading Late So far we only split up the views and the routing.add_url_rule('/'.import_name = import_name @cached_property def view(self): return import_string(self.add_url_rule('/'. **kwargs) What’s important here is is that __module__ and __name__ are properly set.'.helpers import LazyView app = Flask(__name__) app.import_name) def __call__(self. Then you can define your central place to combine the views like this: from flask import Flask from yourapplication.__name__ = import_name.view(*args. view_func=LazyView('yourapplication. view_func=views. 1) self.add_url_rule('/user/<username>'. py) but without any decorator: def index(): pass def user(username): pass And then a file that sets up an application which maps the functions to URLs: from flask import Flask from yourapplication import views app = Flask(__name__) app. view_func=views.__module__.views. This can be accom- plished with a helper class that behaves just like a function but internally imports the real function on first use: from werkzeug import import_string. with the centralized approach you would have one file with the views (views.Then. but the module is still loaded up- front. The trick is to actually load the view function as needed. *args.user) 20. self.index')) 156 . cached_property class LazyView(object): def __init__(self. This is used by Flask internally to figure out how to name the URL rules in case you don’t provide a name for the rule yourself.index) app.rsplit('. import_name): self.

**options) # add a single route to the index view url('views. Here an example app. url_rules=[]. ['/']) # add two routes to a single function endpoint url_rules = ['/user/'. This pattern shows how to use MongoKit.add_url_rule(url_rule.user'.app.add_url_rule('/user/<username>'. Document # configuration MONGODB_HOST = 'localhost' MONGODB_PORT = 27017 # create the little application object 157 . a document mapper library.py module for your application: from flask import Flask from mongokit import Connection.user')) You can further optimize this in terms of amount of keystrokes needed to write this by having a function that calls into add_url_rule() by prefixing a string with the project name and a dot. This pattern requires a running MongoDB server and the MongoKit library installed.index'.1 Declarative The default behavior of MongoKit is the declarative one that is based on common ideas from Django or the SQLAlchemy declarative extension. **options): view = LazyView('yourapplication.19 MongoKit in Flask Using a document database rather than a full DBMS gets more common these days.' + import_name) for url_rule in url_rules: app. The same goes for any kind of remaining decorator. and by wrapping view_func in a LazyView as needed.views. 20. view_func=view. view_func=LazyView('yourapplication. def url(import_name. There are two very common ways to use MongoKit. to integrate with MongoDB. url_rules) One thing to keep in mind is that before and after request handlers have to be in a file that is imported upfront to work properly on the first request.19.'/user/<username>'] url('views. I will outline each of them here: 20.

MongoKit does not have something like a session. app.config.config['MONGODB_HOST']. If you’ve seen the SQLAlchemy pattern you may wonder why we do not have a session and even do not define a init_db function here. On the one hand. e. This sometimes makes it more to type but also makes it blazingly fast.g. On the other hand. Here is an example document (put this also into app.from_object(__name__) # connect to the database connection = Connection(app.name) # register the User document with our current connection connection.→format(length)) return validate class User(Document): structure = { 'name': unicode.app = Flask(__name__) app.): from mongokit import ValidationError def max_length(length): def validate(value): if len(value) <= length: return True # must have %s in error format string to have mongokit place key in there raise ValidationError('%s must be at most {} characters long'. MongoKit is just schemaless too. } validators = { 'name': max_length(50). MongoDB is schemaless. This means you can modify the data structure from one insert query to the next without any prob- lem. 158 . just subclass the Document class that is imported from Mon- goKit. .register([User]) This example shows you how to define your schema (named structure). Per default MongoKit behaves like a python dictionary but with use_dot_notation set to True you can use your documents like you use models in nearly any other ORM by using dots to separate between attributes.config['MONGODB_PORT']) To define your models. 'email': max_length(120) } use_dot_notation = True def __repr__(self): return '<User %r>' % (self.py. a valida- tor for the maximum character length and uses a special MongoKit feature called use_dot_notation. but implements some validation to ensure data integrity. 'email': unicode.

You may use this process if you need the best performance to get.User. you must not use a com- mon str type for either name or email but unicode.User.find_one({'name': u'admin'}) {u'_id': ObjectId('4c271729e13823182f000000'). To query your database.users >>> user = collection.users >>> user = {'name': u'admin'.find()) [<User u'admin'>] >>> collection.models import User >>> collection = connection['test']. u'name': u'admin'. >>> collection = connection['test'].19.find()) [{u'_id': ObjectId('4c271729e13823182f000000').→'admin@localhost'}] >>> collection.find_one({'name': u'admin'}) <User u'admin'> 20.You can insert entries into the database like this: >>> from yourapplication. Note that this example does not show how to couple it with Flask. u'name': u'admin'. We have to get a collection first.→'admin@localhost'} These results are also dict-like objects: 159 . see the above MongoKit code for examples: from MongoKit import Connection connection = Connection() To insert data you can use the insert method. you can do that with MongoKit as well. u'email': u .User() >>> user['name'] = u'admin' >>> user['email'] = u'admin@localhost' >>> user.save() Note that MongoKit is kinda strict with used column types. Querying is simple as well: >>> list(collection.insert(user) MongoKit will automatically commit for us. you use the collection directly: >>> list(collection.database import connection >>> from yourapplication. this is somewhat the same as a table in the SQL world. 'email': u'admin@localhost'} >>> collection.2 PyMongo Compatibility Layer If you just want to use PyMongo. u'email': u .

ico'. So. The old de-facto standard is to serve this file.ico. you need an icon. If your application is not mounted at the root path of the domain you either need to configure the web server to serve the icon at the root or if you can’t do that you’re out of luck.root_path. 20. refer to the web server’s documentation.ico'. at the website root.>>> r = collection.icon') We can leave out the explicit mimetype and it will be guessed. First. however some really old ones do not support this standard. mimetype='image/vnd. with this name. 160 . Now. A common question is how to add a favicon to a Flask application.20 Adding a favicon A “favicon” is an icon used by browsers for tabs and bookmarks. of course.add_url_rule('/favicon.find_one({'name': u'admin'}) >>> r['email'] u'admin@localhost' For more information about MongoKit. but we may as well specify it to avoid the extra guessing. Put the icon in your static directory as favicon. The above will serve the icon via your application and if possible it’s better to config- ure your dedicated web server to serve it. the correct way is to add a link tag in your HTML. This helps to distin- guish your website and to give it a unique brand.join(app. This is not a requirement but a de-facto standard supported by all relevant browsers. as it will always be the same. head over to the website.microsoft. 'static').ico') def favicon(): return send_from_directory(os. 'favicon. filename='favicon. It should be 16 × 16 pixels and in the ICO file format.ico')) If you want to save the extra redirect request you can also write a view using send_from_directory(): import os from flask import send_from_directory @app. filename='favicon. to get browsers to find your icon. redirect_to=url_for('static'. If however your application is the root you can simply route a redirect: app. for example: <link rel="shortcut icon" href="{{ url_for('static'.path.route('/favicon.ico') }}"> That’s all you need for most browsers.

so be careful there in debug environments with profilers and other things you might have enabled.21 Streaming Contents Sometimes you want to send an enormous amount of data to the client.1 See also • The Favicon article on Wikipedia 20.route('/large. but you can easily do it yourself: from flask import Response def stream_template(template_name.1 Basic Usage This is a basic view function that generates a lot of CSV data on the fly. much more than you want to keep in memory. 20. The trick is to have an inner function that uses a generator to generate data and to then invoke that function and pass it to a response object: from flask import Response @app.update_template_context(context) t = app. **context): app.'.get_template(template_name) rv = t. mimetype='text/csv') Each yield expression is directly sent to the browser.jinja_env.join(row) + '\n' return Response(generate().enable_buffering(5) return rv 161 . This functionality is not directly exposed by Flask because it is quite uncommon.20. When you are generating the data on the fly though.20.21. 20.2 Streaming from Templates The Jinja2 template engine also supports rendering templates piece by piece.21.stream(context) rv. how do you send that back to the client without the roundtrip to the filesystem? The answer is by using generators and direct responses. Note though that some WSGI middlewares might break streaming.csv') def generate_large_csv(): def generate(): for row in iter_all_rows(): yield '.

It is created as necessary either by a view function or by some other component in the system.22 Deferred Request Callbacks One of the design principles of Flask is that response objects are created and passed down a chain of potential callbacks that can modify them or replace them. Response @app. request. Since we’re bypassing the Flask template render functions and using the template object itself we have to make sure to update the render context ourselves by calling update_template_context(). 5 is a sane default. the request context is already gone the moment the function executes. The template is then evaluated as the stream is iterated over. Sometimes however moving 162 . 20. Since each time you do a yield the server will flush the content to the client you might want to buffer up a few items in the template which you can do with rv.@app. When the request handling starts. rows=rows)) The trick here is to get the template object from the Jinja2 environment on the appli- cation and to call stream() instead of render() which returns a stream object instead of a string.21. Note that when you stream data. Very often that is possible.9.route('/my-large-page. 20. there is no response object yet.html'.3 Streaming with Context New in version 0. For instance you can try to move that logic into an after-request callback instead.route('/stream') def streamed_response(): def generate(): yield 'Hello ' yield request.enable_buffering(size). Flask 0.9 provides you with a helper that can keep the request context around during the execution of the generator: from flask import stream_with_context. One way is to avoid the situation.html') def render_large_template(): rows = iter_all_rows() return Response(stream_template('the_template.args['name'] yield '!' return Response(stream_with_context(generate())) Without the stream_with_context() function you would get a RuntimeError at that point. But what happens if you want to modify the response at a point where the response does not exist yet? A common example for that would be a before-request function that wants to set a cookie on the response object.

For this the following function needs to be registered as after_request() callback: @app. But we still need to call them.22.get('user_lang') if language is None: language = guess_language_from_request() @after_this_request def remember_language(response): 163 .after_request def call_after_request_callbacks(response): for callback in getattr(g.that code there is just not a very pleasant experience or makes code look very awk- ward.1 The Decorator The following decorator is the key.cookies.3 A Practical Example At any time during a request. For example you can remember the current language of the user in a cookie in the before-request function: from flask import request @app. 'after_request_callbacks'.after_request_callbacks = [] g. As an alternative possibility you can attach a bunch of callback functions to the g object and call them at the end of the request. It registers a function on a list on the g object: from flask import g def after_this_request(f): if not hasattr(g.2 Calling the Deferred Now you can use the after_this_request decorator to mark a function to be called at the end of the request. ()): callback(response) return response 20. 20.22. we can register a function to be called at the end of the request.append(f) return f 20. This way you can defer code execution from anywhere in the application.before_request def detect_user_language(): language = request.after_request_callbacks.22. 'after_request_callbacks'): g.

23 Adding HTTP Method Overrides Some HTTP proxies do not support arbitrary HTTP methods or newer HTTP methods (such as PATCH). 'PUT'. language) g. 'replace') environ['REQUEST_METHOD'] = method if method in self. This can easily be accomplished with an HTTP middleware: class HTTPMethodOverrideMiddleware(object): allowed_methods = frozenset([ 'GET'. 'HEAD'. start_response) To use this with Flask this is all that is necessary: from flask import Flask app = Flask(__name__) app.bodyless_methods: environ['CONTENT_LENGTH'] = '0' return self. 'OPTIONS'. 'DELETE'. The way this works is by letting the client do an HTTP POST request and set the X-HTTP-Method-Override header and set the value to the intended HTTP method (such as PATCH). environ. 'OPTIONS' ]) bodyless_methods = frozenset(['GET'.encode('ascii'.app(environ.allowed_methods: method = method.language = language 20. 'POST'. 'HEAD'. response. In that case it’s possible to “proxy” HTTP methods through another HTTP method in total violation of the protocol.upper() if method in self. ''). 'DELETE']) def __init__(self.wsgi_app = HTTPMethodOverrideMiddleware(app. app): self.get('HTTP_X_HTTP_METHOD_OVERRIDE'. start_response): method = environ.app = app def __call__(self.wsgi_app) 164 .set_cookie('user_lang'. 'PATCH'.

Fortunately this is however very simple to change by wrapping the input stream.form or anything of that nature._hash To use this._hash.route('/special-api'.files # At this point the hash is fully constructed. This seems inconvenient when you want to calculate the checksum of the incoming request data.sha1() def read(self.input'] = stream return stream._hash.update(rv) return rv def readline(self.readline(size_hint) self.24 Request Content Checksums Various pieces of code can consume the request data and preprocess it. all you need to do is to hook the calculating stream in before the request starts consuming data._stream._stream = stream self.environ stream = ChecksumCalcStream(env['wsgi. For instance JSON data ends up on the request object already read and processed. form data ends up there as well but goes through a different code path. The following example calculates the SHA1 checksum of the incoming data as it gets read and stores it in the WSGI environment: import hashlib class ChecksumCalcStream(object): def __init__(self. This is necessary sometimes for some APIs.hexdigest() return 'Hash was: %s' % checksum 165 . Example usage: @app._stream.input']) env['wsgi. (Eg: be careful accessing request. methods=['POST']) def special_api(): hash = generate_checksum(request) # Accessing this parses the input stream files = request. size_hint): rv = self._hash = hashlib.read(bytes) self. before_request_handlers for instance should be careful not to access it).update(rv) return rv def generate_checksum(request): env = request. stream): self. checksum = hash. bytes): rv = self.20.

Task class ContextTask(TaskBase): abstract = True def __call__(self.25 Celery Based Background Tasks Celery is a task queue for Python with batteries included. it becomes a bit nicer by subclassing tasks and adding support for Flask’s application contexts and hooking it up with the Flask configura- tion. configures it with the broker from the ap- plication config. backend=app.Task = ContextTask return celery The function creates a new Celery object. this is called the celery application. like creating tasks and managing workers.1 Installing Celery Celery is on the Python Package Index (PyPI). just for Celery.2 Configuring Celery The first thing you need is a Celery instance. This guide fills in the blanks in how to properly use Celery with Flask but assumes that you generally already read the First Steps with Celery guide in the official Celery documentation. It serves the same purpose as the Flask object in Flask. 166 . **kwargs) celery.import_name.app_context(): return TaskBase.25. For instance you can place this in a tasks module.update(app. updates the rest of the Celery config from the Flask config and then creates a subclass of the task that wraps the task execution in an application context. *args.__call__(self.config) TaskBase = celery.config['CELERY_RESULT_BACKEND']. it must be possible for other modules to import it. It used to have a Flask inte- gration but it became unnecessary after some restructuring of the internals of Celery with Version 3. so it can be installed with standard Python tools like pip or easy_install: $ pip install celery 20.25. 20. broker=app.20. While you can use Celery without any reconfiguration with Flask.config['CELERY_BROKER_URL']) celery.conf. **kwargs): with app. Since this instance is used as the entry-point for everything you want to do in Celery. *args. This is all that is necessary to properly integrate Celery with Flask: from celery import Celery def make_celery(app): celery = Celery(app.

3 Minimal Example With what we have above this is the minimal example of using Celery with Flask: from flask import Flask flask_app = Flask(__name__) flask_app.datastructures import ImmutableOrderedMultiDict class MyRequest(Request): """Request subclass to override request parameter storage""" parameter_storage_class = ImmutableOrderedMultiDict class MyFlask(Flask): 167 . That’s because you also need to run celery.task() def add_together(a. 20.25.wait() will never actually return.delay(23. For example.4 Running the Celery Worker Now if you jumped in and already executed the above code you will be disappointed to learn that your . CELERY_RESULT_BACKEND='redis://localhost:6379' ) celery = make_celery(flask_app) @celery. 42) >>> result. you may want to override how request parameters are handled to pre- serve their order: from flask import Flask. Request from werkzeug. b): return a + b This task can now be called in the background: >>> result = add_together.25. You can do that by running celery as a worker: $ celery -A your_application.26 Subclassing Flask The Flask class is designed for subclassing.wait() 65 20.20.celery worker The your_application string has to point to your application’s package or module that creates the celery object.update( CELERY_BROKER_URL='redis://localhost:6379'.config.

"""Flask subclass using the custom request class""" request_class = MyRequest This is the recommended approach for overriding or augmenting Flask’s internal func- tionality. 168 .

2. Just remember that your Flask application object is the actual WSGI application. 21. If you want to deploy your Flask application to a WSGI server not listed here.1 mod_wsgi (Apache) If you are using the Apache webserver.1 Hosted options • Deploying Flask on Heroku • Deploying Flask on OpenShift • Deploying Flask on Webfaction • Deploying Flask on Google App Engine • Deploying Flask on AWS Elastic Beanstalk • Sharing your Localhost Server with Localtunnel • Deploying on Azure (IIS) • Deploying on PythonAnywhere 21. Some of the options available for properly running Flask in production are documented here. CHAPTER TWENTYONE DEPLOYMENT OPTIONS While lightweight and easy to use. 169 . consider using mod_wsgi. look up the server documentation about how to use a WSGI app with it.run() calls you might have in your applica- tion file are inside an if __name__ == '__main__': block or moved to a separate file.2 Self-hosted options 21. Flask’s built-in server is not suitable for produc- tion as it doesn’t scale well and by default serves only one request at a time. Watch Out Please make sure in advance that any app.

Alternatively there is the option to just patch the path in the . The mod_wsgi installation instructions cover source installations on UNIX systems. If you are using Ubuntu/Debian you can apt-get it and activate it as follows: # apt-get install libapache2-mod-wsgi If you are using a yum based distribution (Fedora.wsgi file. If you encounter segfaulting child processes after the first apache reload you can safely ignore them.Just make sure it’s not called because this will always start a local WSGI server which we do not want if we deploy that application to mod_wsgi. Store that file somewhere that you will find it again (e. This file contains the code mod_wsgi is executing on startup to get the application object. etc. For most applications the following file should be sufficient: from yourapplication import app as application If you don’t have a factory function for application creation but a singleton instance you can directly import that one as application. Installing mod_wsgi If you don’t have mod_wsgi installed yet you have to either install it using a package manager or compile it yourself. OpenSUSE.) you can install it as follows: # yum install mod_wsgi On FreeBSD install mod_wsgi by compiling the www/mod_wsgi port or by using pkg_add: # pkg install ap22-mod_wsgi2 If you are using pkgsrc you can install mod_wsgi by compiling the www/ap2-wsgi pack- age.g.wsgi file To run your application you need a yourapplication. Just restart the server. If you don’t want to install it system wide consider using a virtual python instance.: /var/www/yourapplication) and make sure that yourapplication and all the libraries that are in use are on the python load path. Creating a .. The object called application in that file is then used as application.wsgi file before the import: 170 . Keep in mind that you will have to actually install your application into the virtualenv as well.

insert(0.allow Allow from all </Directory> </VirtualHost> Note: WSGIDaemonProcess isn’t implemented in Windows and Apache will refuse to run with the above configuration.import sys sys.wsgi <Directory C:\yourdir> Order deny.path.wsgi <Directory /var/www/yourapplication> WSGIProcessGroup yourapplication WSGIApplicationGroup %{GLOBAL} Order deny. the syntax for directory permissions has changed from httpd 2. eliminate those lines: <VirtualHost *> ServerName example. '/path/to/the/application') Configuring Apache The last thing you have to do is to create an Apache configuration file for your ap- plication. 171 . Most notably.4 syntax Require all granted For more information consult the mod_wsgi documentation.2 Order allow.deny Allow from all to httpd 2. On a Windows system.com WSGIScriptAlias / C:\yourdir\yourapp. In this example we are telling mod_wsgi to execute the application under a different user for security reasons: <VirtualHost *> ServerName example.4.com WSGIDaemonProcess yourapplication user=user1 group=group1 threads=5 WSGIScriptAlias / /var/www/yourapplication/yourapplication.allow Allow from all </Directory> </VirtualHost> Note: There have been some changes in access control configuration for Apache 2.

Either remove that run() call from the file and move it into a separate run. mod_wsgi will reload all the daemon processes for us. 172 .stdout = sys. just add the following directive to your Directory section: WSGIScriptReloading On Working with Virtual Environments Virtual environments have the advantage that they never install the required depen- dencies system wide so you have a better control over what is used where.py file or put it into such an if block. The reason for this is that for non-installed packages.wsgi file. Make sure the folders the application needs access to have the proper privileges set and the application runs as the correct user (user and group parameter to the WSGIDaemonProcess directive) Problem: application dies with an error on print Keep in mind that mod_wsgi dis- allows doing anything with sys. You can disable this protection from the config by setting the WSGIRestrictStdout to off: WSGIRestrictStdout Off Alternatively you can also replace the standard out in the . If you want to use a virtual environment with mod_wsgi you have to modify your . or convert your application into a package. Problem: application gives permission errors Probably caused by your application running as the wrong user.stdout and sys. the module filename is used to locate the resources and for symlinks the wrong filename is picked up.wsgi file with a differ- ent stream: import sys sys. Please be aware that this does not work.stderr.wsgi file slightly.Troubleshooting If your application does not run. For that. Support for Automatic Reloading To help deployment tools you can activate support for automatic reloading.stderr Problem: accessing resources gives IO errors Your application probably is a single .run() call in your application file that is not guarded by an if __name__ == '__main__': condition. errorlog shows SystemExit ignored You have an app. instead you either have to put the folder into the pythonpath the file is stored in. follow this guide to troubleshoot: Problem: application does not run. Whenever something changes the .py file you symlinked into the site-packages folder.

py' with open(activate_this) as file_: exec(file_. you can proxy to them from your web server. Running a Flask application on this server is quite simple: gunicorn myproject:app Gunicorn provides many command-line options – see gunicorn -h. Keep in mind that the path has to be absolute. These servers stand alone when they run. It’s a pre-fork worker model ported from Ruby’s Unicorn project.py' execfile(activate_this.0.0. Note the section on Proxy Setups if you run into issues. to run a Flask application with 4 worker processes (-w 4) binding to localhost port 4000 (-b 127.0. dict(__file__=activate_this)) For Python 3 add the following lines to the top of your .2.wsgi file: activate_this = '/path/to/env/bin/activate_this.wsgi file: activate_this = '/path/to/env/bin/activate_this.read().0.1:4000): gunicorn -w 4 -b 127.serve_forever() 173 . 21. For example. Gunicorn Gunicorn ‘Green Unicorn’ is a WSGI HTTP Server for UNIX. app) http_server. dict(__file__=activate_this)) This sets up the load paths according to the settings of the virtual environment.1:4000 myproject:app Gevent Gevent is a coroutine-based Python networking library that uses greenlet to provide a high-level synchronous API on top of libev event loop: from gevent.Add the following lines to the top of your . It supports both eventlet and greenlet.2 Standalone WSGI Containers There are popular servers written in Python that contain WSGI applications and serve HTTP.wsgi import WSGIServer from yourapplication import app http_server = WSGIServer((''. 5000).

see twistd -h and twistd web -h for more information.log. Twisted Web comes with a standard WSGI container which can be controlled from the command line using the twistd utility: twistd web --wsgi myproject. proxy_set_header X-Real-IP $remote_addr. setting appropriate headers: server { listen 80.log.Twisted Web Twisted Web is the web server shipped with Twisted. Twisted Web supports many flags and options. on port 8080. access_log /var/log/nginx/access. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for.0. The two prob- lematic values in the WSGI environment usually are REMOTE_ADDR and HTTP_HOST. proxy_redirect off. Here’s a simple nginx configuration which proxies to an application served on local- host at port 8000. and the twistd utility does as well. proxy_set_header X-Forwarded-Proto $scheme. non-blocking event- driven networking library. a mature. the most common setup invokes the host being set from X-Forwarded-Host and the remote address from X-Forwarded-For: 174 . error_log /var/log/nginx/error. You can configure your httpd to pass these headers. location / { proxy_pass http://127.app This example will run a Flask application called app from a module named myproject. with an application from myproject: twistd -n web --port 8080 --wsgi myproject. For example. proxy_set_header Host $host. or you can fix them in middleware. } } If your httpd is not providing these headers.app Proxy Setups If you deploy your application using one of these servers behind an HTTP proxy you will need to rewrite a few headers in order for the application to work. Werkzeug ships a fixer that will solve some common setups. server_name _.1:8000/. to run a Twisted Web server in the foreground.0. but you might want to write your own WSGI middleware for specific setups.

Make sure to have it installed to follow along.2. If you want to rewrite the headers from another header.from werkzeug. environ. FastCGI. Just make sure it’s not called because this will always start a local WSGI server which we do not want if we deploy that application to uWSGI.fixers import ProxyFix app. and HTTP protocols.contrib.app(environ. see FastCGI and Standalone WSGI Containers for other options.3 uWSGI uWSGI is a deployment option on servers like nginx. start_response) app.wsgi_app) Trusting Headers Please keep in mind that it is a security issue to use such a middleware in a non-proxy setup because it will blindly trust the incoming headers which might be forged by malicious clients. Watch Out Please make sure in advance that any app.get('HTTP_X_FHOST'. start_response): host = environ. To use your WSGI appli- cation with uWSGI protocol you will need a uWSGI server first. The most popular uWSGI server is uwsgi.wsgi_app) 21.wsgi_app = ProxyFix(app. and cherokee.wsgi_app = CustomProxyFix(app.app = app def __call__(self. 175 . lighttpd. which we will use for this guide. app): self. you might want to use a fixer like this: class CustomProxyFix(object): def __init__(self. uWSGI is both a protocol and an application server.run() calls you might have in your applica- tion file are inside an if __name__ == '__main__': block or moved to a separate file. the application server can serve uWSGI. '') if host: environ['HTTP_HOST'] = host return self.

py.sock --manage-script-name --mount / . The most popular one is flup which we will use for this guide. Given a flask application in myapp.Starting your app with uwsgi uwsgi is designed to operate on WSGI callables found in python modules. uwsgi_pass unix:/tmp/yourapplication. Configuring nginx A basic flask nginx configuration looks like this: location = /yourapplication { rewrite ^ /yourapplication/. } location @yourapplication { include uwsgi_params. } location @yourapplication { include uwsgi_params.sock.2. Make sure to have it installed to follow along. app is the callable inside of your application (usually the line reads app = Flask(__name__). If you want to deploy your flask application inside of a virtual environment. use the following command: $ uwsgi -s /tmp/yourapplication. and cherokee. If your application is accessi- ble at root level. myapp refers to the name of the file of your flask application (without extension) or the module which provides app. If you want to have it in the URL root its a bit simpler: location / { try_files $uri @yourapplication. It is used together with the --mount directive which will make requests to /yourapplication be directed to myapp:app.sock. } 21. You might also need to add --plugin python or --plugin python3 depending on which python version you use for your project. 176 . To use your WSGI applica- tion with any of them you will need a FastCGI server first. since its smarter about that. uwsgi_pass unix:/tmp/yourapplication. } location /yourapplication { try_files $uri @yourapplication. lighttpd. you can use a single / instead of /yourapplication. you need to also add --virtualenv /path/to/virtual/environment. see uWSGI and Standalone WSGI Containers for other options. } This configuration binds the application to /yourapplication.4 FastCGI FastCGI is a deployment option on servers like nginx.→yourapplication=myapp:app The --manage-script-name will move the handling of SCRIPT_NAME to uwsgi.

bindAddress='/path/to/fcgi.fcgi does not appear in the URL.fcgi Configuring Apache The example above is good enough for a basic Apache deployment but your . Save the yourapplication.run() This is enough for Apache to work.so FastCgiServer /var/www/html/yourapplication/app. For that to work you need to pass the path to the socket to the WSGIServer: WSGIServer(application.fcgi/news/.sock').run() The path has to be the exact same path you define in the server config. example. Make sure to set the executable bit on that file so that the servers can execute it: # chmod +x /var/www/yourapplication/yourapplication.g. It makes sense to have that in /var/www/yourapplication or something similar. Just make sure it’s not called because this will always start a local WSGI server which we do not want if we deploy that application to FastCGI. however nginx and older versions of lighttpd need a socket to be explicitly passed to communicate with the FastCGI server. Let’s call it yourapplication.fcgi file will appear in your application URL e. The following example uses FastCgiServer to start 5 instances of the application which will handle all incoming requests: LoadModule fastcgi_module /usr/lib64/httpd/modules/mod_fastcgi.run() calls you might have in your applica- tion file are inside an if __name__ == '__main__': block or moved to a separate file.com/yourapplication.fcgi file First you need to create the FastCGI server file.fcgi import WSGIServer from yourapplication import app if __name__ == '__main__': WSGIServer(app).fcgi: #!/usr/bin/python from flup.fcgi file somewhere you will find it again.server. There are few ways to configure your application so that yourapplication.fcgi -idle-timeout 300 -processes 5 177 . Creating a . A preferable way is to use the ScriptAlias and SetHandler config- uration directives to route requests to the FastCGI server.Watch Out Please make sure in advance that any app.

0.fcgi)> SetHandler fcgid-script Options +FollowSymLinks +ExecCGI </Files> </IfModule> <IfModule mod_rewrite. If you’re using a standalone FastCGI server.fcgi/$1 [QSA.*)$ yourapplication. Note that in the fol- lowing the path is not real.1:3000 If you cannot set ScriptAlias.server.mydomain. '<your_local_path>/lib/python2.c> AddHandler fcgid-script . it’s simply used as an identifier to other directives such as AliasMatch: FastCgiServer /var/www/html/yourapplication -host 127.6/site-packages') from flup.com DocumentRoot /var/www/html/yourapplication AddHandler fastcgi-script fcgi ScriptAlias / /var/www/html/yourapplication/app.L] </IfModule> Set yourapplication.fcgi import WSGIServer from yourapplication import app class ScriptNameStripper(object): def __init__(self.fcgi: #!/usr/bin/python #: optional path to your local python site-packages folder import sys sys. you can use the FastCgiExternalServer directive instead. you can use WSGI middleware to remove yourapplication.fcgi/ <Location /> SetHandler fastcgi-script </Location> </VirtualHost> These processes will be managed by Apache.path.htaccess: <IfModule mod_fcgid.c> Options +FollowSymlinks RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(. for example on a shared web host.fcgi <Files ~ (\. Set . app): 178 .<VirtualHost *> ServerName webapp1.0.insert(0.fcgi from the URLs.

start_response): environ['SCRIPT_NAME'] = '' return self.rewrite-once = ( "^(/static($|/.server = ("/yourapplication.sock". If you want the application to work in the URL root you have to work around a lighttpd bug with the LighttpdCGIRootFix middle- ware.fcgi$1" ) Remember to enable the FastCGI. A basic Flask FastCGI configuration for nginx looks like this: 179 . environ. see the Lighty docs for more information on FastCGI and Python (note that explicitly passing a socket to run() is no longer necessary). alias and rewrite modules. "max-procs" => 1 )) ) alias. Configuring nginx Installing FastCGI applications on nginx is a bit different because by default no FastCGI parameters are forwarded. "^(/.run() Configuring lighttpd A basic FastCGI configuration for lighttpd looks like that: fastcgi. self.fcgi". "check-local" => "disable".app = app def __call__(self.url = ( "/static/" => "/path/to/your/static" ) url.fcgi" => (( "socket" => "/tmp/yourapplication-fcgi.*))$" => "$1".app(environ.*)$" => "/yourapplication. start_response) app = ScriptNameStripper(app) if __name__ == '__main__': WSGIServer(app). Make sure to apply it only if you are mounting the application the URL root. "bin-path" => "/var/www/yourapplication/yourapplication. This configuration binds the application to /yourapplication. Also.

} location /yourapplication { try_files $uri @yourapplication. Super- visor can manage FastCGI processes.fcgi script inside GNU screen. For a temporary solution. You can look around for other FastCGI process managers or write a script to run your . Very often the only thing the server log tells you is something along the lines of “premature end of headers”.g. } This configuration binds the application to /yourapplication.sock. This example assumes your application is called application. } Running FastCGI Processes Since nginx and others do not load FastCGI apps. and note that this is a manual solution which does not persist across system restart: $ screen $ /var/www/yourapplication/yourapplication.fcgi and that your web server user is www-data: $ su www-data $ cd /var/www/yourapplication 180 .sock. If you want to have it in the URL root it’s a bit simpler because you don’t have to figure out how to calculate PATH_INFO and SCRIPT_NAME: location / { try_files $uri @yourapplication. you can always run the .d script. } location @yourapplication { include fastcgi_params. } location @yourapplication { include fastcgi_params. using a SysV init. fastcgi_param SCRIPT_NAME $fastcgi_script_name. fastcgi_split_path_info ^(/yourapplication)(. fastcgi_param PATH_INFO $fastcgi_path_info. In order to debug the application the only thing that can really give you ideas why it breaks is switching to the correct user and executing the application by hand. fastcgi_pass unix:/tmp/yourapplication-fcgi. you have to do it by yourself.fcgi file at boot.*)$. See man screen for details.fcgi Debugging FastCGI deployments tend to be hard to debug on most web servers. fastcgi_pass unix:/tmp/yourapplication-fcgi. e. fastcgi_param PATH_INFO $fastcgi_script_name.location = /yourapplication { rewrite ^ /yourapplication/ last. fastcgi_param SCRIPT_NAME "".

line 4. This is also the way you can use a Flask application on Google’s App Engine. you will also have to make sure that your code does not contain any print statements. Don’t rely on the current working directory.handlers import CGIHandler from yourapplication import app CGIHandler(). CGI will work for sure. Just make sure it’s not called because this will always start a local WSGI server which we do not want if we deploy that application to CGI / app engine. Watch Out Please make sure in advance that any app. in <module> ImportError: No module named yourapplication In this case the error seems to be “yourapplication” not being on the python path.fcgi Traceback (most recent call last): File "yourapplication.$ python application.5 CGI If all other deployment methods do not work.stdout is overridden by something that doesn’t write into the HTTP response.cgi: #!/usr/bin/python from wsgiref. where execution happens in a CGI-like environment.run(app) Server Setup Usually there are two ways to configure the server. • The code depending on environment variables that are not set by the web server. or that sys. 21. • Different python interpreters being used. Let’s call it yourapplication.2.cgi into a cgi-bin (and use mod_rewrite or something similar to rewrite the URL) or let the 181 . Either just copy the .cgi file First you need to create the CGI application file. CGI is sup- ported by all major servers but usually has a sub-optimal performance.run() calls you might have in your applica- tion file are inside an if __name__ == '__main__': block or moved to a separate file.fcgi". With CGI. Creating a . Common problems are: • Relative paths being used.

works too but the ScriptAlias directive won’t work in that case: RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f # Don't interfere with static files RewriteRule ^(.server point to the file directly. though.htaccess.*)$ /path/to/the/application. you might not have access to your Apache config.cgi/$1 [L] For more information consult the documentation of your webserver. In this case. 182 . In Apache for example you can put something like this into the config: ScriptAlias /app /path/to/the/application.cgi On shared webhosting. a file called . sitting in the public directory you want your app to be available.

1 Read the Source. hook points. See Subclassing Flask for an example.3 Subclass. This works well with Applica- tion Factories. don’t just use Flask – understand it. Flask’s code is written to be read. CHAPTER TWENTYTWO BECOMING BIG Here are your options when growing your codebase or scaling your application. The API docs are full of available overrides. Flask started in part to demonstrate how to build your own framework on top of existing well-used tools Werkzeug (WSGI) and Jinja (templating). Explore the many extensions in the community. You can quickly add or customize behavior by subclassing Flask (see the linked method docs) and using that subclass wherever you instantiate an application class. Look for ways in which your project can be refactored into a collection of utilities and Flask extensions. and look for patterns to build your own extensions if you do not find the tools you need. 22. The Flask class has many methods designed for subclassing. 183 . and documents its internal utilities so that you can find the hook points needed for your project. its documentation is published so you can use its internal APIs. and look for the customizations which are available out of the box in a Flask release. You can provide custom classes for things like the request and response objects. Dig deeper on the APIs you use. Read the source. Extend. Flask sticks to documented APIs in upstream libraries. and Signals. 22. it became useful to a wide audience. and as it developed. 22.2 Hook. As you grow your codebase.

You can introduce WSGI middleware to wrap your Flask instances and introduce fixes and changes at the layer between your Flask application and your HTTP server. If your server uses some kind of concurrency that is not based on threads or greenlets. Many people use patched and modified versions of their framework to counter shortcomings. process or greenlet. the data store you want to use and the Python implementation and webserver you are running on. 22. This is natural because if this would not be the case. Flask is just the paste that glues those together. These libraries do the majority of the work. fork Flask. However the majority of servers are using either threads. The downside of forking is of course that Flask extensions will most likely break be- cause the new framework has a different import name. This idea is also reflected in the license of Flask. Scaling well means for example that if you double the amount of servers you get about twice the performance.4 Wrap with middleware. The Application Dispatching chapter shows in detail how to apply middleware. forking should be the very last resort.5 Fork. greenlets or separate pro- cesses to achieve concurrency which are all methods well supported by the underlying Werkzeug library. Scaling bad means that if you add a new server the application won’t perform any better or would not even support a second server. depending on the number of changes. Be- cause of that. This is not unique to Flask. The majority of code of Flask is within Werkzeug and Jinja2. For many web applications the complexity of the code is less an issue than the scaling for the number of users or data entries expected. Furthermore integrating up- stream changes can be a complex process.6 Scale like a pro. You don’t have to contribute any changes back if you decide to modify the framework. 22. Flask will no longer be able to support these global proxies. If none of the above options work. the framework would be a very complex system to begin with which causes a steep learning curve and a lot of user frustration. 184 . Flask by itself is only limited in terms of scaling by your application code. They depend on context which in Flask is defined as being either a thread.22. Werkzeug includes several middlewares. There is only one limiting factor regarding scaling in Flask which are the context local proxies. For every project there is the point where the underlying framework gets in the way (due to assumptions the original developers had).

185 . If you find an obstacle in your way. The best way for the Flask and Flask extension developers to improve the tools for larger applications is getting feedback from users.22.7 Discuss with the community. don’t hesitate to contact the developers on the mailinglist or IRC channel. The Flask developers keep the framework accessible to users with codebases big and small. caused by Flask.

186 .

Part II
API REFERENCE

If you are looking for information on a specific function, class or method, this part of
the documentation is for you.

187

188

CHAPTER

TWENTYTHREE

API

This part of the documentation covers all the interfaces of Flask. For parts where Flask
depends on external libraries, we document the most important right here and provide
links to the canonical documentation.

23.1 Application Object

class flask.Flask(import_name, static_path=None, static_url_path=None,
static_folder=’static’, template_folder=’templates’, in-
stance_path=None, instance_relative_config=False,
root_path=None)
The flask object implements a WSGI application and acts as the central object.
It is passed the name of the module or package of the application. Once it is
created it will act as a central registry for the view functions, the URL rules,
template configuration and much more.
The name of the package is used to resolve resources from inside the package
or the folder the module is contained in depending on if the package parameter
resolves to an actual python package (a folder with an __init__.py file inside)
or a standard module (just a .py file).
For more information about resource loading, see open_resource().
Usually you create a Flask instance in your main module or in the __init__.py
file of your package like this:

from flask import Flask
app = Flask(__name__)

About the First Parameter
The idea of the first parameter is to give Flask an idea of what belongs to your
application. This name is used to find resources on the filesystem, can be used
by extensions to improve debugging information and a lot more.
So it’s important what you provide there. If you are using a single module,
__name__ is always the correct value. If you however are using a package, it’s

189

usually recommended to hardcode the name of your package there.
For example if your application is defined in yourapplication/app.py you
should create it with one of the two versions below:

app = Flask('yourapplication')
app = Flask(__name__.split('.')[0])

Why is that? The application will work even with __name__, thanks to how re-
sources are looked up. However it will make debugging more painful. Certain
extensions can make assumptions based on the import name of your application.
For example the Flask-SQLAlchemy extension will look for the code in your ap-
plication that triggered an SQL query in debug mode. If the import name is not
properly set up, that debugging information is lost. (For example it would only
pick up SQL queries in yourapplication.app and not yourapplication.views.frontend)

New in version 0.7: The static_url_path, static_folder, and template_folder parame-
ters were added.
New in version 0.8: The instance_path and instance_relative_config parameters
were added.
New in version 0.11: The root_path parameter was added.
Parameters
• import_name – the name of the application package
• static_url_path – can be used to specify a different path
for the static files on the web. Defaults to the name of the
static_folder folder.
• static_folder – the folder with static files that should be
served at static_url_path. Defaults to the 'static' folder in the
root path of the application.
• template_folder – the folder that contains the templates that
should be used by the application. Defaults to 'templates'
folder in the root path of the application.
• instance_path – An alternative instance path for the applica-
tion. By default the folder 'instance' next to the package or
module is assumed to be the instance path.
• instance_relative_config – if set to True relative filenames
for loading the config are assumed to be relative to the instance
path instead of the application root.
• root_path – Flask by default will automatically calculate the
path to the root of the application. In certain situations this
cannot be achieved (for instance if the package is a Python 3
namespace package) and needs to be manually defined.

190

add_template_filter(f, name=None)
Register a custom template filter. Works exactly like the template_filter()
decorator.
Parameters name – the optional name of the filter, otherwise the
function name will be used.
add_template_global(f, name=None)
Register a custom template global function. Works exactly like the
template_global() decorator.
New in version 0.10.
Parameters name – the optional name of the global function, other-
wise the function name will be used.
add_template_test(f, name=None)
Register a custom template test. Works exactly like the template_test()
decorator.
New in version 0.10.
Parameters name – the optional name of the test, otherwise the
function name will be used.
add_url_rule(rule, endpoint=None, view_func=None, **options)
Connects a URL rule. Works exactly like the route() decorator. If a
view_func is provided it will be registered with the endpoint.
Basically this example:

@app.route('/')
def index():
pass

Is equivalent to the following:

def index():
pass
app.add_url_rule('/', 'index', index)

If the view_func is not provided you will need to connect the endpoint to a
view function like so:

app.view_functions['index'] = index

Internally route() invokes add_url_rule() so if you want to customize the
behavior via subclassing you only need to change this method.
For more information refer to URL Route Registrations.
Changed in version 0.2: view_func parameter added.
Changed in version 0.6: OPTIONS is added automatically as method.
Parameters

191

• rule – the URL rule as string
• endpoint – the endpoint for the registered URL rule. Flask
itself assumes the name of the view function as endpoint
• view_func – the function to call when serving a request to the
provided endpoint
• options – the options to be forwarded to the underlying Rule
object. A change to Werkzeug is handling of method options.
methods is a list of methods this rule should be limited to
(GET, POST etc.). By default a rule just listens for GET (and
implicitly HEAD). Starting with Flask 0.6, OPTIONS is implicitly
added and handled by the standard request handling.
after_request(f )
Register a function to be run after each request.
Your function must take one parameter, an instance of response_class and
return a new response object or the same (see process_response()).
As of Flask 0.7 this function might not be executed at the end of the request
in case an unhandled exception occurred.
after_request_funcs = None
A dictionary with lists of functions that should be called after each request.
The key of the dictionary is the name of the blueprint this function is active
for, None for all requests. This can for example be used to close database
connections. To register a function here, use the after_request() decorator.
app_context()
Binds the application only. For as long as the application is bound to the
current context the flask.current_app points to that application. An appli-
cation context is automatically created when a request context is pushed if
necessary.
Example usage:

with app.app_context():
...

New in version 0.9.
app_ctx_globals_class
The class that is used for the g instance.
Example use cases for a custom class:
1.Store arbitrary attributes on flask.g.
2.Add a property for lazy per-request database connectors.
3.Return None instead of AttributeError on unexpected attributes.
4.Raise exception if an unexpected attr is set, a “controlled” flask.g.

192

before_first_request_funcs = None A lists of functions that should be called at the beginning of the first request to this instance.9 this property was called request_globals_class but it was changed in 0.g object is now applica- tion context scoped.10. To register a function here. use the before_request() decorator. alias of _AppCtxGlobals auto_find_instance_path() Tries to locate the instance path if it was not provided to the constructor of the application class. New in version 0. before_first_request(f ) Registers a function to be run before the first request to this instance of the application.10 to app_ctx_globals_class because the flask. This can for example be used to open database connections or getting hold of the currently logged in user. The function will be called without any arguments. It will basically calculate the path to a folder named instance next to your main file or the package. before_request(f ) Registers a function to run before each request. New in version 0. To register a function here. If the function returns a non-None value. The function will be called without any arguments and its return value is ignored. use the before_first_request() decorator.7.8.8. New in version 0. New in version 0. Commands registered 193 . The key of the dictionary is the name of the blueprint this function is active for. cli = None The click command line context for this application. Blueprints can be at- tached multiple times so this dictionary does not tell you how often they got attached. In Flask 0.8. New in version 0. None for all requests. before_request_funcs = None A dictionary with lists of functions that should be called at the beginning of the request. it’s handled as if it was the return value from the view and further request handling is stopped. blueprints = None all the attached blueprints in a dictionary by name.

11. here show up in the flask command once the application has been dis- covered.7. Override this function to customize the behavior. Instead one should override the jinja_loader() function instead. New in version 0.Access to config values through attributes in addition to keys.Default values for certain config options. Example use cases for a custom class: 1. New in version 0.11: Environment.7 this also adds the Jinja2 globals and filters after initialization. 194 . New in version 0. create_jinja_environment() Creates the Jinja2 environment based on jinja_options and select_jinja_autoescape(). It’s discouraged to override this function.9: This can now also be called without a request object when the URL adapter is created for the application context. This behaves exactly like a regular dictionary but supports additional methods to load a config from files.Group object. Changed in version 0. New in version 0. Since 0. The URL adapter is created at a point where the request context is not yet set up so the request is passed explicitly. alias of Config context_processor(f ) Registers a template context processor function. Can be used to override just the loader and keeping the rest unchanged. Defaults to Config. create_global_jinja_loader() Creates the loader for the Jinja2 environment. create_url_adapter(request) Creates a URL adapter for the given request. config_class The class that is used for the config attribute of this app.5. Changed in version 0. The default commands are provided by Flask itself and can be overridden.auto_reload set in accordance with TEMPLATES_AUTO_RELOAD configuration option. The global loader dispatches between the loaders of the application and the individual blueprints. config = None The configuration dictionary as Config. This is an instance of a click.6. 2.

Example: @app. do_teardown_appcontext(exc=<object object>) Called when an application context is popped. In debug mode the debugger will kick in when an unhandled exception occurs and the integrated server will automatically reload the application if changes in the code are detected. otherwise the key is the name of the blueprint. call make_response(). this code was moved to the new full_dispatch_request(). ‘USE_X_SENDFILE’: False. dispatch_request() Does the request dispatching. This attribute can also be configured from the config with the DEBUG config- uration key. This works pretty much the same as do_teardown_request() but for the application context.endpoint') def example(): return "example" Parameters endpoint – the name of the endpoint error_handler_spec = None A dictionary of all registered error handlers. This is not actually called by the Flask object itself but is always triggered when the request context is popped. endpoint(endpoint) A decorator to register a function as an endpoint. Set this to True to enable debugging of the application.7: This no longer does the exception handling.9. New in version 0. Changed in version 0. The key is None for error handlers active on the application. Changed in version 0. Defaults to False. Each key points to another dictionary where the key is the status code of the http exception. ‘SE Default configuration parameters.endpoint('example. Matches the URL and returns the return value of the view or error handler. Previously this was al- ways using the current exception information. do_teardown_request(exc=<object object>) Called after the actual request dispatching and will call every as teardown_request() decorated function.9: Added the exc argument. This does not have to be a response object. default_config = ImmutableDict({‘JSON_AS_ASCII’: True. That way we have a tighter control over certain resources under testing environments.debug The debug flag. In order to convert the return value to a proper response object. The special key None points to a list of tuples 195 .

404 app. For backwards compatibility extensions should register themselves like this: if not hasattr(app. Parameters code_or_exception – the code as integer for the han- dler. or an arbitrary exception extensions = None a place where extensions can store application specific state. 404 You can also register handlers for arbitrary exceptions: @app. 'extensions'): app. use the errorhandler() decorator.7: One can now additionally also register custom excep- tion types that do not necessarily have to be a subclass of the HTTPException class. for application wide error handlers.7: Use register_error_handler() instead of modifying error_handler_spec directly. 500 You can also register a function as error handler without using the errorhandler() decorator. For exam- ple this is where an extension could store database engines and similar things. The following example is equivalent to the one above: def page_not_found(error): return 'This page does not exist'.extensions['extensionname'] = SomeObject() 196 . New in version 0. The first None refers to the active blueprint.errorhandler(DatabaseError) def special_exception_handler(error): return 'Database connection failed'.error_handler_spec[None][404] = page_not_found Setting error handlers via assignments to error_handler_spec however is discouraged as it requires fiddling with nested dictionaries and the special case for arbitrary exception types. Example: @app. To register a error handler.errorhandler(404) def page_not_found(error): return 'This page does not exist'. If the error handler should be application wide None shall be used. New in version 0. where the first item is the class for the instance check and the second the error handler function.extensions = {} app. errorhandler(code_or_exception) A decorator that is used to register a function given an error code.

Flask): def get_send_file_max_age(self. This allows subclasses to change the behavior when sending files based on the filename. New in version 0. For example in case of a “Flask-Foo” extension in flask_foo.3. New in version 0. oth- erwise it is logged and the handler for a 500 internal server error is used. this function returns SEND_FILE_MAX_AGE_DEFAULT from the con- figuration of current_app. handle_url_build_error(error. The key must match the name of the extension module. a default 500 internal server error message is dis- played. If a cache_timeout is given in send_file(). New in version 0. full_dispatch_request() Dispatches the request and on top of that performs request pre and post- processing as well as HTTP exception catching and error handling.js files to 60 seconds: class MyFlask(flask. values) Handle BuildError on url_for(). By default. the key would be 'foo'.get_send_file_max_age(self. got_first_request This attribute is set to True if the application started handling the first re- quest.7. get_send_file_max_age(filename) Provides default cache_timeout for the send_file() functions. and send_file() calls this function on current_app when the given cache_timeout is None. For example. this method is called. 197 . endpoint. Static file functions such as send_from_directory() use this function. to set the cache timeout for . name): if name.9. otherwise. By default this will invoke the registered error handlers and fall back to returning the exception as response. New in version 0. handle_http_exception(e) Handles an HTTP exception.js'): return 60 return flask. name) New in version 0. If no such handler exists.endswith('. handle_exception(e) Default exception handling that kicks in when an exception occurs that is not caught.8.Flask. In debug mode the exception will be re-raised immediately. that time- out is used.3.lower().7. New in version 0.

autoescape’. has_static_folder This is True if the package bound object’s container has a folder for static files. jinja_env The Jinja2 environment used to load templates. Override create_jinja_environment() instead. A special case are HTTPExceptions which are forwarded by this function to the handle_http_exception() method.with_’]}) Options that are passed directly to the Jinja2 environment. This is used internally and automatically called on URL building. instance_path = None Holds the path to the instance folder.5. values) Injects the URL defaults for the given endpoint directly into the values dic- tionary passed. iter_blueprints() Iterates over all blueprints by the order they were registered. New in version 0. inject_url_defaults(endpoint.7. New in version 0.7.5. This function will either return a response value or reraise the exception with the same traceback. init_jinja_globals() Deprecated. New in version 0.ext. alias of Environment jinja_loader The Jinja loader for this package bound object. jinja_options = ImmutableDict({‘extensions’: [’jinja2. Used to initialize the Jinja2 globals.5. jinja_environment The class that is used for the Jinja environment. New in version 0. 198 . Changed in version 0.11. New in version 0.ext. handle_user_exception(e) This method is called whenever an exception occurs that should be handled. ‘jinja2.11. New in version 0. New in version 0.7.8. New in version 0.7: This method is deprecated with 0.

logger. Defaults to JSONEncoder. New in version 0. This is called by handle_exception() if debugging is disabled and right before the handler is called. 42) app.10. Instead of overriding this method we recommend replacing the session_interface. By default the logger name is the package name passed to the constructor. New in version 0. Here some examples: app.Logger object for this application. 199 . make_default_options_response() This method is called to create the default OPTIONS response. make_null_session() Creates a new instance of a missing session. alias of JSONEncoder log_exception(exc_info) Logs an exception.json_decoder The JSON decoder class to use. New in version 0. New in version 0.8.8.7. This logger can be used to (surprise) log messages.warning('A warning occurred (%d apples)'.debug('A value for debugging') app.3.4. The in- stance_relative parameter is passed in from the constructor of Flask (there named instance_relative_config) and indicates if the config should be relative to the instance path or the root path of the application. logger A logging.logger.error('An error occurred') New in version 0. make_config(instance_relative=False) Used to create the config attribute by the Flask constructor.10. Defaults to JSONDecoder. This can be changed through subclassing to change the default behavior of OPTIONS re- sponses. alias of JSONDecoder json_encoder The JSON encoder class to use.logger. logger_name The name of the logger to use. New in version 0. The default configuration is to log to stderr if the application is in debug mode. The default implementation logs the exception as error on the logger. New in version 0.

open_resource(resource. consider the following folder structure: 200 . mode=’rb’) Opens a resource from the application’s resource folder. This is usually the import name with the dif- ference that it’s guessed from the run file if the import name is main. This runs all the registered shell context processors. headers) or (response. name The name of the application. It can be set and overridden to change the value.7. New in version 0. New in version 0. New in version 0. This name is used as a display name when Flask needs the name of the applica- tion. open_instance_resource(resource. • mode – resource file opening mode. To see how this works. To access resources within subfolders use forward slashes as separator. mode=’rb’) Opens a resource from the application’s instance folder (instance_path). status is a string or an inte- ger and headers is a list or a dictionary with header values. default is ‘rb’. Instance resources can also be opened for writing. The following types are allowed for rv: response_class the object is returned unchanged str a response object is created with the string as body unicode a response object is created with the string encoded to utf-8 as body a WSGI function the function is called as WSGI application and buffered as response object tuple A tuple in the form (response. headers) where response is any of the types defined here.8.9: Previously a tuple was interpreted as the arguments for the response object. Parameters rv – the return value from the view function Changed in version 0. Otherwise works like open_resource(). status. make_response(rv) Converts the return value from a view function to a real response object that is an instance of response_class. Parameters • resource – the name of the resource. make_shell_context() Returns the shell context for an interactive shell for this application.11.

This requires that the secret_key is set. • mode – resource file opening mode. New in version 0. passing no arguments.html /index.sql file you would do the following: with app. permanent_session_lifetime A timedelta which is used to set the expiration date of a permanent session.py /schema. Default implementation stores all session data in a signed cookie.html If you want to open the schema. This also triggers the url_value_preprocessor() functions before the actual before_request() functions are called. 201 . it’s handled as if it was the return value from the view and further request handling is stopped. /myapplication.open_resource('schema. Instead of overriding this method we recommend replacing the session_interface. Defaults to timedelta(days=31) preprocess_request() Called before the actual request dispatching and will call each before_request() decorated function. open_session(request) Creates or opens a new session. If any of these functions returns a value. Parameters request – an instance of request_class. preserve_context_on_exception Returns the value of the PRESERVE_CONTEXT_ON_EXCEPTION configuration value in case it’s set. default is ‘rb’.read() do_something_with(contents) Parameters • resource – the name of the resource. To access resources within subfolders use forward slashes as separator. The default is 31 days which makes a permanent session survive for roughly one month.sql') as f: contents = f. This attribute can also be configured from the config with the PERMANENT_SESSION_LIFETIME configuration key. otherwise a sensible default is returned.css /templates /layout.7.sql /static /style.

register_blueprint(blueprint. f ) Alternative error attach function to the errorhandler() decorator that is more straightforward to use for non decorator usage.7. request_class The class that is used for request objects. By default this will call all the after_request() decorated functions. otherwise a sensible default is returned. Returns a new response object or the same. register_error_handler(code_or_exception.7. The example above is doing exactly the same as this code: ctx = app. alias of Request request_context(environ) Creates a RequestContext from the given environment and binds it to the current context. process_response(response) Can be overridden in order to modify the response object before it’s sent to the WSGI server. New in version 0. New in version 0. Example usage: with app.push() try: do_something_with(request) 202 . New in version 0.7. propagate_exceptions Returns the value of the PROPAGATE_EXCEPTIONS configuration value in case it’s set. See Request for more information.5 the functions registered for after request execution are called in reverse order of registration. has to be an instance of response_class.request_context(environ) ctx. This must be used in combination with the with statement because the request is only bound to the current context for the duration of the with block.5: As of Flask 0. Changed in version 0. Parameters response – a response_class object. **options) Registers a blueprint on the application.request_context(environ): do_something_with(request) The object returned can also be used without the with statement which is useful for working in the shell.

6.). port=None. See Response for more informa- tion. This does the same thing as add_url_rule() but is intended for decorator usage: @app. but disable code execution. run(host=None. alias of Response route(rule. If the debug flag is set the server will automatically reload for code changes and show a debugger in case an exception happened. methods is a list of methods this rule should be limited to (GET. A change to Werkzeug is handling of method options.3: Added support for non-with statement usage and with statement is now passed the ctx object. you can pass use_evalex=False as pa- rameter. Do not use run() in a production setting. but disable the code ex- ecution on the interactive debugger. OPTIONS is implicitly added and handled by the standard request handling. It is not intended to meet security and performance requirements for a production server. 203 .route('/') def index(): return 'Hello World' For more information refer to URL Route Registrations. **options) Runs the application on a local development server. Parameters environ – a WSGI environment response_class The class that is used for response objects. debug=None. By default a rule just listens for GET (and implicitly HEAD). finally: ctx. see Deploy- ment Options for WSGI server recommendations. This will keep the debugger’s traceback screen active.pop() Changed in version 0. Instead. Parameters • rule – the URL rule as string • endpoint – the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint • options – the options to be forwarded to the underlying Rule object. Starting with Flask 0. **options) A decorator that is used to register a view function for a given URL rule. If you want to run the application in debug mode. POST etc.

Defaults to 5000 or the port defined in the SERVER_NAME config variable if present. Keep in Mind Flask will suppress any server error with a generic error page unless it is in debug mode. See debug. New in version 0.5. returns True.serving.run_simple() for more information. • debug – if given.10: The default port is now picked from the SERVER_NAME variable. 1'. This attribute can also be configured from the config with the SECRET_KEY configuration key. Instead of overriding this method we recommend replac- ing the session_interface. • port – the port of the webserver. It is not recommended to use this function for development with automatic reloading as this is badly supported. response) Saves the session if it needs updates.0. save_session(session. Set this to a complex random value when you want to use the secure cookie for instance. Setting use_debugger to True without being in debug mode won’t catch any exceptions because there won’t be any to catch. For the default implementation. As such to enable just the interactive debugger with- out the code reloading. 204 . Parameters • host – the hostname to listen on. check open_session(). you have to invoke run() with debug=True and use_reloader=False. Defaults to '127. Defaults to None. Instead you should be using the flask command line script’s run support. • options – the options to be forwarded to the underlying Werkzeug server. select_jinja_autoescape(filename) Returns True if autoescaping should be active for the given template name. Changed in version 0. Parameters • session – the session to be saved (a SecureCookie object) • response – an instance of response_class secret_key If a secret key is set.0. If no template name is given. Set this to '0. enable or disable debug mode.0. cryptographic components can use this to sign cookies and other things.0. See werkzeug.0' to have the server available externally as well.

New in version 0. New in version 0. should_ignore_error(error) This is called to figure out if an error should be ignored or not as far as the teardown system is concerned.11. shell_context_processors = None A list of shell context processor functions that should be run when a shell context is created. The default is 12 hours. Defaults to 'session' session_interface = <flask.app_context() ctx. static_folder The absolute path to the configured static folder.SecureCookieSessionInterface object> the session interface to use. This attribute can also be configured from the config with the SESSION_COOKIE_NAME configuration key. By default an instance of SecureCookieSessionInterface is used here.10.8. New in version 0. session_cookie_name The secure cookie uses this for the name of the session cookie. Defaults to timedelta(hours=12) send_static_file(filename) Function used internally to send static files from the static folder to the browser.sessions.push() 205 . teardown_appcontext(f ) Registers a function to be called when the application context ends. New in version 0. This configuration vari- able can also be set with an integer value used as seconds. Example: ctx = app.5. New in version 0. shell_context_processor(f ) Registers a shell context processor function.send_file_max_age_default A timedelta which is used as default cache_timeout for the send_file() functions. This attribute can also be configured from the config with the SEND_FILE_MAX_AGE_DEFAULT configuration key. If this function returns True then the teardown handlers will not be passed the error.11. These functions are typically also called when the request context is popped.

Since the application context is also torn down if the request ends this is the place to store code that disconnects from databases. This becomes relevant if you are using such constructs in tests. Instead it will keep it alive so that the interactive de- 206 . The return values of teardown functions are ignored..test_request_context() ctx. teardown_request(f ) Register a function to be run at the end of each request. When a teardown function was called because of an exception it will be passed an error object. Debug Note In debug mode Flask will not tear down a request on an exception immediately. Example: ctx = app.pop() When ctx.pop() When ctx.push() .9. This becomes relevant if you are using such constructs in tests. New in version 0.. ctx. ctx.pop() is executed in the above example..pop() is executed in the above example. New in version 0. even if not an actual request was performed. the teardown functions are called just before the request context moves from the stack of active con- texts. the teardown functions are called just before the app context moves from the stack of active con- texts. These functions are executed when the request context is popped. When a teardown function was called because of a exception it will be passed an error object. Generally teardown functions must take every necessary step to avoid that they will fail. If they do execute code that might fail they will have to sur- round the execution of these code by try/except statements and log occur- ring errors. The return values of teardown functions are ignored.. teardown_appcontext_funcs = None A list of functions that are called when the application context is destroyed. Since a request context typically also manages an application context it would also be called when you pop a request context. .9. regardless of whether there was an exception or not.

None for all requests. You can specify a name for the global function. Example: @app. Example: 207 . The key of the dictionary is the name of the blueprint this function is active for. teardown_request_funcs = None A dictionary with lists of functions that are called after each request. otherwise the function name will be used. bugger can still access it. Parameters name – the optional name of the global function. You can specify a name for the filter. The key of the dictionary is the name of the blueprint this function is active for. it gets passed to each teardown_request function. To register a function here. If an exception occurred while processing the request.7. other- wise the function name will be used.10. otherwise the function name will be used. Each returns a dictionary that the template context is updated with. New in version 0. template_context_processors = None A dictionary with list of functions that are called without argument to pop- ulate the template context.template_global() def double(n): return 2 * n New in version 0. This behavior can be controlled by the PRESERVE_CONTEXT_ON_EXCEPTION configuration variable. template_global(name=None) A decorator that is used to register a custom template global function. otherwise the function name will be used. even if an exception has occurred. template_filter(name=None) A decorator that is used to register custom template filter. use the teardown_request() decorator. None for all requests. and their return values are ig- nored. use the context_processor() decorator. template_test(name=None) A decorator that is used to register custom template test. These func- tions are not allowed to modify the request.template_filter() def reverse(s): return s[::-1] Parameters name – the optional name of the filter. You can specify a name for the test. Example: @app. To register a function here. otherwise the function name will be used.

testing = True in order for the exceptions to prop- agate to the test client.test_client(authentication='Basic ..testing import FlaskClient class CustomClient(FlaskClient): def __init__(self. Otherwise. For example: from flask.4: added support for with block usage for the client. See the testing attribute. test_client(use_cookies=True.') See FlaskClient for more information.pop("authentication") super(CustomClient. This is useful if you want to access the context locals for testing: with app.ceil(math..test_client() as c: rv = c._authentication = kwargs.test_client_class = CustomClient client = app.__init__( *args. **kwargs) app. you may pass optional keyword arguments that will then be passed to the application’s test_client_class constructor. **kwargs): self. Note that if you are testing for assertions or exceptions in your application code.args['vodka'] == '42' Additionally. Changed in version 0.testing = True client = app. the exception will be handled by the application (not visible to the test client) and the only indication of an As- sertionError or other exception will be a 500 status code response to the test client. Parameters name – the optional name of the test.sqrt(n))) + 1): if n % i == 0: return False return True New in version 0. For example: app.self). **kwargs) Creates a test client for this application.10.get('/?vodka=42') assert request. otherwise the function name will be used. 208 .. For information about unit testing head over to Testing Flask Applications. *args. int(math. you must set app.test_client() The test client can be used in a with block to defer the closing down of the context until the end of the with block.template_test() def is_prime(n): if n == 2: return True for i in range(2. @app.

session. Defaults to False. Each 209 . test_client_class = None the test client that is used with when test_client is used. **kwargs) Creates a WSGI environment from the given values (see werkzeug. Set this to True to enable the test mode of Flask extensions (and in the future probably also Flask itself). update_template_context(context) Update the template context with some commonly used variables. By default this will return False for all exceptions except for a bad request key er- ror if TRAP_BAD_REQUEST_ERRORS is set to True. EnvironBuilder for more information. If it returns True for any exception the error handler for this exception is not called and it shows up as regular exception in the traceback. trap_http_exception(e) Checks if an HTTP exception should be trapped or not. test_request_context(*args. It also returns True if TRAP_HTTP_EXCEPTIONS is set to True. Note that the as of Flask 0. This is helpful for debug- ging implicitly raised HTTP exceptions. New in version 0. Changed in version 0. For example this might activate unittest helpers that have an additional runtime cost which should not be enabled by default.11: Added **kwargs to support passing additional key- word arguments to the constructor of test_client_class. New in version 0. url_build_error_handlers = None A list of functions that are called when url_for() raises a BuildError.8. the original values in the context will not be overridden if a context processor decides to return a value with the same key. Parameters context – the context as a dictionary that is updated in place to add extra variables. If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the default it’s implicitly enabled.7. testing The testing flag. New in version 0. config and g into the template context as well as every- thing template context processors want to inject.6. this function accepts the same argu- ments).7: The use_cookies parameter was added as well as the ability to override the client to be used by setting the test_client_class attribute. This in- jects request.test. This attribute can also be configured from the config with the TESTING con- figuration key. This is called for all HTTP exceptions raised by a view function.

url_defaults(f ) Callback function for URL defaults for all view functions of the applica- tion. Defaults to werkzeug. This is used by add_url_rule(). function registered here is called with error. Each of these functions has the chance to modify the dictionary of URL values before they are used as the key- word arguments of the view function. The key None here is used for application wide callbacks. It’s called with the endpoint and values and should update the values passed in place. url_map = None The Map for this instance. url_default_functions = None A dictionary with lists of functions that can be used as URL value prepro- cessors. value): return value. self).routing. otherwise the key is the name of the blueprint. Example: from werkzeug. You can use this to change the routing converters after the class was created but before any routes are connected.to_url(value) for value in values) app = Flask(__name__) app.') def to_url(self. New in version 0.routing import BaseConverter class ListConverter(BaseConverter): def to_python(self. values): return '.9. endpoint and values. If a function returns None or raises a BuildError the next function is tried.join(super(ListConverter.url_map. New in version 0.7. For each function registered this one should also provide a url_defaults() function that adds the parameters automatically again that were removed that way.7. Whenever a URL is built these functions are called to modify 210 .split('. It’s called before the view functions are called and can modify the url values provided. New in version 0.Rule.'. alias of Rule url_value_preprocessor(f ) Registers a function as URL value preprocessor for all view functions of the application. url_value_preprocessors = None A dictionary with lists of functions that can be used as URL value processor functions.converters['list'] = ListConverter url_rule_class The rule object to use for URL rules created.

wsgi_app) Then you still have the original application object around and can continue to call methods on it. Defaults to False. See Callbacks and Errors. wsgi_app(environ. The key None here is used for application wide callbacks. otherwise the key is the name of the blueprint.7. This attribute can also be configured from the config with the USE_X_SENDFILE configuration key. To register a view function.2. start_response) The actual WSGI application. This is not implemented in __call__ so that middlewares can be applied without losing a reference to the class. a list of headers and an optional exception context to start the re- sponse 211 . Keep in mind that the server has to support this. use the route() decorator. New in version 0. Changed in version 0. This only affects files sent with the send_file() method. So in- stead of doing this: app = MyMiddleware(app) It’s a better idea to do this instead: app. Each of these functions has the chance to modify the dictionary New in version 0. independent on if an error occurred or not. The keys will be function names which are also used to generate URLs and the values are the function objects themselves. the dictionary of values in place. view_functions = None A dictionary of all view functions registered.7: The behavior of the before and after request call- backs was changed under error conditions and a new callback was added that will always execute at the end of the request. Parameters • environ – a WSGI environment • start_response – a callable accepting a status code. use_x_sendfile Enable this if you want to use the X-Sendfile feature.wsgi_app = MyMiddleware(app.

add_app_template_filter(f. This function is only exe- cuted after each request that is handled by a function of that blueprint. A blueprint is an object that records functions that will be called with the BlueprintSetupState later to register functions or other things on the main application.Blueprint(name. static_folder=None. otherwise the function name will be used. Works exactly like the app_template_test() decorator.23.10. add_template_filter() but for a blueprint. after_request(f ) Like Flask. subdomain=None. name=None) Register a custom template global. available application wide. name=None) Register a custom template filter. url_defaults=None. Works exactly like the app_template_filter() decorator. view_func=None. Parameters name – the optional name of the filter. even if outside of the blueprint. **options) Like Flask.add_template_test() but for a blueprint.10. import_name. url_prefix=None. New in version 0. name=None) Register a custom template test. template_folder=None. Like Flask. 212 .7.after_request() but for a blueprint. available application wide. otherwise the function name will be used. after_app_request(f ) Like Flask. Works exactly like the app_template_global() decorator. otherwise the function name will be used. Like Flask.2 Blueprint Objects class flask.after_request() but for a blueprint. add_app_template_test(f. add_url_rule(rule. New in version 0.add_url_rule() but for a blueprint.add_template_global() but for a blueprint. Parameters name – the optional name of the test. endpoint=None. Parameters name – the optional name of the global. See Modular Applications with Blueprints for more infor- mation. The endpoint for the url_for() function is prefixed with the name of the blueprint. add_app_template_global(f. static_url_path=None. available application wide. root_path=None) Represents a blueprint. Such a function is executed after each request. New in version 0. Like Flask.

This function is only executed for requests handled by a blueprint. Such a function is executed before the first request to the application.before_request(). app_url_value_preprocessor(f ) Same as url_value_preprocessor() but application wide. app_template_global(name=None) Register a custom template global. available application wide. Parameters name – the optional name of the global. even if outside of the blueprint. Parameters name – the optional name of the test. even if outside of the blueprint. Such a function is ex- ecuted each request.errorhandler() but for a blueprint.before_first_request(). template_filter() but for a blueprint. context_processor(f ) Like Flask. template_global() but for a blueprint. app_errorhandler(code) Like Flask. before_app_request(f ) Like Flask.app_context_processor(f ) Like Flask. This function is only exe- cuted before each request that is handled by a function of that blueprint. template_test() but for a blueprint. app_url_defaults(f ) Same as url_defaults() but application wide. Like Flask. 213 . app_template_test(name=None) Register a custom template test. app_template_filter(name=None) Register a custom template filter. otherwise the function name will be used. Like Flask. available application wide. New in version 0.context_processor() but for a blueprint.10. otherwise the function name will be used. Parameters name – the optional name of the filter.context_processor() but for a blueprint.10. Like Flask. Such a function is executed before each re- quest.before_request() but for a blueprint. available application wide. before_app_first_request(f ) Like Flask. otherwise the function name will be used. This handler is used for all requests. even if outside of a blueprint. before_request(f ) Like Flask. New in version 0.

This does not prefix the end- point with the blueprint name.9.get_send_file_max_age(self. New in version 0. name) New in version 0. to set the cache timeout for .endswith('. this method is called. name): if name.Flask. Otherwise works as the errorhandler() decorator of the Flask object.js files to 60 seconds: class MyFlask(flask. endpoint(endpoint) Like Flask. it will be registered to the current blueprint. Please be aware that routing does not happen local to a blueprint so an error han- dler for 404 usually is not handled by a blueprint unless it is caused inside a view function.5. first_registration=False) Creates an instance of BlueprintSetupState() object that is later passed to the register callback functions.endpoint() but for a blueprint. To see how this 214 . has_static_folder This is True if the package bound object’s container has a folder for static files. make_setup_state(app. errorhandler(code_or_exception) Registers an error handler that becomes active for this blueprint only. otherwise. Subclasses can override this to return a sub- class of the setup state. this has to be done explicitly by the user of this method. mode=’rb’) Opens a resource from the application’s resource folder. This allows subclasses to change the behavior when sending files based on the filename. options. If the endpoint is prefixed with a . otherwise it’s an application independent endpoint.lower(). For example. By default. this function returns SEND_FILE_MAX_AGE_DEFAULT from the con- figuration of current_app. open_resource(resource. that time- out is used. If a cache_timeout is given in send_file(). get_send_file_max_age(filename) Provides default cache_timeout for the send_file() functions.js'): return 60 return flask.5.Flask): def get_send_file_max_age(self. Another special case is the 500 internal server error which is always looked up from the application. New in version 0. Static file functions such as send_from_directory() use this function. jinja_loader The Jinja loader for this package bound object. and send_file() calls this function on current_app when the given cache_timeout is None.

Key- word arguments from register_blueprint() are directly forwarded to this method in the options dictionary. send_static_file(filename) Function used internally to send static files from the static folder to the browser.sql') as f: contents = f. the function passed is not called. This can be overridden to customize the register behavior. register(app. • mode – resource file opening mode. f ) Non-decorator version of the errorhandler() error attach function.11.route() but for a blueprint.register_blueprint() to register a blueprint on the ap- plication. consider the following folder structure: /myapplication. first_registration=False) Called by Flask. register_error_handler(code_or_exception.py /schema. **options) Like Flask. options. This function is called with the state as argument as returned by the make_setup_state() method. akin to the register_error_handler() application-wide function of the Flask ob- ject but for error handlers limited to this blueprint. 215 . To access resources within subfolders use forward slashes as separator. record_once(func) Works like record() but wraps the function in another function that will ensure the function is only called once. If the blueprint is registered a second time on the application. default is ‘rb’.sql /static /style.html /index. record(func) Registers a function that is called when the blueprint is registered on the application. route(rule. The endpoint for the url_for() function is prefixed with the name of the blueprint. New in version 0.css /templates /layout.html If you want to open the schema.sql file you would do the following: with app.open_resource('schema. works.read() do_something_with(contents) Parameters • resource – the name of the resource.

Such a function is exe- cuted when tearing down each request. shallow=False) The request object used by default in Flask.teardown_request() but for a blueprint. even if outside of the blueprint. It’s called with the endpoint and values and should update the values passed in place. Teardown request functions are executed when the request con- text is popped. populate_request=True. (The part in the URL after the question mark). static_folder The absolute path to the configured static folder. args A MultiDict with the parsed contents of the query string. values A CombinedMultiDict with the contents of both form and args.5.teardown_request() but for a blueprint. stream If the incoming form data was not encoded with a known mimetype the 216 . It is what ends up as request.Request(environ. teardown_request(f ) Like Flask. The request object is a Request subclass and provides all of the attributes Werkzeug defines plus a few Flask specific ones. even when no actual request was performed. form A MultiDict with the parsed form data from POST or PUT requests. New in version 0. This function is only executed when tearing down requests handled by a function of that blueprint. url_value_preprocessor(f ) Registers a function as URL value preprocessor for this blueprint.3 Incoming Request Data class flask. If you want to replace the request object used you can subclass this and set request_class to your subclass. cookies A dict with the contents of all cookies transmitted with the request. Remembers the matched endpoint and view arguments. It’s called before the view functions are called and can modify the url values provided. Please keep in mind that file uploads will not end up here. 23. url_defaults(f ) Callback function for URL defaults for this blueprint. teardown_app_request(f ) Like Flask. but instead in the files attribute.

GET etc.com/myapplication/π/page. data Contains the incoming request data as string in case it came with a mime- type Flask does not handle.example. It basically behaves like a standard file object you know from Python.html' full_path u'/π/page. method The current request method (POST. The stream only returns the data once.com/myapplication And a user requests the following URI: http://www.html?x=y' script_root u'/myapplication' base_url u'http://www.html? x=y' url_root u'http://www. environ The underlying WSGI environment. Imagine your application is listening on the following application root: http://www. files A MultiDict with files uploaded as part of a POST or PUT request.example. with the difference that it also has a save() function that can store the file on the filesystem.com/myapplication/π/page.html' url u'http://www. data is stored unmodified in this stream for consumption.com/myapplication/%CF%80/page.example.example.example. headers The incoming request headers as a dictionary like object. Most of the time it is a better idea to use data which will give you that data as a string. Each file is stored as FileStorage object.) path full_path script_root url base_url url_root Provides different ways to look at the current IRI.com/myapplication/' 217 .html?x=y In this case the values of the above mentioned attributes would be the fol- lowing: path u'/π/page.

Otherwise this will be None. Parameters • force – if set to True the mimetype is ignored. This in combination with view_args can be used to reconstruct the same or a modified URL. silent=False. If an exception happened when matching. The default implementation just raises a BadRequest exception. is_xhr True if the request was triggered via a JavaScript XMLHttpRequest. Libraries that do that are prototype. New in version 0. The return value of this method is used by get_json() when an error occurred. By default this function will return None if the mimetype is not applicationhttps://www.scribd.com/json but this can be overridden by the force parameter. If parsing fails the on_json_loading_failed() method on the request object will be invoked. jQuery and Mochikit and probably some more. 218 . • silent – if set to True this method will fail silently and return None. module The name of the current module if the request was dispatched to an actual module. This only works with libraries that support the X-Requested-With header and set it to XMLHttpRequest. • cache – if set to True the parsed JSON data is remembered on the request.11. get_json(force=False. on_json_loading_failed(e) Called if decoding of the JSON data failed. use blueprints instead. By default a request is considered to include JSON data if the mimetype is applicationhttps://www.scribd.com/json or application/ *+json. This is deprecated functionality. is_json Indicates if this request is JSON or not. cache=True) Parses the incoming JSON request data and returns it. The get_json() method should be used instead. this will be None. blueprint The name of the current blueprint endpoint The endpoint that matched the request. max_content_length Read-only view of the MAX_CONTENT_LENGTH config key. json If the mimetype is applicationhttps://www.scribd.com/json this will contain the parsed JSON data.

This can be useful to in- spect which methods are allowed for the URL from a before/after handler (request. Works like the response object from Werkzeug but is set to have an HTML mimetype by default. Internally Flask makes sure that you always get the correct data for the active thread if you are in a multithreaded environment. you can use the global request object. Flask parses incoming request data for you and gives you access to it through that global object. Changed in version 0. direct_passthrough=False) The response object that is used by default in Flask. content_type=None. status=None. headers=None. 23. This just shows a quick overview of the most im- portant ones.10: Removed buggy previous behavior of generating a random JSON response. headers A Headers object representing the response headers.Response(response=None.4 Response Objects class flask. url_rule = None The internal URL rule that matched the request. this is the exception that will be raised / was raised as part of the request handling. If an exception hap- pened when matching. New in version 0. See Notes On Proxies for more information. class flask. 219 .8. routing_exception = None If matching the URL failed. If you want that behavior back you can trivially add it by subclassing. If you want to replace the response object used you can subclass this and set response_class to your subclass. This is usually a NotFound exception or something similar. Quite often you don’t have to create this object yourself because make_response() will take care of that for you.url_rule.request To access incoming request data. This is a proxy. status A string with a response status. New in version 0.methods) etc. The request object is an instance of a Request subclass and provides all of the attributes Werkzeug defines. this will be None.6. view_args = None A dict of view arguments that matched the request. mime- type=None.

path=’/’. • max_age – should be a number of seconds.example. This should not be used and will eventually get deprecated. or None (default) if the cookie should last only as long as the client’s browser session. Oth- erwise. with the difference that it keeps track on modifications. do- main=None. So the user can look at the session contents. See Notes On Proxies for more information. mimetype The mimetype (content type without charset etc. secure=None.example. value=’‘. This is a proxy. but not modify it unless they know the secret key.5 Sessions If you have the Flask. status_code The response status as integer. 23. so make sure to set that to something complex and unguessable. max_age=None.example. The following attributes are interesting: 220 . • expires – should be a datetime object or UNIX timestamp. too.com etc. • domain – if you want to set a cross-domain cookie. data A descriptor that calls get_data() and set_data(). foo. expires=None. The parameters are the same as in the cookie Morsel object in the Python standard library but it accepts unicode data.session The session object works pretty much like an ordinary dict. per default it will span the whole domain. Parameters • key – the key (name) of the cookie to be set. To access the current session you can use the session object: class flask. A session basically makes it possible to remember information from one request to an- other. domain=". The way Flask does this is by using a signed cookie.com. • value – the value of the cookie.com" will set a cookie that is readable by the domain www.) set_cookie(key. For exam- ple. httponly=False) Sets a cookie.secret_key set you can use sessions in Flask applications. • path – limits the cookie to a given path. a cookie will only be readable by the domain that set it.

To replace the session interface on an application all you have to do is to assign flask. The session object returned by the open_session() method has to provide a dic- tionary like interface plus the properties and methods from the SessionMixin. modified True if the session object detected a modification. class flask. the others have useful defaults which you don’t need to change. 23.append(42) # so mark it as modified yourself session. Be advised that modifica- tions on mutable structures are not picked up automatically. SessionMixin): pass If open_session() returns None Flask will call into make_null_session() to create a session that acts as replacement if the session support cannot work because some requirement is not fulfilled. The default is 31 days. The only meth- ods you have to implement are open_session() and save_session(). The session interface provides a simple way to replace the session implementation that Flask is using. If set to False (which is the default) the session will be deleted when the user closes the browser. Here an example: # this change is not picked up because a mutable object (here # a list) is changed. The default NullSession class that is created will complain that the secret key was not set. We recommend just subclassing a dict and adding that mixin: class Session(dict.SessionInterface The basic interface you have to implement in order to replace the default session interface which uses werkzeug’s securecookie implementation. new True if the session is new. False otherwise.6 Session Interface New in version 0. in that situation you have to explicitly set the attribute to True yourself.session_interface: app = Flask(__name__) app.8.sessions. session['objects'].session_interface = MySessionInterface() 221 .modified = True permanent If set to True the session lives for permanent_session_lifetime seconds.Flask.

This currently just returns the value of the SESSION_COOKIE_SECURE setting. The default implementation returns now + the permanent session lifetime configured on the application.8. make_null_session(app) Creates a null session which acts as a replacement object if the real session support could not be loaded due to a configuration error. This currently just returns the value of the SESSION_COOKIE_HTTPONLY config var. get_expiration_time(app. New in version 0. null_session_class make_null_session() will look here for the class that should be created when a null session is requested. get_cookie_httponly(app) Returns True if the session cookie should be httponly. alias of NullSession open_session(app. session) A helper method that returns an expiration date for the session or None if the session is linked to the browser session. This checks if the object is an instance of null_session_class by default. is_null_session(obj) Checks if a given object is a null session. and falls back to APPLICATION_ROOT or uses / if it’s None. request) This method has to be implemented and must either return None in case the loading failed because of a configuration error or an instance of a ses- sion object which implements a dictionary like interface + the methods and attributes on SessionMixin. pickle_based = False A flag that indicates if the session interface is pickle based. Likewise the is_null_session() method will perform a typecheck against this type. The default imple- mentation uses the value from the SESSION_COOKIE_PATH config var if it’s set. This can be used 222 . get_cookie_path(app) Returns the path for which the cookie should be valid. This mainly aids the user experience because the job of the null session is to still support lookup without complaining but modifications are answered with a helpful error message of what failed. This creates an instance of null_session_class by default. Null sessions are not asked to be saved. get_cookie_secure(app) Returns True if the cookie should be secure. get_cookie_domain(app) Helpful helper method that returns the cookie domain that should be used for the session cookie if session cookies are used.

11. The default is hmac. serializer = <flask.SecureCookieSession(initial=None) Base class for sessions based on signed cookies. static digest_method() the hash function to use for the signature. 223 . by Flask extensions to make a decision in regards to how to deal with the session object. class flask. session. This check is usually skipped if sessions get deleted.sessions.sessions. The default is a compact JSON derived serializer with support for some extra Python types such as datetime objects or tuples. New in version 0. salt = ‘cookie-session’ the salt that should be applied on top of the secret key for the signing of cookie based sessions. New in version 0. This is still called during a request context so if you absolutely need access to the request you can do that. class flask. should_set_cookie(app.10.sessions. response) This is called for actual sessions returned by open_session() at the end of the request. class flask. session) Indicates whether a cookie should be set now or not.SecureCookieSessionInterface The default session interface that stores sessions in signed cookies through the itsdangerous module. Will still allow read-only access to the empty session but fail on setting. If it’s set to False then a cookie is only set if the session is modified. save_session(app.TaggedJSONSerializer object> A python serializer for the payload. if set to True it’s always set if the session is permanent.NullSession(initial=None) Class used to generate nicer error messages if sessions are not available. The default behavior is controlled by the SESSION_REFRESH_EACH_REQUEST config variable.sessions. The default is sha1 key_derivation = ‘hmac’ the name of the itsdangerous supported key derivation. session_class alias of SecureCookieSession class flask.sessions.SessionMixin Expands a basic dictionary with an accessors that are expected by Flask exten- sions and users for the session. This is used by session backends to figure out if they should emit a set-cookie header or not.

but that is not nec- essarily guaranteed. datetime). For general information about how to use this class refer to werkzeug. This object provides dumping and loading methods similar to simplejson but it also tags certain builtin Python objects that commonly appear in sessions.7 Test Client class flask. 224 . which can be set after instantiation of the app. flask.testing.test_client() includes preset default environ- ment. new = False some session backends can tell you if a session is new. markup objects.FlaskClient(*args. but some backends will default this to false and detect changes in the dictionary for as long as changes do not happen on mutable structures in the session.12: app.environ_base.sessions. permanent this reflects the '_permanent' key in the dict.session_json_serializer = <flask.8.Client. Use with caution. The default mixin implementation just hardcodes False in. Basic usage is outlined in the Testing Flask Applications chapter.sessions. **kwargs) Works like a regular Werkzeug test client but has some knowledge about how Flask works to defer the cleanup of the request context stack to the end of a with body when used in a with statement. 23.TaggedJSONSerializer object> A customized JSON serializer that supports a few extra types that we take for granted when serializing (tuples.test. modified = True for some backends this will always be True.test_client() object in client. Cur- rently the following extended values are supported in the JSON it dumps: •Markup objects •UUID objects •datetime objects •tuples Notice The PERMANENT_SESSION_LIFETIME config key can also be an integer starting with Flask 0. Either catch this down yourself or use the permanent_session_lifetime attribute on the app which converts the result to an integer automatically. Changed in version 0. The default mixin imple- mentation just hardcodes True in.

This can be used to modify the session that the test client uses. like it does for request and session. 23. Flask provides you with a special object that ensures it is only valid for the active request and that will return different values for each request. These two usages are now equivalent: user = getattr(flask. a global variable is not good enough because it would break in threaded environments. 23. See Notes On Proxies for more information. In a nutshell: it does the right thing.10 this is stored on the application context and no longer on the request context which means it becomes available if only the application context is bound and not yet a request. **kwargs) When used in combination with a with statement this opens a session trans- action. As of 0.g Just store on this whatever you want. This is useful for extensions that 225 . with client.get('user'. This is especially useful when combined with the Faking Resources and Context pattern for testing.g.g. None) user = flask. None) It’s now also possible to use the in operator on it to see if an attribute is defined and it yields all keys on iteration. For example a database connection or the user that is currently logged in.8 Application Globals To share data that is valid for one request only from one function to another.current_app Points to the application handling the request.9 Useful Functions and Classes flask. This is a proxy. flask.10 you can use the get() method to get an attribute or None (or the second argument) if it’s not set. Starting with Flask 0. session_transaction(*args.11 you can use pop() and setdefault() in the same way you would use them on a dictionary. 'user'.session_transaction() as session: session['value'] = 42 Internally this is implemented by going through a temporary test request context and since session handling could depend on request variables this function accepts the same arguments as test_request_context() which are directly passed through. Once the with block is left the session is stored back. Additionally as of 0.

remote_addr self. .remote_addr = remote_addr New in version 0. For instance. Example: import gevent from flask import copy_current_request_context @app. flask.copy_current_request_context(f ) A helper function that decorates a function to retain the current request context.username = username if remote_addr is None and has_request_context(): remote_addr = request. so you can change the value of this proxy by using the app_context() method.remote_addr = remote_addr Alternatively you can also just test any of the context bound objects (such as request or g for truthness): class User(db. username. See Notes On Proxies for more information.7..username = username if remote_addr is None and request: remote_addr = request. The moment the function is deco- rated a copy of the request context is created and then pushed when the function is called. remote_addr=None): self. This is useful when working with greenlets.Model): def __init__(self. want to support multiple applications running side by side.remote_addr self. but fail silently if it is unavailable. gevent. class User(db. flask. username.request like you # would otherwise in the view function.route('/') def index(): @copy_current_request_context def do_some_work(): # do some work here. remote_addr=None): self. This is a proxy..spawn(do_some_work) return 'Regular response' 226 . you may want to take advantage of request informa- tion if the request object is available. This is powered by the application context and not by the request context. it can access flask.Model): def __init__(self.has_request_context() If you have code that wants to test if a request context is there or not this function can be used.

New in version 0. The url_for function results in a BuildError when the current app does not have a URL for the given endpoint and values. error is the instance of BuildError. in context of original traceback. exc_type. New in version 0. and not for handling 404 NotFound errors. and endpoint and values are the argu- ments passed into url_for. If the value of a query argument is None. In case blueprints are active you can shortcut references to the same blueprint by prefixing the local endpoint with a dot (. flask. head over to the Quickstart.9. **values) Generates a URL to the given endpoint with the method provided. which can return a string to use as the result of url_for (instead of url_for‘s default to raise the BuildError exception) or re-raise the exception. flask. the current_app calls its url_build_error_handlers if it is not None." # This is an example of hooking the build_error_handler.).append(external_url_handler) Here.exc_info() if exc_value is error: raise exc_type.10. # Re-raise the BuildError. values): "Looks up an external URL when `url_for` cannot build a URL. When it does. **values) if url is None: # External lookup did not have a URL.url_build_error_handlers. You can also just do a boolean check on the current_app object instead. endpoint. Flask has a hook to intercept URL build errors through Flask. An example: def external_url_handler(error. return url app. tb else: raise error # url_for will use this result. instead of raising BuildError.has_app_context() Works like has_request_context() but for the application context. 227 . the whole pair is skipped.index') For more information. New in version 0. tb = sys. Note that this is for building URLs outside the current application.10: The _scheme parameter was added. exc_value.url_for(endpoint. This will reference the index function local to the current blueprint: url_for('. lookup_url is some utility function you've built # which looks up the endpoint in some external URL registry. Variable arguments that are unknown to the target endpoint are appended to the generated URL as query arguments. # Here. exc_value. url = lookup_url(endpoint.url_build_error_handlers. To integrate applications.

if it’s a WSGI application it will be raised in a proxy exception. defaults to 302.Response if un- specified.9: The _anchor and _method parameters were added. The _ex- ternal parameter must be set to True or a ValueError is raised. New in version 0. this also can be set to an empty string to build protocol-relative URLs. flask.10. Because views do not have to return response objects but can return a value that is converted 228 . flask. New in version 0. The rest of the arguments are forwarded to the exception constructor. an absolute URL is generated. • _method – if provided this explicitly specifies an HTTP method. flask. The default behavior uses the same scheme as the current re- quest. Server address can be changed via SERVER_NAME configuration variable which defaults to localhost. code=302. redirects the client to the target location. Parameters • location – the location the response should redirect to.make_response(*args) Sometimes it is necessary to set additional headers in a view. • _anchor – if provided this is added as anchor to the URL. or PREFERRED_URL_SCHEME from the app configuration if no request context is available. As of Werkzeug 0. if called. 305.6: The location can now be a unicode string that is encoded using the iri_to_uri() function.9: Calls Flask. • Response (class) – a Response class to use when instantiating a response. and 307. New in version 0. Supported codes are 301. New in version 0. 302. The default is werkzeug. Parameters • endpoint – the endpoint of the URL (name of the function) • values – the variable arguments of the URL rule • _external – if set to True. 303. • code – the redirect status code. Response=None) Returns a response object (a WSGI application) that.redirect(location.handle_build_error() on BuildError. If the first argument to the callable is an integer it will be looked up in the mapping. 300 is not supported because it’s not a real redirect and 304 because it’s the answer for a request with a request with defined If-Modified-Since headers.wrappers. • _scheme – a string specifying the desired URL scheme.abort() When passed a dict of code -> exception items it can be used as callable that raises exceptions.10: The class used for the Response object can now be passed in.

after_this_request(f ) Executes a function after this request. it creates a new response argument •if one argument is passed. flask.html'. This for example creates a response with a 404 error code: response = make_response(render_template('not_found.make_response() function as tuple.headers['X-Parachutes'] = 'parachutes are cool' return response This function accepts the very same arguments you can return from a view func- tion.6.html'). it becomes tricky to add headers to it.html'. This function can be called instead of using a return and you will get a response object which you can use to attach headers.Flask. Example: @app. 404) The other use case of this function is to force the return value of a view function into a response which is helpful with view decorators: response = make_response(view_function()) response. New in version 0. flask. •if more than one argument is passed. foo=42) You can now do something like this: def index(): response = make_response(render_template('index. This is useful to modify response objects.make_response() is invoked with it. the arguments are passed to the flask. into a response object by Flask itself. Flask.route('/') def index(): @after_this_request def add_header(response): response.headers['X-Parachutes'] = 'parachutes are cool' Internally this function does the following things: •if no arguments are passed. foo=42)) response. The function is passed the response object and has to return the same or a new one. If view looked like this and you want to add a new header: def index(): return render_template('index.headers['X-Foo'] = 'Parachute' return response return 'Hello World!' 229 .

9. Changed in version 0.12: The filename is no longer automatically inferred from file objects. you should use send_from_directory() instead. The default behavior is now to attach etags. this method will try to upgrade the response stream to support range requests. Parameters • filename_or_fp – the filename of the file to send in latin-1. ETags will also be attached automatically if a filename is provided. Please never pass filenames to this function from user sources.2. If conditional=True and filename is provided. If you want to use automatic mimetype and etag support. Alternatively you can set the application’s use_x_sendfile attribute to True to directly emit an X-Sendfile header. add_etags=True. For extra security you probably want to send certain files as at- tachment (HTML for instance). but you can also explicitly provide one. cache_timeout and conditional parameters were added. This will allow the request to be answered with partial content response. otherwise attach an etag yourself. as_attachment=False.9: cache_timeout pulls its default from application config. By default it will try to guess the mimetype for you. mimetype=None. last_modified=None) Sends the contents of a file to the client.7: mimetype guessing and etag support for file objects was deprecated because it was unreliable. con- ditional=False. This however requires support of the underlying webserver for X-Sendfile. This is more useful if a function other than the view function wants to modify a response. Changed in version 0. flask. Pass a filename if you are able to.send_file(filename_or_fp. This is relative to the root_path if a relative path is speci- fied. You can turn this off by setting add_etags=False. cache_timeout=None. By default it will try to use the WSGI server’s file_wrapper support. attach- ment_filename=None.0 Changed in version 0. New in version 0. This functionality will be removed in Flask 1. pass a filepath via filename_or_fp or attachment_filename. For instance think of a decorator that wants to add some headers without converting the return value into a response object. New in version 0.12: The attachment_filename is preferred over filename for MIME-type detection. The mimetype guessing requires a filename or an attachment_filename to be provided. This will use the most efficient method available and configured.5: The add_etags. Changed in version 0. New in version 0. when None. Alternatively a file object might be provided in which case X-Sendfile might not work and fall back to the traditional 230 .

send_from_directory(directory. this value is set by get_send_file_max_age() of current_app. New in version 0. • as_attachment – set to True if you want to send this file with a Content-Disposition: attachment header. method.5. • options – optional keyword arguments that are directly for- warded to send_file(). Parameters • directory – the directory where all the files are stored. filename. • filename – the filename relative to that directory to download. • attachment_filename – the filename for the attachment if it dif- fers from the file’s filename. • conditional – set to True to enable conditional responses. **options) Send a file from a given directory with send_file(). filename. auto detection happens as fallback. • add_etags – set to False to disable attaching of etags. 231 . • cache_timeout – the timeout in seconds for the headers. When None (default).config['UPLOAD_FOLDER']. a datetime or timestamp. This is a secure way to quickly expose static files from an upload folder or something similar. • last_modified – set the Last-Modified header to this value. Example usage: @app. this overrides its mtime. flask. If a file path is given. • mimetype – the mimetype of the file if provided. Make sure that the file pointer is positioned at the start of data to send before calling send_file(). If a file was passed. as_attachment=True) Sending files and Performance It is strongly recommended to activate either X-Sendfile support in your web- server or (if no authentication happens) to tell the webserver to serve files for the given path on its own without calling into the web application for improved performance. otherwise an error will be raised.route('/uploads/<path:filename>') def download_file(filename): return send_from_directory(app.

safe_join(directory.. *pathnames) Safely join directory and zero or more untrusted pathnames components. Raises NotFound if one or more passed paths fall out of its boundaries. Example usage: @app.escape(s) → markup Convert the characters &. The constructor of the Markup class can be used for three different things: When passed an unicode object it’s assumed to be safe. return '<a href="#">foo</a>' . >. otherwise the object passed is converted into a unicode string and then assumed to be safe: >>> Markup("Hello <em>World</em>!") Markup(u'Hello <em>World</em>!') >>> class Foo(object): .... 'rb') as fd: content = fd. The escape function returns markup objects so that double escaping can’t happen. Parameters • directory – the trusted base directory... Marks return value as markup string.. when passed an object with an HTML representation (has an __html__ method) that representation is used. filename) with open(filename.route('/wiki/<path:filename>') def wiki_page(filename): filename = safe_join(app. Markup is a direct subclass of unicode and pro- vides all the methods of unicode just that it escapes arguments passed and always returns Markup. and ” in string s to HTML-safe sequences. <. >>> Markup(Foo()) Markup(u'<a href="#">foo</a>') If you want object passed being always treated as unsafe you can use the escape() classmethod to create a Markup object: 232 .Markup Marks a string as being safe for inclusion in HTML/XML output without need- ing to be escaped.flask.read() # Read and process the file content.. Use this if you need to display text that might contain such characters in HTML. def __html__(self): . • pathnames – the untrusted pathnames relative to that directory. class flask. ‘. This implements the __html__ interface a couple of frame- works and web applications use. flask.config['WIKI_FOLDER'].

>>> Markup.escape("Hello <em>World</em>!")
Markup(u'Hello &lt;em&gt;World&lt;/em&gt;!')

Operations on a markup string are markup aware which means that all argu-
ments are passed through the escape() function:

>>> em = Markup("<em>%s</em>")
>>> em % "foo & bar"
Markup(u'<em>foo &amp; bar</em>')
>>> strong = Markup("<strong>%(text)s</strong>")
>>> strong % {'text': '<blink>hacker here</blink>'}
Markup(u'<strong>&lt;blink&gt;hacker here&lt;/blink&gt;</strong>')
>>> Markup("<em>Hello</em> ") + "<foo>"
Markup(u'<em>Hello</em> &lt;foo&gt;')

classmethod escape(s)
Escape the string. Works like escape() with the difference that for sub-
classes of Markup this function would return the correct subclass.
striptags()
Unescape markup into an text_type string and strip all tags. This also re-
solves known HTML4 and XHTML entities. Whitespace is normalized to
one:

>>> Markup("Main &raquo; <em>About</em>").striptags()
u'Main \xbb About'

unescape()
Unescape markup again into an text_type string. This also resolves known
HTML4 and XHTML entities:

>>> Markup("Main &raquo; <em>About</em>").unescape()
u'Main \xbb <em>About</em>'

23.10 Message Flashing

flask.flash(message, category=’message’)
Flashes a message to the next request. In order to remove the flashed mes-
sage from the session and to display it to the user, the template has to call
get_flashed_messages().
Changed in version 0.3: category parameter added.
Parameters
• message – the message to be flashed.
• category – the category for the message. The following values
are recommended: 'message' for any kind of message, 'error'

233

for errors, 'info' for information messages and 'warning' for
warnings. However any kind of string can be used as category.
flask.get_flashed_messages(with_categories=False, category_filter=[])
Pulls all flashed messages from the session and returns them. Further calls in the
same request to the function will return the same messages. By default just the
messages are returned, but when with_categories is set to True, the return value
will be a list of tuples in the form (category, message) instead.
Filter the flashed messages to one or more categories by providing those cate-
gories in category_filter. This allows rendering categories in separate html blocks.
The with_categories and category_filter arguments are distinct:
•with_categories controls whether categories are returned with message text
(True gives a tuple, where False gives just the message text).
•category_filter filters the messages down to only those matching the pro-
vided categories.
See Message Flashing for examples.
Changed in version 0.3: with_categories parameter added.
Changed in version 0.9: category_filter parameter added.
Parameters
• with_categories – set to True to also receive categories.
• category_filter – whitelist of categories to limit return values

23.11 JSON Support

Flask uses simplejson for the JSON implementation. Since simplejson is provided by
both the standard library as well as extension, Flask will try simplejson first and then
fall back to the stdlib json module. On top of that it will delegate access to the current
application’s JSON encoders and decoders for easier customization.
So for starters instead of doing:

try:
import simplejson as json
except ImportError:
import json

You can instead just do this:

from flask import json

For usage examples, read the json documentation in the standard library. The follow-
ing extensions are by default applied to the stdlib’s JSON module:
1. datetime objects are serialized as RFC 822 strings.

234

2. Any object with an __html__ method (like Markup) will have that method called
and then the return value is serialized as string.
The htmlsafe_dumps() function of this json module is also available as filter called
|tojson in Jinja2. Note that inside script tags no escaping must take place, so make
sure to disable escaping with |safe if you intend to use it inside script tags unless
you are using Flask 0.10 which implies that:

<script type=text/javascript>
doSomethingWith({{ user.username|tojson|safe }});
</script>

Auto-Sort JSON Keys
The configuration variable JSON_SORT_KEYS (Configuration Handling) can be set to false
to stop Flask from auto-sorting keys. By default sorting is enabled and outside of the
app context sorting is turned on.
Notice that disabling key sorting can cause issues when using content based HTTP
caches and Python’s hash randomization feature.

flask.json.jsonify(*args, **kwargs)
This function wraps dumps() to add a few enhancements that make life easier. It
turns the JSON output into a Response object with the applicationhttps://www.scribd.com/json mime-
type. For convenience, it also converts multiple arguments into an array or mul-
tiple keyword arguments into a dict. This means that both jsonify(1,2,3) and
jsonify([1,2,3]) serialize to [1,2,3].
For clarity, the JSON serialization behavior has the following differences from
dumps():
1.Single argument: Passed straight through to dumps().
2.Multiple arguments: Converted to an array before being passed to dumps().
3.Multiple keyword arguments: Converted to a dict before being passed to
dumps().
4.Both args and kwargs: Behavior undefined and will throw an exception.
Example usage:

from flask import jsonify

@app.route('/_get_current_user')
def get_current_user():
return jsonify(username=g.user.username,
email=g.user.email,
id=g.user.id)

This will send a JSON response like this to the browser:

235

{
"username": "admin",
"email": "admin@localhost",
"id": 42
}

Changed in version 0.11: Added support for serializing top-level arrays. This
introduces a security risk in ancient browsers. See JSON Security for details.
This function’s response will be pretty printed if it was not requested
with X-Requested-With: XMLHttpRequest to simplify debugging unless the
JSONIFY_PRETTYPRINT_REGULAR config parameter is set to false. Compressed (not
pretty) formatting currently means no indents and no spaces after separators.
New in version 0.2.
flask.json.dumps(obj, **kwargs)
Serialize obj to a JSON formatted str by using the application’s configured en-
coder (json_encoder) if there is an application on the stack.
This function can return unicode strings or ascii-only bytestrings by default
which coerce into unicode strings automatically. That behavior by default is
controlled by the JSON_AS_ASCII configuration variable and can be overridden
by the simplejson ensure_ascii parameter.
flask.json.dump(obj, fp, **kwargs)
Like dumps() but writes into a file object.
flask.json.loads(s, **kwargs)
Unserialize a JSON object from a string s by using the application’s configured
decoder (json_decoder) if there is an application on the stack.
flask.json.load(fp, **kwargs)
Like loads() but reads from a file object.
class flask.json.JSONEncoder(skipkeys=False, ensure_ascii=True,
check_circular=True, allow_nan=True,
sort_keys=False, indent=None, separators=None,
encoding=’utf-8’, default=None)
The default Flask JSON encoder. This one extends the default simplejson encoder
by also supporting datetime objects, UUID as well as Markup objects which are
serialized as RFC 822 datetime strings (same as the HTTP date format). In order
to support more data types override the default() method.
default(o)
Implement this method in a subclass such that it returns a serializable object
for o, or calls the base implementation (to raise a TypeError).
For example, to support arbitrary iterators, you could implement default
like this:

def default(self, o):
try:

236

iterable = iter(o)
except TypeError:
pass
else:
return list(iterable)
return JSONEncoder.default(self, o)

class flask.json.JSONDecoder(encoding=None, object_hook=None,
parse_float=None, parse_int=None,
parse_constant=None, strict=True, ob-
ject_pairs_hook=None)
The default JSON decoder. This one does not change the behavior from the de-
fault simplejson decoder. Consult the json documentation for more informa-
tion. This decoder is not only used for the load functions of this module but also
Request.

23.12 Template Rendering

flask.render_template(template_name_or_list, **context)
Renders a template from the template folder with the given context.
Parameters
• template_name_or_list – the name of the template to be ren-
dered, or an iterable with template names the first one existing
will be rendered
• context – the variables that should be available in the context
of the template.
flask.render_template_string(source, **context)
Renders a template from the given template source string with the given context.
Template variables will be autoescaped.
Parameters
• source – the source code of the template to be rendered
• context – the variables that should be available in the context
of the template.
flask.get_template_attribute(template_name, attribute)
Loads a macro (or variable) a template exports. This can be used to invoke a
macro from within Python code. If you for example have a template named
_cider.html with the following contents:

{% macro hello(name) %}Hello {{ name }}!{% endmacro %}

You can access this from Python code like this:

237

hello = get_template_attribute('_cider.html', 'hello')
return hello('World')

New in version 0.2.
Parameters
• template_name – the name of the template
• attribute – the name of the variable of macro to access

23.13 Configuration

class flask.Config(root_path, defaults=None)
Works exactly like a dict but provides ways to fill it from files or special dictio-
naries. There are two common patterns to populate the config.
Either you can fill the config from a config file:

app.config.from_pyfile('yourconfig.cfg')

Or alternatively you can define the configuration options in the module that calls
from_object() or provide an import path to a module that should be loaded.
It is also possible to tell it to use the same module and with that provide the
configuration values just before the call:

DEBUG = True
SECRET_KEY = 'development key'
app.config.from_object(__name__)

In both cases (loading from any Python file or loading from modules), only up-
percase keys are added to the config. This makes it possible to use lowercase
values in the config file for temporary values that are not added to the config or
to define the config keys in the same file that implements the application.
Probably the most interesting way to load configurations is from an environment
variable pointing to a file:

app.config.from_envvar('YOURAPPLICATION_SETTINGS')

In this case before launching the application you have to set this environment
variable to the file you want to use. On Linux and OS X use the export statement:

export YOURAPPLICATION_SETTINGS='/path/to/config/file'

On windows use set instead.
Parameters

238

An object can be of one of the following two types: •a string: in this case the object with that name will be imported •an actual object reference: that object is used directly Objects are usually either modules or classes. • silent – set to True if you want silent failure for missing files.config. from_object(obj) Updates the values from the given object. New in version 0. This can either be an absolute filename or a filename relative to the root path. **kwargs) Updates the config like update() ignoring items with non-upper keys.11.environ['YOURAPPLICATION_SETTINGS']) Parameters • variable_name – name of the environment variable • silent – set to True if you want silent failure for missing files. This is basically just a shortcut with nicer error messages for this line of code: app. from_json(filename. True if able to load config. Returns bool. from_object() loads only the uppercase attributes of the module/class. this is the appli- cation’s root_path. • root_path – path to which files are read relative from. silent=False) Updates the values in the config from a JSON file. When the config object is created by the application. silent=False) Loads a configuration from an environment variable pointing to a configu- ration file. New in version 0. Example of module-based configuration: 239 .from_pyfile(os. A dict object will not work with from_object() because the keys of a dict are not attributes of the dict class. False otherwise. This function behaves as if the JSON object was a dictionary and passed to the from_mapping() function.11. from_mapping(*mapping. Parameters • filename – the filename of the JSON file. • defaults – an optional dictionary of default values from_envvar(variable_name.

7: silent parameter.get_namespace('IMAGE_STORE_') The resulting dictionary image_store_config would look like: { 'type': 'fs'. 'path': '/var/apphttps://www.scribd.com/images'. Parameters • namespace – a configuration namespace • lowercase – a flag indicating if the keys of the resulting dic- tionary should be lowercase 240 .com' } This is often useful when configuration options map directly to keyword arguments in functions or class constructors.config['IMAGE_STORE_BASE_URL'] = 'http://img.config. trim_namespace=True) Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix. lowercase=True. Parameters • filename – the filename of the config. app. This can either be an absolute filename or a filename relative to the root path.from_object('yourapplication.website. See Development / Production for an example of class-based configuration using from_object(). 'base_url': 'http://img.config.website. This function behaves as if the file was imported as module with the from_object() function.config.from_object(default_config) You should not use this function to load the actual configuration but rather configuration defaults.default_config') from yourapplication import default_config app. New in version 0. The actual config should be loaded with from_pyfile() and ideally from a location not within the package because the package might be installed system wide.config['IMAGE_STORE_PATH'] = '/var/apphttps://www.scribd.com/images' app.config['IMAGE_STORE_TYPE'] = 'fs' app.com' image_store_config = app. Example usage: app. • silent – set to True if you want silent failure for missing files. get_namespace(namespace. silent=False) Updates the values in the config from a Python file. Parameters obj – an import name or object from_pyfile(filename.

8.route('/stream') def streamed_response(): def generate(): 241 . 23. The downside is that if you are using streamed responses.args['name'] yield '!' return Response(generate()) Alternatively it can also be used around a specific generator: from flask import stream_with_context.ext import foo New in version 0.ext This module acts as redirect import module to Flask extensions.route('/stream') def streamed_response(): @stream_with_context def generate(): yield 'Hello ' yield request.stream_with_context(generator_or_function) Request contexts disappear when the response is started on the server. If you want to use an extension named “Flask-Foo” you would import it from ext as follows: from flask.14 Extensions flask. Response @app. This is done for efficiency reasons and to make it less likely to encounter memory leaks with badly written WSGI middlewares. 23. request. It was added in 0.11. This function however can help you keep the context around for longer: from flask import stream_with_context. • trim_namespace – a flag indicating if the keys of the resulting dictionary should not include the namespace New in version 0. request. Response @app.8 as the canonical way to import Flask extensions and makes it possible for us to have more flexibility in how we distribute extensions.15 Stream Helpers flask. the generator cannot access request bound information any more.

Make sure to properly pop() the stack yourself in that situation. otherwise your unittests will leak memory. match_request() Can be overridden by a subclass to hook into the matching of the request._preserve_context' to True on the WSGI environment the context will not pop itself at the end of the request. it will evaluate all the functions registered on the application for teardown execution (teardown_request()).16 Useful Internals class flask. This is used by the test_client() for example to implement the deferred cleanup functionality. environ. copy() Creates a copy of this request context with the same request object. In debug mode the request context is kept around if exceptions happen so that interactive debuggers have a chance to introspect the data. Changed in version 0.4 this can also be forced for requests that did not fail and outside of DEBUG mode. Because the actual request object is the same this cannot be used to move a request context to a different thread unless access to the request object is locked.ctx.RequestContext(app. It will create the URL adapter and request object for the WSGI environment provided. Do not attempt to use this class directly.9: Added the exc argument. instead use test_request_context() and request_context() to create this object. The request context is automatically popped at the end of the request for you. 23. yield 'Hello ' yield request.args['name'] yield '!' return Response(stream_with_context(generate())) New in version 0. When the request context is popped.10. 242 .9. By setting 'flask. request=None) The request context contains all request relevant information. This will also trigger the execution of functions registered by the teardown_request() decorator. With 0. You might find this helpful for unittests where you need the information from the context local around for a little longer. New in version 0. It is created at the beginning of the request and pushed to the _request_ctx_stack and removed at the end of it. This can be used to move a request context to a different greenlet. pop(exc=<object object>) Pops the request context and unbinds it by doing that.

ctx. flashes an internal cache for the flashed messages. The application context is also implicitly created if a request context is created but the application is not on top of the individual application context. options._app_ctx_stack Works similar to the request context but only binds the application.g object. flask. New in version 0. push() Binds the request context to the current context. first_registration) Temporary holder object for registering a blueprint with the application. This is a documented instance and can be used by extensions and application code but the use is discouraged in general.9.AppContext(app) The application context binds an application object implicitly to the current thread or greenlet. g an object with all the attributes of the flask. pop(exc=<object object>) Pops the app context. app. similar to how the RequestContext binds request informa- tion. url_adapter the URL adapter that was used to match the request. push() Binds the app context to the current context. An in- stance of this class is created by the make_setup_state() method and later passed to all register callback functions.blueprints. session the active session object. flask. Example usage: from flask import _request_ctx_stack def get_session(): ctx = _request_ctx_stack.BlueprintSetupState(blueprint. class flask.session class flask. The following attributes are always present on each layer of the stack: app the active Flask application. This is mainly there for extensions to store data._request_ctx_stack The internal LocalStack that is used to implement all the context local objects used in Flask. request the current request object.top if ctx is not None: return ctx. 243 .

signals. This is the case when blinker is installed. app = None a reference to the current application blueprint = None a reference to the blueprint that created this setup state. The following signals exist in Flask: flask. context. url_prefix = None The prefix that should be used for all URLs defined on the blueprint.name or 'string template'. this attribute can be used to figure out if the blueprint was registered in the past already. The signal is in- voked with the instance of the template as template and the context as dictionary (named context). context) 244 .17 Signals New in version 0.debug('Rendering template "%s" with context %s'. options = None a dictionary with all options that were passed to the register_blueprint() method. first_registration = None as blueprints can be registered multiple times with the application and not everything wants to be registered multiple times on it. None otherwise. template. 23.signals_available True if the signaling system is available.template_rendered This signal is sent when a template was successfully rendered. Example subscriber: def log_template_renders(sender. add_url_rule(rule. **extra): sender. subdomain = None The subdomain that the blueprint should be active for. endpoint=None. **options) A helper method to register a rule (and optionally a view function) to the application.6.logger. url_defaults = None A dictionary with URL defaults that is added to each and every URL that was defined with the blueprint. template. The endpoint is automatically prefixed with the blueprint’s name. view_func=None.

Example subscriber: 245 . Example subscriber: def log_request(sender. It is sent before the standard exception handling kicks in and even in debug mode.connect(log_request.got_request_exception This signal is sent when an exception happens during request processing.connect(log_template_renders. response) from flask import request_finished request_finished. The signal is invoked with the instance of the template as template and the context as dictionary (named context). ' 'Response: %s'.debug('Request context is set up') from flask import request_started request_started. **extra): sender.request_finished This signal is sent right before the response is sent to the client. template. response. template. context) from flask import before_render_template before_render_template. Because the request context is already bound. app) flask. context. The exception itself is passed to the sub- scriber as exception. where no exception handling happens. app) flask. app) flask.before_render_template This signal is sent before template rendering process.connect(log_response.logger. **extra): sender.logger. Example subscriber: def log_template_renders(sender. It is passed the response to be sent named response.debug('Rendering template "%s" with context %s'.name or 'string template'. Example subscriber: def log_response(sender. the subscriber can access the request with the standard global proxies such as request. before any request process- ing happens.connect(log_template_renders. from flask import template_rendered template_rendered.request_started This signal is sent when the request context is set up.debug('Request context is about to close down.logger. **extra): sender. app) flask.

**extra): sender. even if an exception is caused.logger.appcontext_pushed This signal is sent when an application context is pushed. Currently functions listening to this signal are called after the regular teardown handlers. Example subscriber: def close_db_connection(sender. **extra): session. but this is not something you can rely on. flask. app) flask. flask.close() from flask import request_tearing_down request_tearing_down. The sender is the application.connect(log_exception. but this is not something you can rely on. user): def handler(sender.request_tearing_down This signal is sent when the request is tearing down.debug('Got exception during processing: %s'.9.close() from flask import appcontext_tearing_down appcontext_tearing_down. app) As of Flask 0. exception. Example subscriber: def close_db_connection(sender. exception) from flask import got_request_exception got_request_exception. For instance it can be used to set a resource early onto the g object. even if an exception is caused. **extra): session. Example usage: from contextlib import contextmanager from flask import appcontext_pushed @contextmanager def user_set(app. def log_exception(sender. This is usually useful for unittests in order to temporarily hook in information. this will also be passed an exc keyword argument that has a reference to the exception that caused the teardown if there was one. This is always called. This is always called. app) This will also be passed an exc keyword argument that has a reference to the exception that caused the teardown if there was one.appcontext_tearing_down This signal is sent when the app context is tearing down. **kwargs): 246 .connect(close_db_connection. Currently functions listening to this signal are called after the regular teardown handlers.connect(close_db_connection.

flask. class flask.10. app) New in version 0. 23. otherwise returns a fake signal that has a send method that will do nothing but will fail with a RuntimeError for all other operations. The sender is the application. message. g. category. flask. app): yield And in the testcode: def test_user_me(self): with user_set(app.data == 'username=john' New in version 0. New in version 0. 'john'): c = app.Namespace An alias for blinker.base. Example subscriber: recorded = [] def record(sender.View Alternative way to use view functions. otherwise a dummy class that creates fake signals.appcontext_popped This signal is sent when an application context is popped. **extra): recorded.18 Class-Based Views New in version 0.views. This class is available for Flask extensions that want to provide the same fallback system as Flask itself.test_client() resp = c. The messages is sent as message keyword argument and the category as category.10. including connecting. A subclass has to implement 247 . signal(name.connect(record.append((message. class signals. doc=None) Creates a new signal for this namespace if blinker is available. This usually falls in line with the appcontext_tearing_down signal.user = user with appcontext_pushed.connected_to(handler.get('/users/me') assert resp.message_flashed This signal is sent when the application is flashing a message.7.Namespace if blinker is available.10. category)) from flask import message_flashed message_flashed.

If methods is provided the methods do not have to be passed to the add_url_rule() method explicitly: class MyView(View): methods = ['GET'] def dispatch_request(self. dispatch_request() Subclasses have to override this method to implement the actual view func- tion code. You can place one or more decorators in this list and whenever the view function is created the result is automatically decorated.as_view('myview')) When you want to decorate a pluggable view you will have to either do that when the view function is created (by wrapping the return value of as_view()) or you can use the decorators attribute: class SecretView(View): methods = ['GET'] decorators = [superuser_required] def dispatch_request(self): .. Internally this generates a function on the fly which will in- stantiate the View on each request and call the dispatch_request() method on it. 248 . dispatch_request() which is called with the view arguments from the URL rout- ing system. name): return 'Hello %s!' % name app. The arguments passed to as_view() are forwarded to the constructor of the class. However since this moves parts of the logic from the class declaration to the place where it’s hooked into the routing system.8. methods = None A list of methods this view can handle. New in version 0. *class_args. Note that you can not use the class based decorators since those would decorate the view class and not the generated view function! classmethod as_view(name. This method is called with all the arguments from the URL rule. The decorators stored in the decorators list are applied one after another when the view function is created. decorators = () The canonical way to decorate class-based views is to decorate the return value of as_view().. view_func=MyView. **class_kwargs) Converts the class into an actual view function that can be used with the routing system.add_url_rule('/hello/<name>'.

0) + 1 return 'OK' app.url_map.as_view('counter')) 23. Also options is set for you automatically: class CounterAPI(MethodView): def get(self): return session. For instance if you implement a method called get() it means it will re- spond to 'GET' requests and the dispatch_request() implementation will auto- matically forward your request to that.19 URL Route Registrations Generally there are three ways to define rules for the routing system: 1. Here are some examples: @app. 2.Flask. Variable parts in the route can be specified with angular brackets (/user/<username>). The following converters are available: string accepts any text without a slash (the default) int accepts integers float like int but for floating point values path like the default but also accepts slashes any matches one of the items provided uuid accepts UUID strings Custom converters can be defined using flask.add_url_rule() function.route('/') def index(): pass 249 .get('counter'.get('counter'. By default a variable part in the URL accepts any string without a slash however a different converter can be specified as well by using <converter:name>.Flask. view_func=CounterAPI. You can use the flask.url_map.MethodView Like a regular class-based view but that dispatches requests to particular meth- ods. You can use the flask.views. 3.add_url_rule('/counter'. 0) def post(self): session['counter'] = session.class flask. Variable parts are passed to the view function as keyword arguments.route() decorator. You can directly access the underlying Werkzeug routing system which is ex- posed as flask.Flask.Flask.

The only difference is that with the route parameter the view function is defined with the decorator instead of the view_func parameter. the user is automatically redirected to the same page with a trailing slash attached.@app. Here are the parameters that route() and add_url_rule() accept.route('/users/page/<int:page>') def show_users(page): pass This specifies that /users/ will be the URL for page one and /users/page/N will be the URL for page N. defaults={'page': 1}) @app. Defaults can also be specified. You can also define multiple rules for the same function. 2. If a rule ends with a slash and is requested without a slash by the user. This is consistent with how web servers deal with static files. a 404 not found is raised. The idea is to keep each URL unique so the following rules apply: 1. This also makes it possi- ble to use relative link targets safely. Here for example is a definition for a URL that accepts an optional page: @app.route('/post/<int:post_id>') def show_post(post_id): pass An important detail to keep in mind is how Flask deals with trailing slashes. They have to be unique however. If a rule does not end with a trailing slash and the user requests the page with a trailing slash.route('/<username>') def show_user(username): pass @app.route('/users/'. 250 .

See the example above for how faults defaults work. Flask will look on the view function object itself if a methods attribute exists. If this is not provided one can specify the function later by storing it in the view_functions dictionary with the endpoint as key. Starting with Flask 0.specifies the rule for the subdomain in case subdomain matching is in use..the options to be forwarded to the underlying Rule object. not specified the default subdomain is assumed. OPTIONS is implicitly added and handled by the standard request handling. By default a rule just listens for GET (and implicitly HEAD). 23. Flask itself assumes that the name point of the view function is the name of the endpoint if not explicitly stated.). If it does. • methods: If methods are not provided when the URL rule is added.20 View Function Options For internal usage the view functions can have some attributes attached to customize behavior the view function would normally not have control over. sub. They have to be specified as keyword arguments. view_func the function to call when serving a request to the provided endpoint. rule the URL rule as string end. 251 .the endpoint for the registered URL rule. The following at- tributes can be provided optionally to either override some defaults to add_url_rule() or general behavior: • __name__: The name of a function is by default used as endpoint. • provide_automatic_options: if this attribute is set Flask will either force enable or disable the automatic implementation of the HTTP OPTIONS response. Flask will always add these methods when registering a URL rule even if the methods were explicitly overridden in the route() call.method == 'OPTIONS': # custom options handling here . methods is a list of methods this rule should be limited to (GET. Additionally this will be prefixed with the name of the blueprint by default which cannot be customized from the function itself. Full example: def index(): if request. de. If do. POST etc. If endpoint is provided explicitly this value is used. This can be useful when working with decorators that want to customize the OPTIONS response on a per-view basis. A change to tions Werkzeug is handling of method options. it will pull the information for the methods from there. • required_methods: if this attribute is set.6. main **op. A dictionary with defaults for this rule..

Parameters • add_default_commands – if this is True then the default run and shell commands wil be added. Not to be confused with FlaskGroup. command(*args. 23. add_version_option=True. create_app=None) Help object to deal with Flask applications. index) New in version 0. Group but it wraps callbacks in with_appcontext() unless it’s disabled by passing with_appcontext=False. • create_app – an optional callback that is passed the script info and returns the loaded app.21 Command Line Interface class flask. return 'Hello World!' index. commands=None.8: The provide_automatic_options functionality was added.AppGroup(name=None. **kwargs) This works exactly like the method of the same name on a regular click. Normally a developer does not have to interface with this class but there are some very advanced use cases for which it makes sense to create an instance of this.ScriptInfo(app_import_path=None. • add_version_option – adds the --version option. Group but it defaults the group class to AppGroup. class flask. For information as of why this is useful see Custom Scripts. 'OPTIONS'] app.methods = ['GET'.add_url_rule('/'.cli. **extra) Special subclass of the AppGroup group that supports loading more commands from the configured Flask app. create_app=None. In future versions of Flask this object will most likely play a bigger role.cli. **attrs) This works similar to a regular click Group but it changes the behavior of the command() decorator so that it automatically wraps the functions in with_appcontext(). group(*args.provide_automatic_options = False index. 252 . class flask. **kwargs) This works exactly like the method of the same name on a regular click.cli. This is usually not necessary to in- terface with as it’s used internally in the dispatching to click.FlaskGroup(add_default_commands=True. Typically it’s created au- tomatically by the FlaskGroup but you can also manually create it and pass it onwards as click object.

cli object then they are wrapped with this function by default unless it’s disabled. create_app = None Optionally a function that is passed the script info to create the instance of the application. 253 .with_appcontext(f ) Wraps a callback so that it’s guaranteed to be executed with the script’s applica- tion context.cli. The reloader and debugger are by default enabled if the debug flag of Flask is enabled and disabled otherwise.cli.core. This can be changed with the –with- threads option which will enable basic multithreading.cli.Command object> Runs an interactive Python shell in the context of a given Flask application.Command object> Runs a local development server for the Flask application.run_command = <click.core. If callbacks are registered directly to the app.cli. app_import_path = None Optionally the import path for the Flask application. flask. flask. data = None A dictionary with arbitrary data that can be associated with this script info. This local server is recommended for development purposes only but it can also be used for simple intranet deployments.shell_command = <click. This is useful for executing small snippets of management code without having to manually configuring the application. Calling this multiple times will just result in the already loaded app to be returned. flask. By default it will not support any sort of concurrency at all to simplify debugging. load_app() Loads the Flask app (if not yet loaded) and returns it.pass_script_info(f ) Marks a function so that an instance of ScriptInfo is passed as first argument to the click callback. flask. The application will populate the default namespace of this shell according to it’s configuration.

254 .

Part III ADDITIONAL NOTES Design notes. legal information and changelog are here for the interested. 255 .

256 .

When you want to test something 257 . In Flask this is an instance of the Flask class. There are ways to fake multiple applications with a single application object. like maintaining a stack of applications. The most important one is that implicit appli- cation objects require that there may only be one instance at the time. especially in direct comparison with other frameworks. this section is for you. This should give you an idea about some of the design decisions that may appear arbitrary and surprising at first. Now the question is: when does a microframework need more than one application at the same time? A good example for this is unittesting.1 The Explicit Application Object A Python web application based on WSGI has to have one central callable object that implements the actual application. Each Flask application has to create an instance of this class itself and pass it the name of the module. but this causes some problems I won’t outline here in detail.route('/') def index(): return 'Hello World!' Would look like this instead: from hypothetical_flask import route @route('/') def index(): return 'Hello World!' There are three major reasons for this. but why can’t Flask do that itself? Without such an explicit application object the following code: from flask import Flask app = Flask(__name__) @app. 24. CHAPTER TWENTYFOUR DESIGN DECISIONS IN FLASK If you are curious why Flask does certain things the way it does and not differently.

24. This means that you can declare routes in arbitrary order and they will still work as expected. If you want to apply a WSGI middleware. Another design decision with the Werkzeug routing system is that routes in Werkzeug try to ensure that URLs are unique.3 One Template Engine Flask decides on one template engine: Jinja2. The third reason is “explicit is better than implicit”. Another thing that becomes possible when you have an explicit object lying around in your code is that you can subclass the base class (Flask) to alter specific behavior. Now obviously there are frameworks around that do not need any configuration and will still be able to load templates relative to your application module.it can be very helpful to create a minimal application to test specific behavior. Why doesn’t Flask have a pluggable tem- plate engine interface? You can obviously use a different template engine. 24. Flask depends on that information to properly load resources relative to your module. That object is your WSGI ap- plication.2 The Routing System Flask uses the Werkzeug routing system which was designed to automatically order routes by complexity. With Python’s outstanding support for reflection it can then access the package to figure out where the templates and static files are stored (see open_resource()). Werkzeug will go quite far with that in that it will automatically redirect to a canonical URL if a route is ambiguous. But they have to use the current working directory for that. Whenever you create a Flask instance you usually pass it __name__ as package name. This is a requirement if you want to properly imple- ment decorator based routing since decorators could be fired in undefined order when the application is split into multiple modules. Furthermore this design makes it possible to use a factory function to create the appli- cation which is very helpful for unittesting and similar things (Application Factories). which is a very unreliable way to determine where the application is. The current working directory is process-wide and if you are running multiple applications in one process (which could happen in a webserver without you knowing) the paths will be off. you don’t have to remember anything else. just wrap it and you’re done (though there are better ways to do that so that you do not lose the reference to the application object wsgi_app()). Worse: many web- servers do not set the working directory to the directory of your application but to the document root which does not have to be the same folder. but Flask will still configure Jinja2 for you. While that limitation that Jinja2 is always configured 258 . But there is another very important reason why Flask depends on an explicit instantia- tion of that class: the package name. When the application object is deleted everything it allocated will be freed again. This would not be possible without hacks if the object were created ahead of time for you based on a class that is not exposed to you.

The development of WebOb and Werkzeug started side by side with similar ideas in mind: be a good implementation of WSGI for other applications to take advantage. Paste is still around but from my understanding it’s sort of deprecated in favour of WebOb. Just that it’s called Rack there. You can easily use your own templating language. packages with dependencies are no longer an issue and there are very few reasons against having libraries that depend on others. On the surface they all work the same: you tell the engine to evaluate a template with a set of variables and take the return value as string. 259 . When it comes to connecting a template engine with an application or framework there is more than just rendering templates. support for reusable blocks (macros) that can be used from inside templates and also from Python code. Jinja2 for example has an extensive filter sys- tem. but besides that it looks very much like a WSGI rendition for Ruby. Flask is a framework that takes advantage of the work already done by Werkzeug to properly interface WSGI (which can be a complex task at times). Furthermore extensions can then easily depend on one template language being present. but an extension could still depend on Jinja itself. For instance. But that’s about where similarities end. This Rack library has two equivalents in Python: WebOb (formerly Paste) and Werkzeug. supports iterative template rendering. Template engines are like programming languages and each of those engines has a certain understanding about how things work. But nearly all applications in Ruby land do not work with Rack directly. Why shouldn’t it? If we look over to the Ruby side of web development there we have a protocol very similar to WSGI.4 Micro with Dependencies Why does Flask call itself a microframework and yet it depends on two libraries (namely Werkzeug and Jinja2). A template abstraction layer that would not take the unique features of the template engines away is a science on its own and a too large undertaking for a microframework like Flask. configurable syntax and more. uses Unicode for all operations.will probably go away. template inheritance by taking the availability of XPath into account and more. Thanks to recent developments in the Python package infrastructure. a certain way to do template inheritance. Also it provides ways to access macros from Jinja2 templates. the decision to bundle one template engine and use that will not. Flask uses Jinja2’s extensive autoescaping support. 24. Mako on the other hand treats templates similar to Python modules. but on top of a library with the same name. On the other hand an engine like Genshi is based on XML stream evaluation.

24. Everything else is up to you or extensions. What Flask is Not Flask will never have a database layer. However Flask is just not designed for large applications or asynchronous servers. 260 . However not every application needs a SQL database.6 What Flask is. The idea of Flask is to build a good foundation for all applications.5 Thread Locals Flask uses thread local objects (context local objects in fact. they support greenlet con- texts as well) for request. Why is this the case? Because people have different preferences and requirements and Flask could not meet those if it would force any of this into the core. Flask wants to make it quick and easy to write a traditional web application. Why is that and isn’t that a bad idea? Yes it is usually not such a bright idea to use thread locals. They cause troubles for servers that are not based on the concept of threads and make large applications harder to maintain. Everything else is up for extensions.24. Also see the Becoming Big section of the documentation for some inspiration for larger applications based on Flask. It also binds to a few common standard library packages such as logging. The majority of web applications will need a template engine in some sort. Flask itself just bridges to Werkzeug to implement a proper WSGI application and to Jinja2 to handle templating. session and an extra object you can put your own things on (g). It will not have a form library or anything else in that direction.

Because there is much confusion about HTML and XHTML among developers. but Internet Ex- plorer refuses to read files with that MIME type. One of the most important causes of pain is XML’s draconian (strict and ruthless) er- ror handling. so that the HTML is cleaner and faster to load. few people do. When an XML parsing error is encountered. but they often come with a larger runtime overhead and are not as straightforward to use because they have to obey XML rules. however. So the valid XHTML was being treated as invalid HTML. barely any websites on the Internet are actual XHTML (which is HTML processed us- ing XML rules). However. This is likely because properly using XHTML can be quite painful. instead of attempting to recover from the error and display what it can. what really determines XHTML/HTML processing in browsers is the MIME type. However. Most of the (X)HTML generation on the web is based on non-XML template engines (such as Jinja. even if the document properly validates as XHTML. The XHTML spec states that XHTML must be served with the MIME type application/xhtml+xml. To properly work with XHTML. CHAPTER TWENTYFIVE HTML/XHTML FAQ The Flask documentation and example applications are using HTML5. One of them is Internet Explorer’s lack of proper XHTML support. The majority of users. They wrote an XHTML doctype at the top of the document and self-closed all the necessary tags (<br> becomes <br/> or <br></br> in XHTML). this document tries to answer some of the major ques- tions. assumed they were properly using XHTML. XHTML also changed the way JavaScript is used. pro- grammers have to use the namespaced DOM interface with the XHTML namespace 261 . the one used in Flask) which do not protect you from accidentally creating invalid XHTML. While it is relatively easy to configure Web servers to serve XHTML properly. There are XML based template en- gines.1 History of XHTML For a while. which as said before is often not set properly. You may no- tice that in many situations. the browser is supposed to show the user an ugly error message. it appeared that HTML was about to be replaced by XHTML. when end tags are optional they are not used. such as Kid and the popular Genshi. There are a couple of major reasons why this is the case. 25.

25. or WHATWG (which was formed by the major browser vendors Apple. as the XHTML 2 working group has been disbanded and HTML5 is being implemented by all major browser vendors. (XHTML 1. In 2007. Currently.3 HTML versus XHTML The following table gives you a quick overview of features available in HTML 4. browser vendors implemented the XHTML syntax over the syntax defined by the specification. based on existing browser behavior instead of unrealistic and backwards-incompatible specifi- cations. 25. it appears that XHTML is losing traction.) 262 . since people were using XHTML-like tags along the lines of <link />. as it was superseded by XHTML 1.2 History of HTML5 Development of the HTML5 specification was started in 2004 under the name “Web Applications 1.01. and Opera) with the goal of writing a new and improved HTML specification.0 is not included.to query for HTML elements. Mozilla.0” by the Web Hypertext Application Technology Working Group. known as HTML5.1 and HTML5.1 and the barely-used XHTML5. XHTML 1. For example. However. in HTML4 <title/Hello/ theoretically parses exactly the same as <title>Hello</title>. the specification was adopted as the basis of a new HTML specification under the umbrella of the W3C.

<thead>. It should not be used in new code. It is usually not supported by browsers. so long as they contain no whitespace or special characters (like <. others are actually specified.unlike XHTML. • Requiring boolean attributes to have a value. or <tfoot> tags. 3 XHTML 1.0 is the last XHTML standard that allows to be served as text/html for backwards com- patibility reasons. <th>. <td>. This means the following page in HTML5 is perfectly valid: <!doctype html> <title>Hello HTML5</title> 1 This is an obscure feature inherited from SGML. for reasons detailed above.01 XHTML1.1 HTML5 <tag/value/ == <tag>value</tag> 1 <br/> supported 2 <script/> supported should be served as text/html 3 should be served as application/xhtml+xml strict error handling inline SVG inline MathML <video> tag <audio> tag New semantic tags like <article> 25. >. <dt>. Some of these work because of the lenient error handling most browsers use when they encounter a markup error. or "). <dd>.4 What does “strict” mean? HTML5 has strictly defined parsing rules. <li>. missing end tags or unquoted attribute values). which simply states parsing should abort. <tbody>. but it also specifies exactly how a browser should react to parsing errors . The following constructs are optional in HTML5 by standard. • Quoting attributes. Some people are confused by apparently invalid syntax that still generates the expected results (for example. <tr>. but have to be supported by browsers: • Wrapping the document in an <html> tag • Wrapping header elements in <head> or the body elements in <body> • Closing the <p>. 263 . '. HTML4. 2 This is for compatibility with server code that generates XHTML for tags such as <br>.

• The <audio> and <video> tags provide a way to embed audio and video without complicated add-ons like QuickTime or Flash. Web Sockets. • Advanced JavaScript APIs like Web Storage. which supports a powerful drawing API. HTML5 is hard to beat. Dive Into HTML5. <dl> <dt>Key 1 <dd>Value 1 <dt>Key 2 <dd>Value 2 </dl> </div> 25. • The <canvas> tag. reducing the need for server-generated images to present data graphically. • Semantic elements like <article>. geolo- cation. so use caution. 264 . <header>. as well.<div class=header> <h1>Hello HTML5</h1> <p class=tagline>HTML5 is awesome </div> <ul class=nav> <li><a href=/index>Index</a> <li><a href=/downloads>Downloads</a> <li><a href=/about>About</a> </ul> <div class=body> <h2>HTML5 is probably the future</h2> <p> There might be some other things around but in terms of browser vendor support. Web Workers. and <time> that make con- tent easier to understand. • New form control types like <input type="date"> that allow user agents to make entering and validating values easier. A good guide to new features in HTML5 is Mark Pilgrim’s soon-to-be-published book.5 New technologies in HTML5 HTML5 adds many new features that make Web applications easier to write and to use. however. and offline applications. Not all of them are supported in browsers yet. Many other features have been added. <nav>.

• HTML5 adds several new features. • It has the support of most browser vendors behind it. including semantic tags and the long-awaited <audio> and <video> tags. • It is much easier to write.25. the answer is HTML5. To summarize the reasons given above: • Internet Explorer (which. and more compact. There are very few reasons to use XHTML consider- ing the latest developments in Web browsers. sadly. it is undoubtedly better to use HTML5 than XHTML. For most applications.6 What should be used? Currently. • Many JavaScript libraries also do not support XHTML. due to the more compli- cated namespacing API it requires. 265 . currently leads in market share) has poor sup- port for XHTML.

266 .

1 Cross-Site Scripting (XSS) Cross site scripting is the concept of injecting arbitrary HTML (and with it JavaScript) into the context of a website. Flask configures Jinja2 to automatically escape all values unless explicitly told other- wise. never do that. there is one thing it cannot protect you from: XSS by attribute injection. While Jinja2 can protect you from XSS issues by escaping HTML. use the Content-Disposition: attachment header to prevent that problem. This should rule out all XSS problems caused in templates. but there are a couple more you have to take care of yourself. an attacker could easily inject custom JavaScript handlers. For more information on that have a look at the Wikipedia article on Cross-Site Scripting. Some browsers are using content-type guessing based on the first few bytes so users could trick a browser to execute HTML. To counter this possible attack vector. be sure to always quote your attributes with either double or single quotes when using Jinja expressions in them: <a href="{{ href }}">the text</a> Why is this necessary? Because if you would not be doing that. • sending out textfiles from uploaded files. but there are still other places where you have to be careful: • generating HTML without the help of Jinja2 • calling Markup on data submitted by users • sending out HTML from uploaded files. Flask tries to solve a few of these things for you. For example an attacker could inject this piece of HTML+JavaScript: 267 . developers have to properly escape text so that it cannot include arbitrary HTML tags. CHAPTER TWENTYSIX SECURITY CONSIDERATIONS Web applications usually face all kinds of security problems and it’s very hard to get everything right. Another thing that is very important are unquoted attributes. To remedy this. 26.

How can you prevent that? Basically for each request that modifies content on the server you would have to either use a one-time token and store that in the cookie and also transmit it with the form data. so this behavior was changed and jsonify() now supports serializing arrays. But instead of showing the cookie to the user. when you sent POST requests to will delete a user’s profile (say http://example. their profiles would get deleted while they are looking at images of fluffy cats.10 and lower. Why does Flask not do that for you? The ideal place for this to happen is the form validation framework. If an attacker now creates a page that sends a post request to that page with some JavaScript they just have to trick some users to load that page and their profiles will end up being deleted. In combination with CSS injections the attacker might even make the element fill out the entire page so that the user would just have to have the mouse anywhere on the page to trigger the attack. Imagine you were to run Facebook with millions of concurrent users and someone would send out links to images of little kittens. If your authentication information is stored in cookies. 26.3 JSON Security In Flask 0. 26. 268 . When users would go to that page.com/user/delete). jsonify() did not serialize top-level arrays to JSON. Say you have a specific URL that. This is a very complex topic and I won’t outline it here in detail just mention what it is and how to theoretically prevent it. a good attacker might also execute any other JavaScript code. ECMAScript 5 closed this vulnerability.onmouseover=alert(document.cookie) When the user would then move with the mouse over the link. The state of “being logged in” is controlled by a cookie. the cookie would be presented to the user in an alert window. After receiving the data on the server again. If you don’t keep that in mind. Unfortunately that includes requests triggered by 3rd party sites. which does not exist in Flask. you have implicit state man- agement.2 Cross-Site Request Forgery (CSRF) Another big problem is CSRF. you would then have to compare the two tokens and ensure they are equal. This was because of a security vulnerability in ECMAScript 4. All of these browsers have other more serious vulnerabilities. some people might be able to trick your application’s users with social engineering to do stupid things without them knowing. and that cookie is sent with each request to a page. so only extremely old browsers are still vul- nerable.

If you don’t know Unicode so far. Not only these libraries. SQLAlchemy or your other ORM should take care of that. This part of the documentation just tries to cover the very basics so that you have a pleasant experience with Unicode related things. Some databases have a protocol that already transmits Unicode and if they do not. is totally Unicode based when it comes to text. Flask will do the encoding and setting of the appropriate headers for you. The same is true if you are talking to databases with the help of SQLAlchemy or a similar ORM system. are transmitted in an HTTP header. Not only the protocol. However HTML which is usually trans- mitted on top of HTTP supports a large variety of character sets and which ones are used. 269 . also the majority of web related Python libraries that deal with text. Positively Must Know About Unicode and Character Sets.1 Automatic Conversion Flask has a few assumptions about your application (which you can change of course) that give you basic and painless Unicode support: • the encoding for text on your website is UTF-8 • internally you will always use Unicode exclusively for text except for literal strings with only ASCII character points. CHAPTER TWENTYSEVEN UNICODE IN FLASK Flask. like Jinja2 and Werkzeug. also the system used to address doc- uments on servers (so called URIs or URLs). So what does this mean to you? HTTP is based on bytes. To not make this too complex Flask just assumes that if you are sending Unicode out you want it to be UTF-8 encoded. 27. you should probably read The Absolute Min- imum Every Software Developer Absolutely. • encoding and decoding happens whenever you are talking over a protocol that requires bytes to be transmitted.

encode() method: def write_file(filename. • Jinja is configured to decode the template files from UTF-8. 'r') as f: return f. So do yourself a favour and limit yourself to UTF-8 for text files as well. 'w') as f: f. charset='utf-8'): with open(filename.read().into the first or second line of your Python source file.27. Here the old problem that text files do not specify their encoding comes into play.4 Configuring Editors Most editors save as UTF-8 by default nowadays but in case your editor is not config- ured to do this you have to change it.x mean? • as long as you are using ASCII charpoints only (basically numbers. • if you need anything else than ASCII in a string you have to mark this string as Unicode string by prefixing it with a lowercase u. To tell the interpreter your encoding you can put the # -*. (like u'Hänsel und Gretel') • if you are using non-Unicode characters in your Python files you have to tell Python which encoding your file uses.3 Encoding and Decoding Yourself If you are talking with a filesystem or something that is not really based on Unicode you will have to ensure that you decode properly when working with Unicode inter- face.encode(charset)) 27. 27. Anyways. So make sure to tell your editor to save the file as UTF-8 there as well. some special characters of latin letters without umlauts or anything fancy) you can use regular string literals ('Hello World').2 The Golden Rule So the rule of thumb: if you are not dealing with binary data.write(contents. What does working with Unicode in Python 2. To load such a file with Unicode you can use the built-in str. I recommend UTF-8 for this pur- pose. work with Unicode. charset='utf-8'): with open(filename. So for example if you want to load a file on the filesystem and embed it into a Jinja2 template you will have to decode it from the encoding of that file. contents.decode(charset) To go from Unicode into a specific charset such as UTF-8 you can use the unicode.decode() method: def read_file(filename. Here some common ways to set your editor to 270 . Again.coding: utf-8 -*.

Select the “New Document/Default Directory” tab 3..store as UTF-8: • Vim: put set enc=utf-8 to your . Select “UTF-8 without BOM” as encoding It is also recommended to use the Unix newline format. you can select it in the same panel but this is not a requirement.. 271 .emacs file: (prefer-coding-system 'utf-8) (setq default-buffer-file-coding-system 'utf-8) • Notepad++: 1. Go to Settings -> Preferences .vimrc file. 2. • Emacs: either use an encoding cookie or put this into your .

272 .

Flask sets up a redirect package called flask.py files. CHAPTER TWENTYEIGHT FLASK EXTENSION DEVELOPMENT Flask. This is done to transition from the old namespace packages. Make sure to include the name “Flask” somewhere in that name and that you check the capitalization. 273 . This is a requirement because many people will use patterns like the Application Factories pattern to create their application as needed to aid unittests and to support multiple configurations. So for example if you plan to add support for a library named simplexml to Flask. being a microframework. often requires some repetitive steps to get a third party library working. Because of that it is crucial that your application supports that kind of behavior. you would name your extension’s package flask_simplexml. Because very often these steps could be abstracted to support multi- ple projects the Flask Extension Registry was created. This is how users can then register dependencies to your extension in their setup. Most importantly the extension must be shipped with a setup. If you want to create your own Flask extension for something that does not exist yet. Also the development checkout link should work so that people can easily install the development version into their virtualenv without having to download the library by hand. If you for instance have a package called flask_something users would import it as flask.1 Anatomy of an Extension Extensions are all located in a package called flask_something where “something” is the name of the library you want to bridge. The name of the actual extension (the human readable name) however would be some- thing like “Flask-SimpleXML”.something. 28.ext. See Extension Import Transition for more details.py file and registered on PyPI. this guide to extension development will help you get your extension running in no time and to feel like users would expect your extension to behave. But what do extensions look like themselves? An extension has to ensure that it works with multiple Flask application instances at once.ext where users should import the ex- tensions from.

MIT or more liberal license to be able to be enlisted in the Flask Extension Registry.2 “Hello Flaskext!” So let’s get started with creating such a Flask extension. license='BSD'. Keep in mind that the Flask Extension Registry is a moderated place and libraries will be reviewed upfront if they behave as required. zip_safe=False. First we create the following folder structure: flask-sqlite3/ flask_sqlite3. long_description=__doc__. author_email='your-email@example.py LICENSE README Here’s the contents of the most important files: 28.1 setup.com'. version='1.2. # if you would be using a package instead use packages instead # of py_modules: # packages=['flask_sqlite3']. description='Very short description'. 274 .py file which is used to install your Flask extension. include_package_data=True. The following contents are something you can work with: """ Flask-SQLite3 ------------- This is the description for that library """ from setuptools import setup setup( name='Flask-SQLite3'. 28. author='Your Name'. The extension we want to create here will provide very basic support for SQLite3.Flask extensions must be licensed under a BSD.py The next file that is absolutely required is the setup. url='http://example. py_modules=['flask_sqlite3'].com/flask-sqlite3/'.0'.

2. 'License :: OSI Approved :: BSD License'.2 flask_sqlite3. 275 . 'Topic :: Software Development :: Libraries :: Python Modules' ] ) That’s a lot of code but you can really just copy/paste that from existing extensions and adapt. 'Operating System :: OS Independent'. But how exactly should such an exten- sion look like? What are the best practices? Continue reading for some insight. So how does the extension know the name of the application object? Quite simple: you pass it to it. extra_args]) that initializes the extension for that application. There are two recommended ways for an extension to initialize: initialization functions: If your extension is called helloworld you might have a function called init_helloworld(app[. For an example look at how the OAuth exten- sion works: there is an OAuth object that provides some helper functions like OAuth.remote_app to create a reference to a remote application that uses OAuth. install_requires=[ 'Flask' ].py Now this is where your extension code goes. platforms='any'. 'Intended Audience :: Developers'. For example. 'Programming Language :: Python'. classes: Classes work mostly like initialization functions but can later be used to further change the behavior. It could attach before / after handlers etc. classifiers=[ 'Environment :: Web Environment'. consider an application that’s currently connecting to SQLite like the documentation suggests (Us- ing SQLite 3 with Flask). 28. 28.3 Initializing Extensions Many extensions will need some kind of initialization step. 'Topic :: Internet :: WWW/HTTP :: Dynamic Content'.

the _app_ctx_stack is the correct one. # Starting with Flask 0.sqlite3_db.connect(current_app.4 The Extension Code Here’s the contents of the flask_sqlite3.teardown_request(self.teardown) def connect(self): return sqlite3. # before that we need to use the _request_ctx_stack. 'sqlite3_db'): ctx. In that case. For the SQLite 3 extension we will use the class-based approach because it will provide users with an object that handles opening and closing database connections. ':memory:') # Use the newstyle teardown_appcontext if it's available.What to use depends on what you have in mind. try: from flask import _app_ctx_stack as stack except ImportError: from flask import _request_ctx_stack as stack class SQLite3(object): def __init__(self.close() @property 276 .9. app): app.top if hasattr(ctx. exception): ctx = stack.app = app if app is not None: self. What’s important about classes is that they encourage to be shared around on mod- ule level. # otherwise fall back to the request context if hasattr(app. 'teardown_appcontext'): app.init_app(app) def init_app(self. 28.config['SQLITE3_DATABASE']) def teardown(self. app=None): self.config. the object itself must not under any circumstances store any application specific state and must be shareable between different application.py for copy/paste: import sqlite3 from flask import current_app # Find the stack on which we want to store the database connection.teardown) else: app.teardown_appcontext(self.setdefault('SQLITE3_DATABASE'.

you can use the database in the same way: 277 .config.route('/') def show_all(): cur = db.top if ctx is not None: if not hasattr(ctx. Note that we’re falling back to the _request_ctx_stack. It will try to use the new- style app context handler and if it does not exist. if supplied.connect() return ctx. def connection(self): ctx = stack. falls back to the request context one. we add a connection property that on first access opens the database connection and stores it on the context. 2.cursor() cur. So why did we decide on a class-based approach here? Because using our extension looks something like this: from flask import Flask from flask_sqlite3 import SQLite3 app = Flask(__name__) app. 'sqlite3_db'): ctx. the init_app method attaches the teardown handler. Finally. Extensions should use the top context for stor- ing their own information with a sufficiently complex name.sqlite3_db So here’s what these lines of code do: 1. we define a connect method that opens a database connection. 3.sqlite3_db = self. The init_app method exists so that the SQLite3 object can be instantiated with- out requiring an app object.9 or later with the app context support. This method supports the factory pattern for cre- ating applications. The init_app will set the configuration for the database.execute(. The __init__ method takes an optional app object and. will call init_app.. Next.from_pyfile('the-config. Note here that we’re attaching our database connection to the top application context via _app_ctx_stack.top. In addition.cfg') db = SQLite3(app) You can then use the database from views like this: @app.top if the application is using an older version of Flask that does not support it.) Likewise if you are outside of a request but you are using Flask 0. de- faulting to an in memory database if no configuration is supplied. 4.connection.. This is also the recommended way to handling resources: fetch resources lazily the first time they are used.

the sqlite3_db connection is closed... During the teardown of a request.top. app = create_app('the-config. before every request.connection. 28. init_app does not assign app to self. a sqlite3_db variable is assigned to _app_ctx_stack.6 Teardown Behavior This is only relevant if you want to support Flask 0. the same connection to the sqlite3 database is accessible to anything that needs it for the duration of the request. 28. the init_app method is used to support the factory pattern for creating apps: db = Sqlite3() # Then later on. it must either use the current_app context local or change the API in a way that you can pass the application explicitly.5 Using _app_ctx_stack In the example above. This tells the extension: I am not interested in using multiple applications.init_app(app) Keep in mind that supporting this factory pattern for creating apps is required for approved flask extensions (described below).app_context(): cur = db. When the extension needs to find the current application and it does not have a refer- ence to it. this variable is accessible using the connection property of SQLite3.cursor() cur.execute(. it is recommended to fall back to _request_ctx_stack which is bound to a request. The following pattern is a good way to support both: 278 . Note on init_app As you noticed.with app.6 and older Due to the change in Flask 0. Additionally. If the _app_ctx_stack does not exist because the user uses an old version of Flask. This is intentional! Class based Flask extensions must only store the application on the object when the application was passed to the constructor.7 regarding functions that are run at the end of the request your extension will have to be extra careful there if it wants to continue to support older versions of Flask.) At the end of the with block the teardown handles will be executed automatically.cfg') db. By using this pattern. In a view function.

An approved Flask extension requires a maintainer.7 Learn from Others This documentation only touches the bare minimum for extension development. If you want your own extension to be approved you have to follow these guidelines: 0. it’s a very good idea to check out existing extensions on the Flask Extension Registry. because teardown functions are passed the exception and typically don’t return anything. And this can only work if collaboration happens early. An approved Flask extension must provide exactly one package or module named flask_extensionname. but also to avoid having multiple developers working on pretty much the same side by side. 279 .after_request(close_connection) Strictly speaking the above code is wrong. so introduce your project on the mailinglist.def close_connection(response): ctx = _request_ctx_stack.top ctx. If no main- tainer is available. it might be a very good idea to get some more input. Especially if you do something nobody before you did. Approved extensions are tested as part of Flask itself to ensure extensions do not break on new releases. In the event an extension author would like to move beyond the project. 28. give access to the Flask core team.teardown_request(close_connection) else: app. 'teardown_request'): app. 28.sqlite3_db. and let other developers give you a helping hand with designing the API.8 Approved Extensions Flask also has the concept of approved extensions. However because the return value is discarded this will just work assuming that the code in between does not touch the passed parameter. The best Flask extensions are extensions that share common idioms for the API. If you feel lost there is still the mailinglist and the IRC chan- nel to get some ideas for nice looking APIs. If you want to learn more.close() return response if hasattr(app. Remember: good API design is hard. These approved extensions are listed on the Flask Extension Registry and marked appropriately. the project should find a new maintainer including full source hosting transition and PyPI access. This not only to get an idea about what people might want to have from an extension. 1.

ext. An extension currently has to support Python 2. The flask. The extension must have documentation that uses one of the two Flask themes for Sphinx documentation. 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.py file.py file un- less a dependency cannot be met because it is not available on PyPI. The naming scheme for official extensions is Flask-ExtensionName or ExtensionName-Flask. As of Flask 0.8 introduced a redirect import system as a compatibility aid for app develop- ers: Importing flask. 3. For test suites invoked with make test the extension has to ensure that all dependencies for the test are installed automatically. 5. of the form flaskext. 7.py description (and thus the PyPI description) has to link to the doc- umentation. The test suite also has to be part of the distribution. 2. 10.foo.9 Extension Import Transition In early versions of Flask we recommended using namespace packages for Flask ex- tensions.py test.ext.foo in that order.foo compatibility alias is still in Flask 0. Flask 0. The setup. 4. If tests are invoked with python setup. 6. 8. most Flask extensions have transitioned to the new naming schema.11 but is now deprecated – you should use flask_foo. test dependencies can be specified in the setup.py test. 280 .foo for a long time.11. The zip_safe flag in the setup script must be set to False. 9.7 28. Approved extensions must define all their dependencies in the setup. even if the extension would be safe for zipping.foo would try flask_foo and flaskext.6 as well as Python 2. This turned out to be problematic in practice be- cause it meant that multiple flaskext packages coexist. Consequently we have rec- ommended to name extensions flask_foo over flaskext. The license must be BSD/MIT/WTFPL licensed. It must ship a testing suite that can either be invoked with make test or python setup. website (if there is one) and there must be a link to automatically install the development version (PackageName==dev).

name. or indent four spaces: this_is_a_very_long(function_call. align to the braces: this_is_a_very_long(function_call.that_returns_an_object_with_an_attribute MyModel. no exceptions. 'and even more') For lists or tuples with many items. including Flask. 'with many parameters') \ . 'with more items'. 'to come in this line'. 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.limit(10) If you break in a statement with parentheses or braces. CHAPTER TWENTYNINE POCOO STYLEGUIDE The Pocoo styleguide is the styleguide for all Pocoo Projects. 42. This styleguide is a requirement for Patches to Flask and a recommendation for Flask ex- tensions. continue and return state- ments. In general the Pocoo Styleguide closely follows PEP 8 with some small differences and extensions. 'with many parameters'.filter(MyModel. break immediately after the opening brace: items = [ 'this is the first'. Maximum line length: 79 characters with a soft limit for 84 if absolutely necessary. 'set of items'.1 General Layout Indentation: 4 real spaces. No tabs.scalar > 120) \ .order_by(MyModel.query. 23. Try to avoid too nested code by cleverly placing break. 'like this' ] 281 .desc()) \ . 29.

name): self.' % name class MyClass(object): """This is a simple docstring""" def __init__(self. Do not use too many blank lines to separate logical segments in code.g.2 Expressions and Statements General whitespace rules: • No whitespace for unary operators that are not words (e.name. Example: def hello(name): print 'Hello %s!' % name def goodbye(name): print 'See you %s. 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 with constant: 282 .: -. ~ etc.name = name def get_annoying_name(self): return self. everything else by one. Good: exp = -1.upper() + '!!!!111' 29.) as well on the inner side of parentheses. • Whitespace is placed between binary operators.Blank lines: Top level functions and classes are separated by two lines.05 value = (item_value / item_count) * offset / exp value = my_list[index] value = my_dict['key'] Bad: exp = .

Good: if method == 'md5': pass Bad: if 'md5' == method: pass Comparisons: • 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. rebind the builtin to a different name instead. If the function needs to access a shadowed builtin. Double underscores are reserved for mixin classes.real_name or x. On classes with keywords. trailing underscores are appended. with acronyms kept uppercase (HTTPWriter and not HttpWriter) • Variable names: lowercase_with_underscores • Method and function names: lowercase_with_underscores • Constants: UPPERCASE_WITH_UNDERSCORES • precompiled regular expressions: name_re Protected members are prefixed with a single underscore. Check for features. Clashes with builtins are allowed and must not be resolved by appending an underline to the variable name. C) instead of type(A) is C.3 Naming Conventions • Class names: CamelCase.username) 283 . do not foo instead) Negated containment checks: use foo not in bar instead of not foo in bar Instance checks: isinstance(a. but try to avoid instance checks in general. Function and method arguments: • class methods: cls as first parameter • instance methods: self as first parameter • lambdas for properties might have the first parameter replaced with x like in display_name = property(lambda x: x. 29.

:license: LICENSE_NAME. otherwise the text is on the same line as the opening quote and the triple quote that closes the string on its own line: def foo(): """This is a simple docstring""" def bar(): """This is a longer docstring with so much information in there that it spans three lines. Both are formatted with reStructured- Text. """ Module header: The module header consists of an utf-8 encoding declaration (if non ASCII letters are used. 29. If it’s just one line. """ Please keep in mind that proper copyrights and license files are a requirement for approved Flask extensions.4 Docstrings Docstring conventions: All docstrings are formatted with reStructuredText as under- stood by Sphinx. see LICENSE_FILE for more details. but it is recommended all the time) and a standard doc- string: # -*. If a comment is used to document an attribute.29. they are laid out differently.module ~~~~~~~~~~~~~~ A brief description goes here.5 Comments Rules for comments are similar to docstrings. In this case the closing triple quote is on its own line. the closing triple quote is on the same line as the opening. :copyright: (c) YEAR by AUTHOR. put a colon after the opening pound sign (#): class User(object): #: the name of the user as unicode string name = Column(String) #: the sha1 hash of the password + inline salt pw_hash = Column(String) 284 . Depending on the number of lines in the docstring.coding: utf-8 -*- """ package.

You should start using Python 3 for your next project. so encoding issues should not affect you.10 and Werkzeug 0. The majority of the upgrade work is in the lower-level libraries like Flask and Werkzeug. but there are a few things to be aware of. not the high-level application code.3 or higher.2 and older are not supported.9 were the first versions to introduce Python 3 support. This mainly affects WSGI middleware interacting with the WSGI environ data. 3. Flask 0. You need to use Python 3. 285 . CHAPTER THIRTY PYTHON 3 SUPPORT Flask. You should use the latest versions of all Flask-related packages. For example. its dependencies. Werkzeug wraps that information in high-level helpers. which complicates how low level code handles HTTP data. Python 3 changed how unicode and bytes are handled. and most Flask extensions support Python 3. all of the examples in the Flask repository work on both Python 2 and 3 and did not require a single line of code changed.

286 .

. etag generation or MIME-type guessing: response = send_file(open('/path/to/file. 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. the kind where you don’t have to change anything in your code to profit from a new release.1 Changes to send_file The filename is no longer automatically inferred from file-like objects.1 Version 0.txt' # Just pass the filepath directly response = send_file(fname) # Set the MIME-type and ETag explicitly response = send_file(open(fname). mimetype='text/plain') response..set_etag(. CHAPTER THIRTYONE UPGRADING TO NEWER RELEASES Flask itself is changing like any software is changing over time. This means that the following code will no longer automatically have X-Sendfile support.1. Use the pip command to upgrade your existing Flask installation by providing the --upgrade parameter: $ pip install --upgrade Flask 31.12 31.txt')) Any of the following is functionally equivalent: fname = '/path/to/file. 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. Most of the changes are the nice kind.) 287 .

This was unintended and plain wrong.11 is an odd release in the Flask release cycle because it was supposed to be the 1.set_etag(. If you have been tracking the master branch which was 1.# Set `attachment_filename` for MIME-type guessing # ETag still needs to be manually set response = send_file(open(fname). 31.2.1 Debugging Flask 0. the function fails if no filename information was provided. 31.. Now the inheritance hierarchy takes precedence and handlers for more specific exception classes are executed instead of more general ones. Instead the new LOGGER_HANDLER_POLICY configuration can be used to disable the default log handlers and custom log handlers can be set up. Trying to register a handler on an instance now raises ValueError.11 0. 288 . See Error handlers for specifics. The precedence of handlers used to be based on the decoration/call order of errorhandler() and register_error_handler().) The reason for this is that some file-like objects have a invalid or even misleading name attribute. However because there was such a long lead time up to the release we decided to push out a 0.2 Error handling The behavior of error handlers was changed. Note: There used to be a logic error allowing you to register handlers only for excep- tion instances. Silently swallowing errors in such cases was not a satisfying solution. attachment_filename=fname) response. Additionally the default of falling back to application/octet-stream has been re- stricted.0 release.11 removed the debug_log_format attribute from Flask applications. In case you did track the master branch you will notice that flask --app is removed now. respectively.2 Version 0.11 release first with some changes removed to make the transition easier.. 31. If Flask can’t guess one or the user didn’t provide one. You need to use the environment variable to specify an application.2.0 you might see some unexpected changes. and therefore was replaced with the intended behavior of registering handlers only using exception classes and HTTP error codes.

Flask also started storing the flask.ext.3 Version 0. 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. rv): if isinstance(rv. If you depend on the old behavior. The old form still works.exthook. rv) 289 . it’s now always a tuple in the form (response. 31. 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.10 is that the cookie serialization format changed from pickle to a specialized JSON format.response_class(*rv) return Flask. The old flask. you can add it easily by subclassing Flask: class TraditionalFlask(Flask): def make_response(self. tuple): return self.Flask.Flask.request_globals_class attribute was renamed to flask. headers) where at least one item has to be provided. 31.make_response(self.10 The biggest change going from 0. you should use flask_foo.2.4 Extension imports Extension imports of the form flask.3 Templating The render_template_string() function has changed to autoescape template vari- ables by default.g object on the application context instead of the request context. In order to not break people’s sessions it is possible to continue using the old session system by using the Flask-OldSessions extension.9 The behavior of returning tuples from a function was simplified. If you return a tuple it no longer defines the arguments for the response object you’re creating. but Flask will issue a flask. 31. 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.2. status.4 Version 0. This better matches the behavior of render_template().foo are deprecated. This change has been done in order to avoid the damage an attacker can do if the secret key is leaked.ExtDeprecationWarning for each extension you import the old way.app_ctx_globals_class.31. We also provide a migration utility called flask-ext-migrate that is supposed to automatically rewrite your imports for this.9 to 0.

8 Flask introduced a new session interface system. We internally spread a lot of deprecation warnings all over the place to make it easy to find pieces of code that it was unable to upgrade. 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. With that introduction we moved the implementation details for the session system into a new module called flask. Using the app context stack instead of the request context stack will make extensions more readily handle use cases outside of requests. 31.session the module that implements sessions and flask. the app context stack makes sense for extensions which connect to databases. For instance. We also noticed that there was a naming collision between flask. We strongly recommend that you hand review the generated patchfile and only apply the chunks that look good.7 did not trigger teardown handlers when the test client was used in a with statement. If you are using git as version control system for your project we recommend applying the patch with path -p1 < patchfile.session which is the global session object. Due to a bug in the test client Flask 0. 31. please con- sider changing to _app_ctx_stack if it makes sense for your extension. If you used the previously undocumented session support we urge you to upgrade. This was since fixed but might require some changes in your test suites if you relied on this behavior.If you maintain an extension that was using _request_ctx_stack before.5 Version 0. If invalid JSON data was submitted Flask will now raise a BadRequest exception in- stead of letting the default ValueError bubble up. The script scans your whole application and generates an unified diff with changes it assumes are safe to apply. However as this is an automated tool it won’t be able to find all use cases and it might miss some. sessions.7 In Flask 0.6 Version 0.diff and then using the interactive commit feature to only apply the chunks that look good. 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. To apply the upgrade script do the following: 290 .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.

py > patchfile.html. msysgit or ming32.html for a template file called templates/index. Old code: return send_file(my_file_object) return send_file(my_file_object) New code: 291 . If you get a deprecation warning. Check the manual of your version control system for more information. This was unreliable and caused issues for a few setups. Also source control systems like svn.py 2. Previously if you had a folder named templates next to a blueprint named admin the implicit template path automatically was admin/index. If you were using per-module template folders you need to move some templates around. Additionally the send_file() function is now issuing deprecation warnings if you depend on functionality that will be removed in Flask 0.html. In order to see the deprecation warnings that might be emitted you have to enabled them with the warnings module. If you caught these exceptions with AttributeError before.11. Apply the patch: patch -p1 < patchfile.7.diff 3. you should catch them with RuntimeError now.6. This no longer is the case. 1. hg or git have builtin support for applying unified diffs as generated by the tool. Download the script: flask-07-upgrade. 31. Now you need to name the template templates/admin/index. Previously it was possible to use etags and mimetypes when file objects were passed.diff 5. If you are working with windows and you lack the patch command line utility you can get it as part of various Unix runtime environments for windows including cygwin. Review the generated patchfile. Run it in the directory of your application: python flask-07-upgrade.1 Bug in Request Locals Due to a bug in earlier implementations the request local proxies now raise a RuntimeError instead of an AttributeError when they are unbound. The tool will not detect this so you will have to do that on your own. make sure to update your application to work with either filenames there or disable etag attaching and attach them yourself. Please note that deprecation warnings are disabled by default starting with Python 2. 4.

This makes it now a lot easier to write unit tests as you can prevent closing down of database connections for a while.close() On the upside this change greatly improves the internal code flow and makes it easier to customize the dispatching and error handling.3 Manual Error Handler Attaching While it is still possible to attach error handlers to Flask.after_request def after_request(response): g. In general we no longer recommend custom error handler attaching via assignments to the underlying dictionary due to the more complex internal handling to support arbitrary exception classes and blueprints. 'db'): g.test_client() as client: resp = client.6. 292 .db. but for things that absolutely must happen at the end of request we introduced the new teardown_request() decorator. See Flask. It’s not consistently skipped if exceptions happen whereas previously it might have been called twice to ensure it is executed at the end of the request.errorhandler() for more information.teardown_request def after_request(exception): if hasattr(g.db.return send_file(my_file_object.2 Upgrading to new Teardown Handling We streamlined the behavior of the callbacks for request handling. You can take advantage of the fact that the teardown callbacks are called when the re- sponse context is removed from the stack so a test can query the database after request handling: with app.db is still bound if there is such a thing # and here it's gone 31.6.close() return response You are now encouraged to use this instead: @app. For things that modify the response the after_request() decorators continue to work as expected.get('/') # g. If you have database connection code that looks like this: @app. add_etags=False) 31.error_handlers it’s discour- aged to do so and in fact deprecated. Unfortunately that change also made after-request work differently under error conditions.

The upgrade script tries to guess that name but it might fail as this information could change at runtime. Now it means “relative to current module”. They will also no longer automatically export templates from a folder called templates next to their loca- tion however but it can be enabled from the constructor. (Note that register_error_handler() is new in Flask 0. handle_error) Alternatively you should just attach the function with a decorator: @app.. 293 . Flask will restore the previous behavior as good as possible. What changed? • Blueprints need explicit names.register_error_handler(403.4 Blueprint Support Blueprints replace the previous concept of “Modules” in Flask. • Blueprints have an inverse behavior for url_for(). Same with static files: if you want to continue serving static files you need to tell the constructor explic- itly the path to the static folder (which can be relative to the blueprint’s module path).error_handlers[403] = handle_error Into this: app. However we strongly recommend upgrading to the new blueprints as they provide a lot of useful improvement such as the ability to attach a blueprint multiple times. This means that you need to add another subfolder with the blueprint’s name into that folder if you want blueprintname/template. • Blueprints do not automatically provide static folders. If you continue to use the Module object which is deprecated. Modules had an automatic name guessing scheme where the shortname for the module was taken from the last part of the import module. • Rendering templates was simplified. They provide better semantics for various features and work better with large applications.7) 31. Now the blueprints can provide template folders which are added to a general template searchpath.html as the template name. The script will inverse all calls to url_for() automatically for you.. It will do this in a very eager way so you might end up with some unnecessary leading dots in your code if you’re not using modules.6.foo told url_for() that it should look for the endpoint foo on the application. The update script provided should be able to upgrade your applications automatically. Previously .errorhandler(403) def handle_error(e): .The proper upgrade is to change this: app. blueprint specific error handlers and a lot more. but there might be some cases where it fails to upgrade.

The following changes may be relevant to your application: • autoescaping no longer happens for all templates. and that extension has a unittest-mode you might want to link the activation of that mode to the new TESTING flag. This change was made so that Flask behaves more like people expected it to work and how other systems handle request pre.9 Version 0. Removing support for this makes the Flask internal code easier to understand and fixes a couple of small issues that make debugging harder than necessary. now they are called in reverse order.htm. 31. Another change that breaks backwards compatibility is that context processors will no longer override values passed directly to the template rendering function.8 Version 0. If you want to customize the Jinja loader now.5 Flask 0. 294 .xml and .4 For application developers there are no changes that require changes in your code. Previously they were called in the order of the registration.5 is the first release that comes as a Python package instead of a single mod- ule. the default context processor will not override it with the current request object.6 Flask 0.xhtml. In case you are developing on a Flask extension however. . Instead it is configured to only happen on files ending with . If for example request is as variable passed directly to the template. .and post- processing.6 comes with a backwards incompatible change which affects the order of after- request handlers. use the create_jinja_environment() method instead. This makes it easier to extend context processors later to inject additional variables without breaking existing template not expecting them. There were a couple of internal refactoring so if you depend on undocumented internal details you probably have to adapt the imports. If you depend on the order of execution of post-request functions.31. This functionality might come back in future releases if there is demand for this feature. • Flask no longer supports zipped applications in this release. If you have templates with different extensions you should override the select_jinja_autoescape() method.html. • The create_jinja_loader function is gone.7 Version 0. be sure to change the order. 31.

3 Categories for Flash Messages Flash messages can now have categories attached. If you run your application in production and want to profit from automatic error logging.3 Flask 0. How this works is outlined in Configuration Handling. This is an opt-in feature because it requires some rethinking in the code.10 Version 0. 31. Read all about that in the Message Flashing pattern. (Which most likely is the case for any application out there). All these are features that are 100% backwards compatible but you might want to take advantage of them. instead you can just load a configuration into the config object. you might be interested in attaching a proper log handler. warnings or regular messages differently for example.3 introduces configuration support and logging as well as categories for flash- ing messages.10.31. If you previously had code like this: app.10. Also you can start logging warnings and errors into the logger when appropriately. This makes it possible to render errors.debug = DEBUG app. For more information on that. 31.secret_key = SECRET_KEY You no longer have to do that.1 Configuration Support The configuration support makes it easier to write any kind of application that requires some sort of configuration. 295 .2 Logging Integration Flask now configures a logger for you with some basic and useful defaults.10. 31. read Application Errors.

296 .

32. • Correctly invoke response handlers for both regular request dispatching as well as error handlers.test_client includes preset default environment. CHAPTER THIRTYTWO FLASK CHANGELOG Here you can see the full list of changes between each Flask release.1 Version 0.11. • the cli command now responds to –version. instead of per client. as per issue #104.get.12 Released on December 21st 2016.2 Version 0.join (pull re- quest #1730). See pull request #1849. which can now be di- rectly set.2 Bugfix release. • Mimetype guessing in send_file now fails loudly and doesn’t fall back to application/octet-stream. codename Punsch. • Disable logger propagation by default for the app logger. See pull request #1988. • Add support for range requests in send_file. unreleased • Fix crash when running under PyPy3. • Make flask. see pull request #1814. • Revert a behavior change that made the dev server crash instead of returning a Internal Server Error (pull request #2006).path. • app. • Mimetype guessing and ETag generation for file-like objects in send_file has been removed. 297 .safe_join able to join multiple paths like os. 32.

Flask. • Added flask. This is recommended over the old flask. • Error handlers that match specific classes are now checked first.run() method as it works faster and more reliable due to a different design and also replaces Flask-Script. If set to True a permanent session will be refreshed each request and get their lifetime extended. exceptions). • Added before_render_template signal.py from working. released on June 7th 2016. • Added SESSION_REFRESH_EACH_REQUEST config key that controls the set-cookie behavior. • Added support to serializing top-level arrays to flask.Config. Non permanent sessions are not affected by this and will al- ways expire if the browser window closes.config_class. See pull request #1872. thereby allow- ing catching exceptions that are subclasses of HTTP exceptions (in werkzeug. • Added support for returning tuples in the form (response.4 Version 0. • Added flask. • Made Flask support custom JSON mimetypes for incoming data.3’s namespace loader.test_client_class.32. codename Absinthe.test_client() to support passing additional keyword arguments to the constructor of flask. • Added flask and the flask. 32. This makes it possible for an extension author to create exceptions 298 .cli module to start the local debug server through the click CLI system.Flask.11. See JSON Security for details.Config. • Added **kwargs to flask.11 Released on May 29th 2016.jsonify(). • Templates are no longer automatically reloaded outside of debug mode.3 Version 0.1 Bugfix release. • Fixed a bug that prevented FLASK_APP=foobar/__init__. • Added flask. This intro- duces a security risk in ancient browsers.3’s namespace pack- ages.Test. This can be configured with the new TEMPLATES_AUTO_RELOAD config key. • Added support for explicit root paths when using Python 3.from_json().get_namespace(). headers) from a view function. if set to False it will only be modified if the session actually modifies. • Added a workaround for a limitation in Python 3.

• send_from_directory now raises BadRequest if the filename is invalid on the server OS (pull request #1763). • Deprecated request. • flask. that will by default result in the HTTP error of their choosing. Re- duces JSON response size when JSONIFY_PRETTYPRINT_REGULAR=False by removing unnecessary white space included by default after separators. but may be caught with a custom error handler if desired. • Removed deprecated module functionality. See https://github.get_json(). 299 .com/kennethreitz/ httpbin/issues/168 • The automatically provided OPTIONS method is now correctly disabled if the user registered an overriding rule with the lowercase-version options (issue #1288).json. • Exceptions during teardown handling will no longer leave bad application con- texts lingering around. • Turn on autoescape for flask. • flask.g now has pop() and setdefault methods. • Enforce blueprint handling in the order they were registered for template load- ing. because it is a convention that UNIX text files end with a newline and some clients don’t deal well when this newline is missing.date type (pull request #1326). • Ported test suite to py.json in favour of request. • Don’t leak exception info of already catched exceptions to context teardown han- dlers (pull request #1393). • Added the EXPLAIN_TEMPLATE_LOADING config flag which when enabled will in- struct Flask to explain how it locates templates.Config.com/pallets/flask/pull/ 1262 – this came up originally as a part of https://github. • Add “pretty” and “compressed” separators definitions in jsonify() method. • flask.ext is now deprecated (pull request #1484). • Added flask.templating. • Allow custom Jinja environment subclasses (pull request #1422). This should help users debug when the wrong templates are loaded.test.jsonify now supports the datetime. • JSON responses are now terminated with a newline character. The log format is now hardcoded but the default log handling can be disabled through the LOGGER_HANDLER_POLICY configuration key. • Flask will now log by default even if debug is disabled. • Added the JSONIFY_MIMETYPE configuration variable (pull request #1728).render_template_string by default (pull request #1515).from_mapping().

• Fixed Python 3 bug when a handler from app. Now it’s possible to use that filter in single quoted attributes. This should make using that filter with angular. • Fixed an issue with query parameters getting removed from requests in the test client when absolute URLs were requested.10. release date to be announced) • Fixed broken test_appcontext_signals() test case. 32.7 Version 0. • Added support for byte strings back to the session system. 300 .5 Version 0.10 Released on June 13th 2013. • Fixed an etags bug when sending a file streams with a name.js easier.10.1 (bugfix release. • Fixed an issue causing exceptions raised before entering a request or app context to be passed to teardown handlers. released on June 14th 2013) • Fixed an issue where |tojson was not quoting single quotes which made the filter not work properly in HTML attributes. • Fixed an issue where registering the same method twice for the same endpoint would trigger an exception incorrectly. 32. codename Limoncello.6 Version 0.url_build_error_handlers reraises the BuildError.find_package() with a useful mes- sage explaining why it is raised when a PEP 302 import hook is used without an is_package() method. • Changed logic of before first request handlers to flip the flag after invoking.helpers.32. This will allow some uses that are potentially dangerous but should probably be per- mitted. • Fixed send_from_directory not expanding to the application root path correctly. • Raise an AttributeError in flask. • Made @before_first_request into a decorator as intended. This broke compati- bility with the common case of people putting binary data for token verification into the session.2 (bugfix release.

This allows much easier customization of how JSON is handled by Flask or any Flask extension. session and g objects will not be available and blueprint’s context processors are not called. app_ctx_globals_class which is a better name to what it does since 0. • flask.• Changed default cookie serialization format from pickle to JSON to limit the impact an attacker can do if the secret key leaks.g is now stored on the app context instead of the request context.10. • tojson used in templates is now safe by default due. • Added template_global methods in addition to the already existing template_filter method family.g now can be used with the in operator to see what’s defined and it now is iterable and will yield all attributes stored. session and g are now also added as proxies to the template context which makes them available in imported templates.dumps to return bytestrings by default. • request.Flask. • Added an option to generate non-ascii encoded JSON which should result in less bytes being transmitted over the network. • Removed deprecated internal flask. • The config object is now available to the template as a real global and not through a context processor which makes it available even in imported templates by de- fault.sessions instead to get the session module. • flask. 301 . • Added wrapper module around simplejson and added default serialization of datetime objects. • flask.g now gained a get() method for not erroring out on non existing items.session module alias.request_globals_class got renamed to flask.json.10 for more infor- mation. • tojson filter now does not escape script blocks in HTML5 parsers.session the session proxy. • flask. See Version 0. • Added template_test methods in addition to the already existing template_filter method family. The behavior is slightly different as the request.Flask. • Templates can now be rendered without request context. Use flask. It’s disabled by default to not cause confusion with existing libraries that might expect flask. • Set the content-length header for x-sendfile. One has to be very careful with those though because usage outside of macros might cause caching. This was allowed due to the different escaping behavior. • Flask will now raise an error if you attempt to register a new function on an already used endpoint. This is not to be confused with flask.

• Request context preservation in debug mode now keeps the exception informa- tion around which means that teardown handlers are able to distinguish error from success cases. • The flask.7 now to prepare for Python 3. • Python requirements changed: requiring Python 2. 32.8 Version 0. • Flask now orders JSON keys by default to not trash HTTP caches due to different hash seeds between different workers. • Removed custom JSON HTTP exception subclasses. • Added message_flashed signal that simplifies flashing testing. • Added support for copying of request contexts for better working with greenlets. • Logger now only returns the debug log setting if it was not set explicitly. • Changed how the teardown system is informed about exceptions.9 Released on July 1st 2012. • Changed logic for picking defaults for cookie values from sessions to work better with Google Chrome. • Added appcontext_pushed and appcontext_popped signals. • Flask will no longer invoke the wrong error handlers if a proxy exception is passed through.url_for() function now can also explicitly generate URL rules spe- cific to a given HTTP method. • The flask.get_json() as a replacement for the old flask.3 port. 302 . If you were relying on them you can reintroduce them again yourself trivially.on_json_loading_failed() now returns a JSON formatted response by default. Using them however is strongly discouraged as the interface was flawed. • Added flask. This is now more reliable in case something handles an exception halfway through the error handling process. codename Campari.6 or 2.request. • Added a workaround for chrome’s cookies in localhost not working as intended with domain names. • Added the JSONIFY_PRETTYPRINT_REGULAR configuration variable. • The builtin run method now takes the SERVER_NAME into account when picking the default port to run on.Request.json prop- erty.url_for() function now can generate anchors to the generated links. • The flask.request.

• Unregister a circular dependency between the WSGI environment and the re-
quest object when shutting down the request. This means that environ werkzeug.
request will be None after the response was returned to the WSGI server but has
the advantage that the garbage collector is not needed on CPython to tear down
the request unless the user created circular dependencies themselves.
• Session is now stored after callbacks so that if the session payload is stored in the
session you can still modify it in an after request callback.
• The flask.Flask class will avoid importing the provided import name if it can
(the required first parameter), to benefit tools which build Flask instances pro-
grammatically. The Flask class will fall back to using import on systems with
custom module hooks, e.g. Google App Engine, or when the import name is
inside a zip archive (usually a .egg) prior to Python 2.7.
• Blueprints now have a decorator to add custom template filters application wide,
flask.Blueprint.app_template_filter().
• The Flask and Blueprint classes now have a non-decorator method for adding
custom template filters application wide, flask.Flask.add_template_filter()
and flask.Blueprint.add_app_template_filter().
• The flask.get_flashed_messages() function now allows rendering flashed mes-
sage categories in separate blocks, through a category_filter argument.
• The flask.Flask.run() method now accepts None for host and port arguments,
using default values when None. This allows for calling run using configuration
values, e.g. app.run(app.config.get('MYHOST'), app.config.get('MYPORT')),
with proper behavior whether or not a config file is provided.
• The flask.render_template() method now accepts a either an iterable of tem-
plate names or a single template name. Previously, it only accepted a single
template name. On an iterable, the first template found is rendered.
• Added flask.Flask.app_context() which works very similar to the request con-
text but only provides access to the current application. This also adds support
for URL generation without an active request context.
• View functions can now return a tuple with the first instance being an instance
of flask.Response. This allows for returning jsonify(error="error msg"), 400
from a view function.
• Flask and Blueprint now provide a get_send_file_max_age() hook for sub-
classes to override behavior of serving static files from Flask when using
flask.Flask.send_static_file() (used for the default static file handler) and
send_file(). This hook is provided a filename, which for example allows chang-
ing cache controls by file extension. The default max-age for send_file and static
files can be configured through a new SEND_FILE_MAX_AGE_DEFAULT configuration
variable, which is used in the default get_send_file_max_age implementation.
• Fixed an assumption in sessions implementation which could break message
flashing on sessions implementations which use external storage.

303

• Changed the behavior of tuple return values from functions. They are no longer
arguments to the response object, they now have a defined meaning.
• Added flask.Flask.request_globals_class to allow a specific class to be used
on creation of the g instance of each request.
• Added required_methods attribute to view functions to force-add methods on reg-
istration.
• Added flask.after_this_request().
• Added flask.stream_with_context() and the ability to push contexts multiple
times without producing unexpected behavior.

32.9 Version 0.8.1

Bugfix release, released on July 1st 2012
• Fixed an issue with the undocumented flask.session module to not work properly
on Python 2.5. It should not be used but did cause some problems for package
managers.

32.10 Version 0.8

Released on September 29th 2011, codename Rakija
• Refactored session support into a session interface so that the implementation of
the sessions can be changed without having to override the Flask class.
• Empty session cookies are now deleted properly automatically.
• View functions can now opt out of getting the automatic OPTIONS implementa-
tion.
• HTTP exceptions and Bad Request errors can now be trapped so that they show
up normally in the traceback.
• Flask in debug mode is now detecting some common problems and tries to warn
you about them.
• Flask in debug mode will now complain with an assertion error if a view was
attached after the first request was handled. This gives earlier feedback when
users forget to import view code ahead of time.
• Added the ability to register callbacks that are only triggered once at the begin-
ning of the first request. (Flask.before_first_request())
• Malformed JSON data will now trigger a bad request HTTP exception instead
of a value error which usually would result in a 500 internal server error if not
handled. This is a backwards incompatible change.

304

• Applications now not only have a root path where the resources and modules are
located but also an instance path which is the designated place to drop files that
are modified at runtime (uploads etc.). Also this is conceptually only instance de-
pending and outside version control so it’s the perfect place to put configuration
files etc. For more information see Instance Folders.
• Added the APPLICATION_ROOT configuration variable.
• Implemented session_transaction() to easily modify sessions from the test en-
vironment.
• Refactored test client internally. The APPLICATION_ROOT configuration variable as
well as SERVER_NAME are now properly used by the test client as defaults.
• Added flask.views.View.decorators to support simpler decorating of plug-
gable (class-based) views.
• Fixed an issue where the test client if used with the “with” statement did not
trigger the execution of the teardown handlers.
• Added finer control over the session cookie parameters.
• HEAD requests to a method view now automatically dispatch to the get method
if no handler was implemented.
• Implemented the virtual flask.ext package to import extensions from.
• The context preservation on exceptions is now an integral component of Flask
itself and no longer of the test client. This cleaned up some internal logic and
lowers the odds of runaway request contexts in unittests.

32.11 Version 0.7.3

Bugfix release, release date to be decided
• Fixed the Jinja2 environment’s list_templates method not returning the correct
names when blueprints or modules were involved.

32.12 Version 0.7.2

Bugfix release, released on July 6th 2011
• Fixed an issue with URL processors not properly working on blueprints.

32.13 Version 0.7.1

Bugfix release, released on June 29th 2011
• Added missing future import that broke 2.5 compatibility.

305

• Fixed an infinite redirect issue with blueprints.

32.14 Version 0.7

Released on June 28th 2011, codename Grappa
• Added make_default_options_response() which can be used by subclasses to
alter the default behavior for OPTIONS responses.
• Unbound locals now raise a proper RuntimeError instead of an AttributeError.
• Mimetype guessing and etag support based on file objects is now deprecated for
flask.send_file() because it was unreliable. Pass filenames instead or attach
your own etags and provide a proper mimetype by hand.
• Static file handling for modules now requires the name of the static folder to
be supplied explicitly. The previous autodetection was not reliable and caused
issues on Google’s App Engine. Until 1.0 the old behavior will continue to work
but issue dependency warnings.
• fixed a problem for Flask to run on jython.
• added a PROPAGATE_EXCEPTIONS configuration variable that can be used to flip
the setting of exception propagation which previously was linked to DEBUG alone
and is now linked to either DEBUG or TESTING.
• Flask no longer internally depends on rules being added through the add_url_rule
function and can now also accept regular werkzeug rules added to the url map.
• Added an endpoint method to the flask application object which allows one to
register a callback to an arbitrary endpoint with a decorator.
• Use Last-Modified for static file sending instead of Date which was incorrectly
introduced in 0.6.
• Added create_jinja_loader to override the loader creation process.
• Implemented a silent flag for config.from_pyfile.
• Added teardown_request decorator, for functions that should run at the end of
a request regardless of whether an exception occurred. Also the behavior for
after_request was changed. It’s now no longer executed when an exception is
raised. See Upgrading to new Teardown Handling
• Implemented flask.has_request_context()
• Deprecated init_jinja_globals. Override the create_jinja_environment() method
instead to achieve the same functionality.
• Added flask.safe_join()
• The automatic JSON request data unpacking now looks at the charset mimetype
parameter.

306

• Don’t modify the session on flask.get_flashed_messages() if there are no mes-
sages in the session.
• before_request handlers are now able to abort requests with errors.
• it is not possible to define user exception handlers. That way you can provide
custom error messages from a central hub for certain errors that might occur dur-
ing request processing (for instance database connection errors, timeouts from
remote resources etc.).
• Blueprints can provide blueprint specific error handlers.
• Implemented generic Pluggable Views (class-based views).

32.15 Version 0.6.1

Bugfix release, released on December 31st 2010
• Fixed an issue where the default OPTIONS response was not exposing all valid
methods in the Allow header.
• Jinja2 template loading syntax now allows ”./” in front of a template load path.
Previously this caused issues with module setups.
• Fixed an issue where the subdomain setting for modules was ignored for the
static folder.
• Fixed a security problem that allowed clients to download arbitrary files if the
host server was a windows based operating system and the client uses back-
slashes to escape the directory the files where exposed from.

32.16 Version 0.6

Released on July 27th 2010, codename Whisky
• after request functions are now called in reverse order of registration.
• OPTIONS is now automatically implemented by Flask unless the application
explicitly adds ‘OPTIONS’ as method to the URL rule. In this case no automatic
OPTIONS handling kicks in.
• static rules are now even in place if there is no static folder for the module. This
was implemented to aid GAE which will remove the static folder if it’s part of a
mapping in the .yml file.
• the config is now available in the templates as config.
• context processors will no longer override values passed directly to the render
function.
• added the ability to limit the incoming request data with the new
MAX_CONTENT_LENGTH configuration value.

307

• the endpoint for the flask.Module.add_url_rule() method is now optional to
be consistent with the function of the same name on the application object.
• added a flask.make_response() function that simplifies creating response object
instances in views.
• added signalling support based on blinker. This feature is currently optional and
supposed to be used by extensions and applications. If you want to use it, make
sure to have blinker installed.
• refactored the way URL adapters are created. This process is now fully customiz-
able with the create_url_adapter() method.
• modules can now register for a subdomain instead of just an URL prefix. This
makes it possible to bind a whole module to a configurable subdomain.

32.17 Version 0.5.2

Bugfix Release, released on July 15th 2010
• fixed another issue with loading templates from directories when modules were
used.

32.18 Version 0.5.1

Bugfix Release, released on July 6th 2010
• fixes an issue with template loading from directories when modules where used.

32.19 Version 0.5

Released on July 6th 2010, codename Calvados
• fixed a bug with subdomains that was caused by the inability to specify the
server name. The server name can now be set with the SERVER_NAME config key.
This key is now also used to set the session cookie cross-subdomain wide.
• autoescaping is no longer active for all templates. Instead it is only active for .
html, .htm, .xml and .xhtml. Inside templates this behavior can be changed with
the autoescape tag.
• refactored Flask internally. It now consists of more than a single file.
• flask.send_file() now emits etags and has the ability to do conditional re-
sponses builtin.
• (temporarily) dropped support for zipped applications. This was a rarely used
feature and led to some confusing behavior.

308

• added support for context binding that does not require the use of the with state- ment for playing in the console. • after_request() handlers are now also invoked if the request dies with an ex- ception and an error handling page kicks in.Handler and will log request handling exceptions to that logger when not in debug mode.3. • added support for per-package template and static-file directories.from_envvar() • removed some unused code from flask • release does no longer include development leftover files (. • test client has not the ability to preserve the request context for a little longer. built documentation in zip and pdf file and some .1 Bugfix release.3 Released on May 28th 2010.22 Version 0. This makes it possible to receive mails on server errors for example. 32. • added a helper function to expose files from any directory. • removed support for create_jinja_loader which is no longer used in 0.pyc files) 32. This can also be used to trigger custom requests that do not pop the request stack for testing. codename Schnaps • added support for categories for flashed messages. • because the Python standard library caches loggers. • the logger switches to DEBUG mode now if debug is enabled. • added TESTING switch that can activate unittesting helpers.4 Released on June 18th 2010. 309 . released on May 28th 2010 • fixed a error reporting bug with flask. • the application now configures a logging.20 Version 0. the name of the logger is configurable now to better support unittests.Config.5 due to the improved module support.21 Version 0. codename Rakia • added the ability to register application wide error handlers from modules. 32.git folder for themes.

• added support for Google Appengine. • added support for send_file() • module support and internal request handling refactoring to better support pluggable applications.0. codename Jägermeister • various bugfixes • integrated JSON support • added get_template_attribute() helper function.2 Released on May 12th 2010. • server listens on 127. • the request context is now available within the with statement making it possible to further push the request context or pop it. • sessions can be set to be permanent now on a per-session basis. • refactored internal request dispatching. • added support for configurations.0. 32.23 Version 0. 310 . • add_url_rule() can now also register a view function. • better error reporting on missing secret keys.1 First public preview release. 32.24 Version 0.1 by default now to fix issues with chrome. • added external URL support.

It basically means: do whatever you want with it as long as the copyright in Flask sticks around.1.1.1 Authors Flask is written and maintained by Armin Ronacher and various contributors: 33. 33. the conditions are not modified and the disclaimer is present. The full license text can be found below (Flask License). Furthermore you must not use the names of the authors to promote derivatives of the software without written consent.2 Patches and Suggestions • Adam Zapletal • Ali Afshar • Chris Edgemon • Chris Grindstaff • Christopher Grebs • Daniel Neuhäuser • Dan Sully • David Lord @davidism • Edmond Burnett • Florent Xicluna 311 . CHAPTER THIRTYTHREE LICENSE Flask is licensed under a three clause BSD License. For the documentation and artwork different licenses apply.1 Development Lead • Armin Ronacher <armin.com> 33.ronacher@active-4.

3 Flask License Copyright (c) 2015 by Armin Ronacher and contributors.2 General License Definitions The following section contains the full license texts for Flask and the documentation. • The “Flask Artwork License” applies to the project’s Horn-Logo. • “AUTHORS” hereby refers to all the authors listed in the Authors section. See AUTHORS for more details. with or without modification. are permitted provided that the following conditions are met: 312 . Some rights reserved. • Georg Brandl • Jeff Widman @jeffwidman • Justin Quick • Kenneth Reitz • Keyan Pishdadian • Marian Sigler • Martijn Pieters • Matt Campell • Matthew Frazier • Michael van Tellingen • Ron DuPlain • Sebastien Estienne • Simon Sapin • Stephane Wirtel • Thomas Schranz • Zhao Xiaohong 33. • The “Flask License” applies to all the source code shipped as part of Flask (Flask itself as well as the examples and the unittests) as well as documentation. Redistribution and use in source and binary forms of the software as well as docu- mentation. 33.

INDIRECT. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.pocoo. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE AND DOCUMENTATION.4 Flask Artwork License Copyright (c) 2010 by Armin Ronacher. EXEMPLARY. BUT NOT LIMITED TO. THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DIS- CLAIMED. INCIDENTAL. • The names of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission. DATA. 313 . LOSS OF USE. Note: we would appreciate that you make the image a link to http://flask. This logo or a modified version may be used by anyone to refer to the Flask project. STRICT LIABILITY. OR CONSEQUENTIAL DAMAGES (INCLUDING.) of the image. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT. • Redistributions in binary form must reproduce the above copyright notice. INCLUDING. 33. PRO- CUREMENT OF SUBSTITUTE GOODS OR SERVICES. THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WAR- RANTIES. BUT NOT LIMITED TO. Some rights reserved.org/ if you use it on a web page. this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. with or without modification. but does not indicate endorsement by the project. Redistribution and use in source (the SVG file) and binary forms (rendered PNG files etc. this list of conditions and the following disclaimer. OR PROFITS. • The names of the contributors to the Flask software (see AUTHORS) may not be used to endorse or promote products derived from this software without specific prior written permission. WHETHER IN CONTRACT. OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY. SPECIAL. are permitted provided that the fol- lowing conditions are met: • Redistributions of source code must retain the above copyright notice and this list of conditions. • Redistributions of source code must retain the above copyright notice.

Blueprint method). 192 B after_request_funcs (flask. 243 tribute). 212 method).Flask method). 243 191 appcontext_popped (in module flask).BlueprintSetupState before_app_request() (flask.Flask method). 247 add_url_rule() (flask.cli. 213 app_context() (flask.Blueprint method). 229 (flask. 248 method).Flask attribute).Blueprint method). 213 add_app_template_test() (flask.Blueprint method).Blueprint method).Blueprint method).Flask method).blueprints.Flask at- _app_ctx_stack (in module flask). 193 314 .cli). method).views.Blueprint method).Blueprint method). 217 192 before_app_first_request() after_this_request() (in module flask).ScriptInfo at- abort() (in module flask).Blueprint method). 243 args (flask. 252 add_app_template_filter() app_template_filter() (flask. 190 method).Blueprint method). 252 method).Blueprint attribute).Flask app_context_processor() (flask. 216 add_url_rule() (flask. 213 add_template_global() (flask.Blueprint (flask. appcontext_pushed (in module flask).Request attribute). 243 app_errorhandler() (flask. 246 212 appcontext_tearing_down (in module add_url_rule() flask). base_url (flask.Flask app_url_defaults() (flask. 213 A app_import_path (flask.Flask app_url_value_preprocessor() method).Flask method). 192 before_first_request() (flask. 212 before_first_request_funcs (flask. 191 as_view() (flask. 193 method). 212 method).blueprints. AppContext (class in flask. 213 add_template_filter() (flask.Blueprint (flask. 246 (flask.ctx).Request attribute). 212 auto_find_instance_path() (flask. 213 app (flask. 213 add_app_template_global() app_template_global() (flask. 228 tribute). 193 212 after_request() (flask. 191 (flask. INDEX Symbols app_ctx_globals_class (flask. 192 _request_ctx_stack (in module flask).BlueprintSetupState AppGroup (class in flask. 213 add_template_test() (flask. 212 method).Blueprint method). 244 method).Flask after_request() (flask.View class after_app_request() (flask.Flask at- tribute).Blueprint app_template_test() (flask.

views. 232 create_global_jinja_loader() (flask. 189 data (flask. 193 command() (flask.Flask blueprints (flask. copy_current_request_context() (in mod. 189 data (flask.Blueprint method).Flask method). 233 D Flask (class in flask).Flask at.cli. 213 config (flask. 217 flask. 224 248 FlaskGroup (class in flask. Blueprint (class in flask). 194 endpoint() (flask. 32 194 YOURAPPLICATION_SETTINGS. static method). 196 method). 193 (flask.SecureCookieSessionInterface before_request_funcs (flask. 218 Config (class in flask).cli. 238 endpoint() (flask.ScriptInfo attribute).View attribute).JSONEncoder FLASKR_SETTINGS. 225 attribute).RequestContext method). first_registration 194 (flask.Flask method). 34 context_processor() (flask. 195 213 digest_method() before_request() (flask. FLASKR_SETTINGS.cli). 218 do_teardown_appcontext() (flask.Request attribute). 244 method). 253 flask (module).json).Flask attribute).Request attribute). 34 decorators (flask.View attribute).Flask attribute).blueprints).Flask method). 195 BlueprintSetupState (class in do_teardown_request() (flask.views. 236 form (flask. copy() (flask.testing).ctx.AppGroup method). FlaskClient (class in flask. default_config (flask.sessions. 243 method). 68 cookies (flask.Flask attribute).Flask attribute). 223 tribute).Flask flask.Flask method). 252 default() (flask. 234 debug (flask.Blueprint method). 214 ule flask).before_request() (flask. 195 dump() (in module flask. 212 195 blueprint (flask. 233 253 escape() (in module flask). 194 FLASK_DEBUG.json.Flask attribute).Blueprint method).BlueprintSetupState current_app (in module flask). 194 create_jinja_environment() (flask.Request attribute). escape() (flask.BlueprintSetupState dispatch_request() (flask.Flask extensions (flask. 193 dispatch_request() (flask. 193 method). 241 data (flask.Flask attribute).json). 248 blueprint (flask. 195 config_class (flask.blueprints.Flask attribute).ScriptInfo attribute). 236 cli (flask.Request attribute).blueprints.Request attribute). E 252 endpoint (flask.Flask attribute).Request attribute). 194 environ (flask. 196 create_app (flask.json (module).Request attribute). 194 files (flask. 236 C dumps() (in module flask. 244 flash() (in module flask).Flask method). 220 flask.ext (in module flask). 216 315 . 217 context_processor() (flask.Response attribute). 195 242 errorhandler() (flask. 226 errorhandler() (flask.Markup class method).cli. 32 method).Flask F method).Blueprint environment variable method).Flask method). 213 FLASK_DEBUG. 216 error_handler_spec (flask. 217 create_url_adapter() (flask.

json).Flask attribute).Flask 214 method).Flask attribute).Flask method).SecureCookieSessionInterface attribute).Config method).Flask method). 214 g (in module flask). 239 handle_user_exception() (flask.Flask from_json() (flask.SessionInterface is_json (flask. full_path (flask. 239 handle_http_exception() (flask.sessions. 218 method).Request attribute). 236 group() (flask.json). 217 226 has_static_folder (flask. 222 is_xhr (flask.Response attribute).Flask attribute). 225 has_static_folder (flask. get_cookie_domain() 198 (flask.SessionInterface method).Flask attribute). 222 198 get_cookie_secure() instance_path (flask.Flask method). 199 got_request_exception (in module flask).sessions.Flask from_pyfile() (flask. 197 from_object() (flask. get_send_file_max_age() (flask.Request method).SessionInterface inject_url_defaults() (flask. 223 316 .Flask attribute). json_decoder (flask.Request attribute). 197 has_request_context() (in module flask). 237 245 JSONEncoder (class in flask.Config method).Flask has_app_context() (in module flask).from_envvar() (flask.Flask attribute).Request attribute). 198 197 json_encoder (flask. iter_blueprints() (flask.SessionInterface (flask. get_send_file_max_age() (flask. 222 headers (flask. 197 jinja_loader (flask.AppGroup method). 239 method).SessionInterface headers (flask.Request attribute).sessions.Flask 239 method). 217 get_flashed_messages() (in module flask). 197 from_mapping() (flask.sessions. jinja_env (flask. 214 jinja_loader (flask.Config method). 198 240 jinja_environment (flask.cli. get_cookie_path() 198 (flask.json).Config method).Request attribute). 237 json (flask.Flask method). 235 H K handle_exception() (flask. 217 method).sessions. method).sessions. 198 234 get_json() (flask. 198 (flask. 240 method). handle_url_build_error() (flask.sessions.Flask attribute).Config method). 198 get_template_attribute() (in module jinja_options (flask.Config method).Blueprint 198 method).Blueprint attribute). 222 is_null_session() get_expiration_time() (flask. 252 jsonify() (in module flask.Flask attribute). 222 init_jinja_globals() (flask. key_derivation 197 (flask. 198 flask). 218 got_first_request (flask.Blueprint at- G tribute). JSONDecoder (class in flask. 219 get_cookie_httponly() (flask. 222 method). 227 method). 198 full_dispatch_request() (flask.SessionInterface I method). 218 J get_namespace() (flask.Flask attribute).

sessions. 236 NullSession (class in flask.Request attribute).sessions).cli.json).Flask method).Flask logger_name (flask. 232 attribute). 223 load_app() (flask. 220 (flask. 200 253 make_response() (in module flask).session attribute). 201 (flask. modified (flask.AppContext method).blueprints. 214 permanent (flask.session attribute). 244 method). 253 O loads() (in module flask. 242 attribute). 218 pop() (flask.SessionMixin at- Python Enhancement Proposals tribute). 222 make_null_session() options (flask. 202 N push() (flask. 199 open_instance_resource() (flask. 199 open_session() make_null_session() (flask.RequestContext method).L attribute).Request attribute).session attribute).Flask method). 228 path (flask. 218 tribute).RequestContext new (flask.sessions.cli).ctx. 200 push() (flask.ctx.AppContext method).sessions.sessions. 243 tribute).Flask method).Blueprint permanent (flask. 218 logger (flask. (flask. 217 preprocess_request() (flask. M 214 make_config() (flask. 236 on_json_loading_failed() (flask. 221 process_response() (flask.RequestContext (flask. 200 open_resource() (flask. 201 MethodView (class in flask.Flask attribute).SessionInterface method). 220 method).SessionInterface 199 method). 242 new (flask. 248 preserve_context_on_exception mimetype (flask.SessionMixin make_shell_context() (flask. 199 method). 224 PEP 8. message_flashed (in module flask). 243 name (flask.Flask method).sessions. 248 method). 201 match_request() pickle_based (flask.SessionMixin at- 201 tribute).ctx. 222 P make_response() (flask. 200 make_default_options_response() open_session() (flask.ctx. 222 max_content_length (flask. 201 modified (flask. 200 permanent_session_lifetime (flask. 217 make_setup_state() (flask.Flask methods (flask.Flask method). 281 null_session_class (flask. 199 open_resource() (flask.views).Blueprint method). 247 242 method (flask.Flask method).Request attribute). 199 method).ctx.Flask Markup (class in flask).views.BlueprintSetupState (flask.View attribute).Flask attribute). pass_script_info() (in module flask. 221 method).Request at- pop() (flask.Request log_exception() (flask.sessions. 224 method).Flask attribute).SessionInterface 317 .Flask attribute). 223 propagate_exceptions (flask.Flask attribute).Flask at- module (flask. 222 load() (in module flask.ScriptInfo method).json).Flask method).SessionInterface attribute).sessions.Response attribute).Flask method).

Blueprint method). 205 safe_join() (in module flask). 223 script_root (flask. 223 should_ignore_error() (flask.Namespace ScriptInfo (class in flask. 219 attribute).FlaskClient method). 204 register_blueprint() (flask.Flask attribute).cli).cli).SecureCookieSessionInterface tribute). 219 session_json_serializer (in module response_class (flask. flask).sessions). 220 run_command (in module flask.Blueprint render_template() (in module flask). 223 request_class (flask.Request attribute).Blueprint method). 242 205 Response (class in flask).Flask at- salt (flask.Flask method).Flask method). route() (flask.Flask register() (flask.sessions. 216 serializer (flask. 253 shell_context_processor() (flask. 205 save_session() should_set_cookie() (flask. 204 method). 223 record_once() (flask. 228 select_jinja_autoescape() (flask. 217 signal() (flask. 252 method). 247 signals. 223 method).Namespace (class in flask).ctx).Blueprint method). 223 run() (flask. 223 redirect() (in module flask). 202 session (class in flask).sessions.SessionInterface method).Blueprint attribute).signals_available (in module 318 . 215 224 route() (flask. 215 render_template_string() (in module send_static_file() (flask. register_error_handler() (flask.Blueprint method). 202 send_static_file() (flask. 247 secret_key (flask. 224 RFC session_transaction() RFC 822.sessions). 220 request_context() (flask.testing. tribute). 234 (flask.signals. 253 shell_command (in module flask. 230 202 send_file_max_age_default (flask. session_class 202 (flask.sessions). 219 SessionMixin (class in flask. send_file() (in module flask). 231 shell_context_processors (flask.SessionInterface (flask. 203 set_cookie() (flask.Flask save_session() (flask.Flask method).R SecureCookieSession (class in record() (flask.Flask method). 203 SessionInterface (class in flask.sessions.sessions). 221 tribute).Response method).SecureCookieSessionInterface request (class in flask). 205 attribute).sessions.Request at. 245 attribute). 203 flask.Flask method).Flask attribute).Flask 231 method).Flask register_error_handler() (flask. 237 205 Request (class in flask). SecureCookieSessionInterface (class in 215 flask. 215 flask. 245 session_cookie_name (flask. routing_exception (flask.cli).Flask at- request_tearing_down (in module flask). 204 signals.Flask attribute). 237 method).sessions). 204 method).Flask S method).Flask method).sessions. 215 method). 205 246 session_interface (flask.Flask attribute).SecureCookieSessionInterface request_finished (in module flask). 223 request_started (in module flask). RequestContext (class in flask. 215 send_from_directory() (in module flask).

216 216 stream_with_context() (in module flask). 247 template_context_processors (flask.Blueprint method). tribute).Request attribute). 209 216 url_default_functions (flask. 216 url_value_preprocessor() (flask.Flask method). 244 219 url_defaults() (flask. 210 subdomain (flask. template_rendered (in module flask). 210 attribute). attribute). 207 View (class in flask. Y 209 YOURAPPLICATION_SETTINGS. 216 tribute).Markup method).Request attribute).Flask teardown_appcontext_funcs (flask.Flask method).Flask attribute). W 207 with_appcontext() (in module flask.Flask attribute). 209 U unescape() (flask. 211 template_filter() (flask.Flask method).Request attribute). 219 attribute).Flask at- static_folder (flask. 216 use_x_sendfile (flask. url_defaults() (flask.Blueprint attribute). 208 test_client_class (flask.Request attribute).Flask method). 206 url_value_preprocessors (flask.Flask attribute). 219 teardown_app_request() (flask. 206 V teardown_request_funcs (flask. 68 test_request_context() (flask.Flask attribute).Flask method). 210 status (flask. 217 T url_rule (flask. 210 241 url_for() (in module flask). 216 method).Flask method). 205 tribute).Flask attribute).blueprints. 210 method). 217 319 .BlueprintSetupState attribute).Request attribute).Flask method).Flask method). 207 template_global() (flask.Response attribute).Request attribute).Flask method). 209 testing (flask. 210 method). 211 teardown_request() (flask.blueprints.views).Flask at- teardown_request() (flask. 211 test_client() (flask.Markup method).Flask method). 207 wsgi_app() (flask.Flask method). 244 253 template_test() (flask. 244 url_root (flask.Blueprint teardown_appcontext() (flask. 209 trap_http_exception() (flask. 244 url_build_error_handlers (flask. 209 url (flask. 205 url_value_preprocessor() (flask.cli).blueprints. 233 url_map (flask.Flask attribute).values (flask. 207 view_functions (flask.Blueprint tribute).Flask method).Flask at- static_folder (flask. 219 url_defaults (flask.Flask view_args (flask.Response attribute). 244 attribute).BlueprintSetupStateurl_prefix (flask.Flask at.BlueprintSetupState status_code (flask.Blueprint url_rule_class (flask.Flask attribute). 233 update_template_context() (flask. 227 striptags() (flask. stream (flask. flask).