Skip to content
Myr

Merge branch 'master' into celery-documentation

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

authored by David Lord · committed by David Lord · parents 2b03eca, ff361d3 · Browse files · 81 files+1639 added−800 removed
This commit

State

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

Diff stats

81 files+1639 added−800 removed

  • tests:+574 added−76 removed
  • other:+1065 added−724 removed

81 files+1639 added−800 removed

modified:docs/_templates/sidebarintro.html+3 added-3 removed
modified:docs/deploying/fastcgi.rst+4 added-4 removed
142 unmodified lines
143 ))144 )145146 alias.url = (147 "/static/" => "/path/to/your/static"147 "/static/" => "/path/to/your/static/"148 )149150 url.rewrite-once = (151 "^(/static($|/.*))$" => "$1",
6 unmodified lines
158:class:`~werkzeug.contrib.fixers.LighttpdCGIRootFix` middleware.159160Make sure to apply it only if you are mounting the application the URL161root. Also, see the Lighty docs for more information on `FastCGI and Python162<http://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModFastCGI>`_ (note that162<https://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModFastCGI>`_ (note that163explicitly passing a socket to run() is no longer necessary).164165Configuring nginx166-----------------
66 unmodified lines
233- The code depending on environment variables that are not set by the234 web server.235- Different python interpreters being used.236237.. _nginx: http://nginx.org/238.. _lighttpd: http://www.lighttpd.net/237.. _nginx: https://nginx.org/238.. _lighttpd: https://www.lighttpd.net/239.. _cherokee: http://cherokee-project.com/240.. _flup: https://pypi.python.org/pypi/flup
modified:docs/deploying/index.rst+2 added
19 unmodified lines
20- `Deploying Flask on Heroku <https://devcenter.heroku.com/articles/getting-started-with-python>`_21- `Deploying Flask on OpenShift <https://developers.openshift.com/en/python-flask.html>`_22- `Deploying Flask on Webfaction <http://flask.pocoo.org/snippets/65/>`_23- `Deploying Flask on Google App Engine <https://github.com/kamalgill/flask-appengine-template>`_24- `Deploying Flask on AWS Elastic Beanstalk <https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-flask.html>`_25- `Sharing your Localhost Server with Localtunnel <http://flask.pocoo.org/snippets/89/>`_26- `Deploying on Azure (IIS) <https://azure.microsoft.com/documentation/articles/web-sites-python-configure/>`_27- `Deploying on PythonAnywhere <https://help.pythonanywhere.com/pages/Flask/>`_2829Self-hosted options30-------------------31
8 unmodified lines
modified:docs/deploying/mod_wsgi.rst+4 added-4 removed
11 unmodified lines
12 '__main__':`` block or moved to a separate file. Just make sure it's13 not called because this will always start a local WSGI server which14 we do not want if we deploy that application to mod_wsgi.1516.. _Apache: http://httpd.apache.org/16.. _Apache: https://httpd.apache.org/1718Installing `mod_wsgi`19---------------------20
92 unmodified lines
113 </VirtualHost>114115Note: There have been some changes in access control configuration for `Apache 2.4`_.116117.. _Apache 2.4: http://httpd.apache.org/docs/trunk/upgrading.html117.. _Apache 2.4: https://httpd.apache.org/docs/trunk/upgrading.html118119Most notably, the syntax for directory permissions has changed from httpd 2.2120121.. sourcecode:: apache
10 unmodified lines
132133For more information consult the `mod_wsgi documentation`_.134135.. _mod_wsgi: https://github.com/GrahamDumpleton/mod_wsgi136.. _installation instructions: http://modwsgi.readthedocs.io/en/develop/installation.html136.. _installation instructions: https://modwsgi.readthedocs.io/en/develop/installation.html137.. _virtual python: https://pypi.python.org/pypi/virtualenv138.. _mod_wsgi documentation: http://modwsgi.readthedocs.io/en/develop/index.html138.. _mod_wsgi documentation: https://modwsgi.readthedocs.io/en/develop/index.html139140Troubleshooting141---------------142
75 unmodified lines
modified:docs/deploying/uwsgi.rst+2 added-2 removed
64 unmodified lines
65 include uwsgi_params;66 uwsgi_pass unix:/tmp/yourapplication.sock;67 }6869.. _nginx: http://nginx.org/70.. _lighttpd: http://www.lighttpd.net/69.. _nginx: https://nginx.org/70.. _lighttpd: https://www.lighttpd.net/71.. _cherokee: http://cherokee-project.com/72.. _uwsgi: http://projects.unbit.it/uwsgi/
modified:docs/patterns/appfactories.rst+2 added-2 removed
4 unmodified lines
56If you are already using packages and blueprints for your application7(:ref:`blueprints`) there are a couple of really nice ways to further improve8the experience. A common pattern is creating the application object when9the blueprint is imported. But if you move the creation of this object,9the blueprint is imported. But if you move the creation of this object10into a function, you can then create multiple instances of this app later.1112So why would you want to do this?13
45 unmodified lines
5960It's preferable to create your extensions and app factories so that the61extension object does not initially get bound to the application.6263Using `Flask-SQLAlchemy <http://pythonhosted.org/Flask-SQLAlchemy/>`_,63Using `Flask-SQLAlchemy <http://flask-sqlalchemy.pocoo.org/>`_,64as an example, you should not do something along those lines::6566 def create_app(config_filename):67 app = Flask(__name__)
49 unmodified lines
modified:docs/patterns/deferredcallbacks.rst+24 added-52 removed
1 unmodified line
23Deferred Request Callbacks4==========================56One of the design principles of Flask is that response objects are created7and passed down a chain of potential callbacks that can modify them or8replace them. When the request handling starts, there is no response9object yet. It is created as necessary either by a view function or by10some other component in the system.6One of the design principles of Flask is that response objects are created and7passed down a chain of potential callbacks that can modify them or replace8them. When the request handling starts, there is no response object yet. It is9created as necessary either by a view function or by some other component in10the system.1112But what happens if you want to modify the response at a point where the13response does not exist yet? A common example for that would be a14before-request function that wants to set a cookie on the response object.12What happens if you want to modify the response at a point where the response13does not exist yet? A common example for that would be a14:meth:`~flask.Flask.before_request` callback that wants to set a cookie on the15response object.1616One way is to avoid the situation. Very often that is possible. For17instance you can try to move that logic into an after-request callback18instead. Sometimes however moving that code there is just not a very19pleasant experience or makes code look very awkward.17One way is to avoid the situation. Very often that is possible. For instance18you can try to move that logic into a :meth:`~flask.Flask.after_request`19callback instead. However, sometimes moving code there makes it more20more complicated or awkward to reason about.2121As an alternative possibility you can attach a bunch of callback functions22to the :data:`~flask.g` object and call them at the end of the request.23This way you can defer code execution from anywhere in the application.22As an alternative, you can use :func:`~flask.after_this_request` to register23callbacks that will execute after only the current request. This way you can24defer code execution from anywhere in the application, based on the current25request.262526The Decorator27-------------2829The following decorator is the key. It registers a function on a list on30the :data:`~flask.g` object::3132 from flask import g3334 def after_this_request(f):35 if not hasattr(g, 'after_request_callbacks'):36 g.after_request_callbacks = []37 g.after_request_callbacks.append(f)38 return f394041Calling the Deferred42--------------------4344Now you can use the `after_this_request` decorator to mark a function to45be called at the end of the request. But we still need to call them. For46this the following function needs to be registered as47:meth:`~flask.Flask.after_request` callback::4849 @app.after_request50 def call_after_request_callbacks(response):51 for callback in getattr(g, 'after_request_callbacks', ()):52 callback(response)53 return response545556A Practical Example57-------------------5827At any time during a request, we can register a function to be called at the60end of the request. For example you can remember the current language of the61user in a cookie in the before-request function::28end of the request. For example you can remember the current language of the29user in a cookie in a :meth:`~flask.Flask.before_request` callback::3063 from flask import request31 from flask import request, after_this_request3233 @app.before_request34 def detect_user_language():35 language = request.cookies.get('user_lang')3637 if language is None:38 language = guess_language_from_request()3940 # when the response exists, set a cookie with the language41 @after_this_request42 def remember_language(response):43 response.set_cookie('user_lang', language)4445 g.language = language
modified:docs/patterns/distribute.rst+1 added-1 removed
172 unmodified lines
173the code without having to run ``install`` again after each change.174175176.. _pip: https://pypi.python.org/pypi/pip177.. _Setuptools: https://pythonhosted.org/setuptools177.. _Setuptools: https://pypi.python.org/pypi/setuptools
modified:docs/patterns/errorpages.rst+35 added-19 removed
45 unmodified lines
4647Error Handlers48--------------4950An error handler is a function, just like a view function, but it is51called when an error happens and is passed that error. The error is most52likely a :exc:`~werkzeug.exceptions.HTTPException`, but in one case it53can be a different error: a handler for internal server errors will be54passed other exception instances as well if they are uncaught.50An error handler is a function that returns a response when a type of error is51raised, similar to how a view is a function that returns a response when a52request URL is matched. It is passed the instance of the error being handled,53which is most likely a :exc:`~werkzeug.exceptions.HTTPException`. An error54handler for "500 Internal Server Error" will be passed uncaught exceptions in55addition to explicit 500 errors.5657An error handler is registered with the :meth:`~flask.Flask.errorhandler`57decorator and the error code of the exception. Keep in mind that Flask58will *not* set the error code for you, so make sure to also provide the59HTTP status code when returning a response.58decorator or the :meth:`~flask.Flask.register_error_handler` method. A handler59can be registered for a status code, like 404, or for an exception class.6061Please note that if you add an error handler for "500 Internal Server62Error", Flask will not trigger it if it's running in Debug mode.61The status code of the response will not be set to the handler's code. Make62sure to provide the appropriate HTTP status code when returning a response from63a handler.6464Here an example implementation for a "404 Page Not Found" exception::65A handler for "500 Internal Server Error" will not be used when running in66debug mode. Instead, the interactive debugger will be shown.6768Here is an example implementation for a "404 Page Not Found" exception::6970 from flask import render_template7172 @app.errorhandler(404)73 def page_not_found(e):74 # note that we set the 404 status explicitly75 return render_template('404.html'), 4047677When using the :ref:`application factory pattern <app-factories>`::7879 from flask import Flask, render_template8081 def page_not_found(e):82 return render_template('404.html'), 4048384 def create_app(config_filename):85 app = Flask(__name__)86 app.register_error_handler(404, page_not_found)87 return app8889An example template might be this:9091.. sourcecode:: html+jinja9276 {% extends "layout.html" %}77 {% block title %}Page Not Found{% endblock %}78 {% block body %}79 <h1>Page Not Found</h1>80 <p>What you were looking for is just not there.81 <p><a href="{{ url_for('index') }}">go somewhere nice</a>82 {% endblock %}8393 {% extends "layout.html" %}94 {% block title %}Page Not Found{% endblock %}95 {% block body %}96 <h1>Page Not Found</h1>97 <p>What you were looking for is just not there.98 <p><a href="{{ url_for('index') }}">go somewhere nice</a>99 {% endblock %}
modified:docs/patterns/favicon.rst+1 added-1 removed
47 unmodified lines
4849See also50--------5152* The `Favicon <http://en.wikipedia.org/wiki/Favicon>`_ article on52* The `Favicon <https://en.wikipedia.org/wiki/Favicon>`_ article on53 Wikipedia
modified:docs/patterns/fileuploads.rst+5 added-5 removed
19 unmodified lines
20specific upload folder and displays a file to the user. Let's look at the21bootstrapping code for our application::2223 import os24 from flask import Flask, request, redirect, url_for24 from flask import Flask, flash, request, redirect, url_for25 from werkzeug.utils import secure_filename2627 UPLOAD_FOLDER = '/path/to/the/uploads'28 ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
28 unmodified lines
57 flash('No file part')58 return redirect(request.url)59 file = request.files['file']60 # if user does not select file, browser also61 # submit a empty part without filename61 # submit an empty part without filename62 if file.filename == '':63 flash('No selected file')64 return redirect(request.url)65 if file and allowed_file(file.filename):
5 unmodified lines
71 <!doctype html>72 <title>Upload new File</title>73 <h1>Upload new File</h1>74 <form method=post enctype=multipart/form-data>75 <p><input type=file name=file>76 <input type=submit value=Upload>75 <input type=file name=file>76 <input type=submit value=Upload>77 </form>78 '''7980So what does that :func:`~werkzeug.utils.secure_filename` function actually do?
99 unmodified lines
180`Flask-Uploads`_ that implements a full fledged upload mechanism with white and181blacklisting of extensions and more.182183.. _jQuery: https://jquery.com/184.. _Flask-Uploads: http://pythonhosted.org/Flask-Uploads/184.. _Flask-Uploads: https://pythonhosted.org/Flask-Uploads/
modified:docs/patterns/packages.rst+6 added-1 removed
15 unmodified lines
16 index.html17 login.html18 ...1920If you find yourself stuck on something, feel free21to take a look at the source code for this example.22You'll find `the full src for this example here`_.2324Simple Packages25---------------2627To convert that into a larger one, just create a new folder
36 unmodified lines
6465 export FLASK_APP=yourapplication6667If you are outside of the project directory make sure to provide the exact 64path to your application directory. Similiarly you can turn on "debug 68path to your application directory. Similarly you can turn on "debug 69mode" with this environment variable:: 7071 export FLASK_DEBUG=true 72
60 unmodified lines
133 :ref:`becomingbig` section for some inspiration how to deal with that.134135136.. _working-with-modules:137.. _the full src for this example here: https://github.com/pallets/flask/tree/master/examples/patterns/largerapp138139Working with Blueprints140-----------------------141
4 unmodified lines
modified:docs/patterns/sqlalchemy.rst+5 added-5 removed
20 unmodified lines
2122You can download `Flask-SQLAlchemy`_ from `PyPI23<https://pypi.python.org/pypi/Flask-SQLAlchemy>`_.2425.. _Flask-SQLAlchemy: http://pythonhosted.org/Flask-SQLAlchemy/25.. _Flask-SQLAlchemy: http://flask-sqlalchemy.pocoo.org/262728Declarative29-----------
77 unmodified lines
107[<User u'admin'>]108>>> User.query.filter(User.name == 'admin').first()109<User u'admin'>110111.. _SQLAlchemy: http://www.sqlalchemy.org/111.. _SQLAlchemy: https://www.sqlalchemy.org/112.. _declarative:113 http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/113 https://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/114115Manual Object Relational Mapping116--------------------------------117
16 unmodified lines
134 bind=engine))135 def init_db():136 metadata.create_all(bind=engine)137138As for the declarative approach you need to close the session after138As in the declarative approach, you need to close the session after139each request or application context shutdown. Put this into your140application module::141142 from yourapplication.database import db_session
71 unmodified lines
214>>> engine.execute('select * from users where id = :1', [1]).first()215(1, u'admin', u'admin@localhost')216217For more information about SQLAlchemy, head over to the218`website <http://www.sqlalchemy.org/>`_.218`website <https://www.sqlalchemy.org/>`_.
modified:docs/patterns/sqlite3.rst+7 added-7 removed
1 unmodified line
23Using SQLite 3 with Flask4=========================56In Flask you can easily implement the opening of database connections on 7demand and closing them when the context dies (usually at the end of the 6In Flask you can easily implement the opening of database connections on7demand and closing them when the context dies (usually at the end of the8request).910Here is a simple example of how you can use SQLite 3 with Flask::11
58 unmodified lines
70Now in each request handling function you can access `g.db` to get the71current open database connection. To simplify working with SQLite, a72row factory function is useful. It is executed for every result returned73from the database to convert the result. For instance, in order to get74dictionaries instead of tuples, this could be inserted into the ``get_db`` 74dictionaries instead of tuples, this could be inserted into the ``get_db``75function we created above::7677 def make_dicts(cursor, row):78 return dict((cursor.description[idx][0], value)
22 unmodified lines
101 M102103Additionally, it is a good idea to provide a query function that combines104getting the cursor, executing and fetching the results::105 105106 def query_db(query, args=(), one=False):107 cur = get_db().execute(query, args)108 rv = cur.fetchall()109 cur.close()110 return (rv[0] if rv else None) if one else rv111112This handy little function, in combination with a row factory, makes 113working with the database much more pleasant than it is by just using the 112This handy little function, in combination with a row factory, makes113working with the database much more pleasant than it is by just using the114raw cursor and connection objects.115116Here is how you can use it::117
12 unmodified lines
130To pass variable parts to the SQL statement, use a question mark in the131statement and pass in the arguments as a list. Never directly add them to132the SQL statement with string formatting because this makes it possible133to attack the application using `SQL Injections134<http://en.wikipedia.org/wiki/SQL_injection>`_.134<https://en.wikipedia.org/wiki/SQL_injection>`_.135136Initial Schemas137---------------138
16 unmodified lines
modified:docs/patterns/wtforms.rst+1 added-1 removed
17 unmodified lines
18 few little helpers that make working with forms and Flask more19 fun. You can get it from `PyPI20 <https://pypi.python.org/pypi/Flask-WTF>`_.2122.. _Flask-WTF: http://pythonhosted.org/Flask-WTF/22.. _Flask-WTF: https://flask-wtf.readthedocs.io/en/stable/2324The Forms25---------26
100 unmodified lines
modified:docs/tutorial/introduction.rst+1 added-1 removed
29 unmodified lines
30 :alt: screenshot of the final application3132Continue with :ref:`tutorial-folders`.3334.. _SQLAlchemy: http://www.sqlalchemy.org/34.. _SQLAlchemy: https://www.sqlalchemy.org/
modified:docs/tutorial/packaging.rst+1 added-1 removed
53 unmodified lines
54into this file, :file:`flaskr/__init__.py`:5556.. sourcecode:: python5758 from flaskr import app58 from .flaskr import app5960This import statement brings the application instance into the top-level 61of the application package. When it is time to run the application, the 62Flask development server needs the location of the app instance. This
46 unmodified lines
modified:docs/tutorial/templates.rst+3 added-3 removed
57 unmodified lines
5859This template extends the :file:`layout.html` template from above to display the60messages. Note that the ``for`` loop iterates over the messages we passed61in with the :func:`~flask.render_template` function. Notice that the form is62configured to to submit to the `add_entry` view function and use ``POST`` as62configured to submit to the `add_entry` view function and use ``POST`` as63HTTP method:6465.. sourcecode:: html+jinja66
11 unmodified lines
78 </form>79 {% endif %}80 <ul class=entries>81 {% for entry in entries %}82 <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}82 <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}</li>83 {% else %}84 <li><em>Unbelievable. No entries here so far</em>84 <li><em>Unbelievable. No entries here so far</em></li>85 {% endfor %}86 </ul>87 {% endblock %}88
24 unmodified lines
modified:docs/tutorial/testing.rst+1 added-1 removed
44 unmodified lines
4546Run and watch the tests pass, within the top-level :file:`flaskr/` 47directory as::4849 py.test49 pytest5051Testing + setuptools52--------------------53
43 unmodified lines
modified:docs/api.rst+2 added-58 removed
28 unmodified lines
29---------------------3031.. autoclass:: Request32 :members:33 :inherited-members:3434 .. attribute:: form3536 A :class:`~werkzeug.datastructures.MultiDict` with the parsed form data from ``POST``37 or ``PUT`` requests. Please keep in mind that file uploads will not38 end up here, but instead in the :attr:`files` attribute.3940 .. attribute:: args4142 A :class:`~werkzeug.datastructures.MultiDict` with the parsed contents of the query43 string. (The part in the URL after the question mark).4445 .. attribute:: values4647 A :class:`~werkzeug.datastructures.CombinedMultiDict` with the contents of both48 :attr:`form` and :attr:`args`.4950 .. attribute:: cookies5152 A :class:`dict` with the contents of all cookies transmitted with53 the request.5455 .. attribute:: stream5657 If the incoming form data was not encoded with a known mimetype58 the data is stored unmodified in this stream for consumption. Most59 of the time it is a better idea to use :attr:`data` which will give60 you that data as a string. The stream only returns the data once.6162 .. attribute:: headers6364 The incoming request headers as a dictionary like object.6566 .. attribute:: data6768 Contains the incoming request data as string in case it came with69 a mimetype Flask does not handle.7071 .. attribute:: files7273 A :class:`~werkzeug.datastructures.MultiDict` with files uploaded as part of a74 ``POST`` or ``PUT`` request. Each file is stored as75 :class:`~werkzeug.datastructures.FileStorage` object. It basically behaves like a76 standard file object you know from Python, with the difference that77 it also has a :meth:`~werkzeug.datastructures.FileStorage.save` function that can78 store the file on the filesystem.7935 .. attribute:: environ3637 The underlying WSGI environment.3884 .. attribute:: method8586 The current request method (``POST``, ``GET`` etc.)8739 .. attribute:: path40 .. attribute:: full_path41 .. attribute:: script_root42 .. attribute:: url
21 unmodified lines
64 `url` ``u'http://www.example.com/myapplication/π/page.html?x=y'``65 `url_root` ``u'http://www.example.com/myapplication/'``66 ============= ======================================================67117 .. attribute:: is_xhr68119 ``True`` if the request was triggered via a JavaScript120 `XMLHttpRequest`. This only works with libraries that support the121 ``X-Requested-With`` header and set it to `XMLHttpRequest`.122 Libraries that do that are prototype, jQuery and Mochikit and123 probably some more.69.. attribute:: request70125.. class:: request12671 To access incoming request data, you can use the global `request`72 object. Flask parses incoming request data for you and gives you73 access to it through that global object. Internally Flask makes74 sure that you always get the correct data for the active thread if you
761 unmodified lines
modified:docs/becomingbig.rst+1 added-1 removed
10 unmodified lines
11Flask started in part to demonstrate how to build your own framework on top of12existing well-used tools Werkzeug (WSGI) and Jinja (templating), and as it13developed, it became useful to a wide audience. As you grow your codebase,14don't just use Flask -- understand it. Read the source. Flask's code is15written to be read; it's documentation is published so you can use its internal15written to be read; its documentation is published so you can use its internal16APIs. Flask sticks to documented APIs in upstream libraries, and documents its17internal utilities so that you can find the hook points needed for your18project.19
82 unmodified lines
modified:docs/blueprints.rst+23 added-5 removed
175 unmodified lines
176177 admin = Blueprint('admin', __name__, template_folder='templates')178179For static files, the path can be absolute or relative to the blueprint180resource folder. 180resource folder.181182The template folder is added to the search path of templates but with a lower 183priority than the actual application's template folder. That way you can 184easily override templates that a blueprint provides in the actual application. 182The template folder is added to the search path of templates but with a lower183priority than the actual application's template folder. That way you can184easily override templates that a blueprint provides in the actual application.185This also means that if you don't want a blueprint template to be accidentally186overridden, make sure that no other blueprint or actual application template187has the same relative path. When multiple blueprints provide the same relative188template path the first blueprint registered takes precedence over the others.
4 unmodified lines
193``templates`` as a `template_folder` you will have to create a file like194this: :file:`yourapplication/admin/templates/admin/index.html`. The reason195for the extra ``admin`` folder is to avoid getting our template overridden196by a template named ``index.html`` in the actual application template197folder. 197folder.198199To further reiterate this: if you have a blueprint named ``admin`` and you200want to render a template called :file:`index.html` which is specific to this201blueprint, the best idea is to lay out your templates like this::
42 unmodified lines
244 @simple_page.errorhandler(404)245 def page_not_found(e):246 return render_template('pages/404.html')247248Most errorhandlers will simply work as expected; however, there is a caveat249concerning handlers for 404 and 405 exceptions. These errorhandlers are only250invoked from an appropriate ``raise`` statement or a call to ``abort`` in another251of the blueprint's view functions; they are not invoked by, e.g., an invalid URL252access. This is because the blueprint does not "own" a certain URL space, so253the application instance has no way of knowing which blueprint errorhandler it254should run if given an invalid URL. If you would like to execute different255handling strategies for these errors based on URL prefixes, they may be defined256at the application level using the ``request`` proxy object::257258 @app.errorhandler(404)259 @app.errorhandler(405)260 def _handle_api_error(ex):261 if request.path.startswith('/api/'):262 return jsonify_error(ex)263 else:264 return ex265266More information on error handling see :ref:`errorpages`.
modified:docs/cli.rst+14 added-2 removed
54 unmodified lines
55``export FLASK_APP`` into your ``activate`` script by adding it to the56bottom of the file. That way every time you activate your virtualenv you57automatically also activate the correct application name.5859Edit the activate script for the shell you use. For example:6061Unix Bash: ``venv/bin/activate``::6263 FLASK_APP=hello64 export FLASK_APP6566Windows CMD.exe: ``venv\Scripts\activate.bat``::6768 set "FLASK_APP=hello"69 :END7071Debug Flag72----------7374The :command:`flask` script can also be instructed to enable the debug
75 unmodified lines
150 import os151 from yourapplication import create_app152 app = create_app(os.environ['YOURAPPLICATION_CONFIG'])153142Once this has happened you can make the flask command automatically pick143it up::154Once this has happened you can make the :command:`flask` command automatically155pick it up::156157 export YOURAPPLICATION_CONFIG=/path/to/config.cfg158 export FLASK_APP=/path/to/autoapp.py159
101 unmodified lines
modified:docs/conf.py+15 added-4 removed
9 unmodified lines
10#11# All configuration values have a default; values that are commented out12# serve to show the default.13from __future__ import print_function14from datetime import datetime14import os15import sys16import pkg_resources17import time18import datetime1920BUILD_DATE = datetime.datetime.utcfromtimestamp(int(os.environ.get('SOURCE_DATE_EPOCH', time.time())))2122# If extensions (or modules to document with autodoc) are in another directory,23# add these directories to sys.path here. If the directory is relative to the24# documentation root, use os.path.abspath to make it absolute, like shown here.25sys.path.append(os.path.join(os.path.dirname(__file__), '_themes'))
11 unmodified lines
37 'sphinx.ext.intersphinx',38 'flaskdocext'39]4041try:42 __import__('sphinxcontrib.log_cabinet')43except ImportError:44 print('sphinxcontrib-log-cabinet is not installed.')45 print('Changelog directives will not be re-organized.')46else:47 extensions.append('sphinxcontrib.log_cabinet')4849# Add any paths that contain templates here, relative to this directory.50templates_path = ['_templates']5152# The suffix of source filenames.
6 unmodified lines
59master_doc = 'index'6061# General information about the project.62project = u'Flask'52copyright = u'2010 - {0}, Armin Ronacher'.format(datetime.utcnow().year)63copyright = u'2010 - {0}, Armin Ronacher'.format(BUILD_DATE.year)6465# The version info for the project you're documenting, acts as replacement for66# |version| and |release|, also used in various other places throughout the67# built documents.
173 unmodified lines
241242# The scheme of the identifier. Typical schemes are ISBN or URL.243#epub_scheme = ''244234# The unique identifier of the text. This can be a ISBN number245# The unique identifier of the text. This can be an ISBN number246# or the project homepage.247#epub_identifier = ''248249# A unique identification for the text.
17 unmodified lines
267 'python': ('https://docs.python.org/3/', None),268 'werkzeug': ('http://werkzeug.pocoo.org/docs/', None),269 'click': ('http://click.pocoo.org/', None),270 'jinja': ('http://jinja.pocoo.org/docs/', None),260 'sqlalchemy': ('http://docs.sqlalchemy.org/en/latest/', None),271 'sqlalchemy': ('https://docs.sqlalchemy.org/en/latest/', None),272 'wtforms': ('https://wtforms.readthedocs.io/en/latest/', None),273 'blinker': ('https://pythonhosted.org/blinker/', None)274}275
35 unmodified lines
modified:docs/config.rst+28 added-14 removed
42 unmodified lines
43 DEBUG=True,44 SECRET_KEY='...'45 )4647.. admonition:: Debug Mode with the ``flask`` Script4849 If you use the :command:`flask` script to start a local development50 server, to enable the debug mode, you need to export the ``FLASK_DEBUG``51 environment variable before running the server::5253 $ export FLASK_DEBUG=154 $ flask run5556 (On Windows you need to use ``set`` instead of ``export``).57 58 ``app.debug`` and ``app.config['DEBUG']`` are not compatible with 59   the :command:`flask` script. They only worked when using ``Flask.run()``60 method.61 62Builtin Configuration Values63----------------------------6465The following configuration values are used internally by Flask:6667.. tabularcolumns:: |p{6.5cm}|p{8.5cm}|6869================================= =========================================55``DEBUG`` enable/disable debug mode70``DEBUG`` enable/disable debug mode when using 71 ``Flask.run()`` method to start server72``TESTING`` enable/disable testing mode73``PROPAGATE_EXCEPTIONS`` explicitly enable or disable the74 propagation of exceptions. If not set or75 explicitly set to ``None`` this is
55 unmodified lines
131 help. Setting a ``SERVER_NAME`` also132 by default enables URL generation133 without a request context but with an134 application context.119``APPLICATION_ROOT`` If the application does not occupy120 a whole domain or subdomain this can121 be set to the path where the application122 is configured to live. This is for123 session cookie as path value. If124 domains are used, this should be125 ``None``.135``APPLICATION_ROOT`` The path value used for the session136 cookie if ``SESSION_COOKIE_PATH`` isn't137 set. If it's also ``None`` ``'/'`` is used.138 Note that to actually serve your Flask139 app under a subpath you need to tell140 your WSGI container the ``SCRIPT_NAME``141 WSGI environment variable.142``MAX_CONTENT_LENGTH`` If set to a value in bytes, Flask will143 reject incoming requests with a144 content length greater than this by145 returning a 413 status code.
47 unmodified lines
193 behavior by changing this variable.194 This is not recommended but might give195 you a performance improvement on the196 cost of cacheability.181``JSONIFY_PRETTYPRINT_REGULAR`` If this is set to ``True`` (the default)182 jsonify responses will be pretty printed183 if they are not requested by an184 XMLHttpRequest object (controlled by185 the ``X-Requested-With`` header)197``JSONIFY_PRETTYPRINT_REGULAR`` If this is set to ``True`` or the Flask app198 is running in debug mode, jsonify responses199 will be pretty printed.200``JSONIFY_MIMETYPE`` MIME type used for jsonify responses.201``TEMPLATES_AUTO_RELOAD`` Whether to check for modifications of202 the template source and reload it203 automatically. By default the value is
71 unmodified lines
275 app.config.from_envvar('YOURAPPLICATION_SETTINGS')276277This first loads the configuration from the278`yourapplication.default_settings` module and then overrides the values265with the contents of the file the :envvar:``YOURAPPLICATION_SETTINGS``279with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS`280environment variable points to. This environment variable can be set on281Linux or OS X with the export command in the shell before starting the282server::283
196 unmodified lines
modified:docs/errorhandling.rst+6 added-5 removed
32 unmodified lines
3334Sending error mails, even if just for critical ones, can become35overwhelming if enough users are hitting the error and log files are36typically never looked at. This is why we recommend using `Sentry37<http://www.getsentry.com/>`_ for dealing with application errors. It's37<https://www.getsentry.com/>`_ for dealing with application errors. It's38available as an Open Source project `on GitHub39<https://github.com/getsentry/sentry>`__ and is also available as a `hosted version40<https://getsentry.com/signup/>`_ which you can try for free. Sentry41aggregates duplicate errors, captures the full stack trace and local
46 unmodified lines
8889 @app.errorhandler(werkzeug.exceptions.BadRequest)90 def handle_bad_request(e):91 return 'bad request!'92 9293 app.register_error_handler(400, lambda e: 'bad request!')9495Those two ways are equivalent, but the first one is more clear and leaves96you with a function to call on your whim (and in tests). Note that
118 unmodified lines
215A formatter can be instantiated with a format string. Note that216tracebacks are appended to the log entry automatically. You don't have to217do that in the log formatter format string.218219Here some example setups:219Here are some example setups:220221Email222`````223
51 unmodified lines
275+------------------+----------------------------------------------------+276| ``%(lineno)d`` | Source line number where the logging call was |277| | issued (if available). |278+------------------+----------------------------------------------------+279| ``%(asctime)s`` | Human-readable time when the LogRecord` was |280| | created. By default this is of the form |279| ``%(asctime)s`` | Human-readable time when the |280| | :class:`~logging.LogRecord` was created. |281| | By default this is of the form |282| | ``"2003-07-08 16:49:45,896"`` (the numbers after |283| | the comma are millisecond portion of the time). |284| | This can be changed by subclassing the formatter |285| | and overriding the |
109 unmodified lines
modified:docs/extensiondev.rst+1 added-9 removed
27 unmodified lines
28"Flask" somewhere in that name and that you check the capitalization.29This is how users can then register dependencies to your extension in30their :file:`setup.py` files.3132Flask sets up a redirect package called :data:`flask.ext` where users33should import the extensions from. If you for instance have a package34called ``flask_something`` users would import it as35``flask.ext.something``. This is done to transition from the old36namespace packages. See :ref:`ext-import-transition` for more details.3732But what do extensions look like themselves? An extension has to ensure33that it works with multiple Flask application instances at once. This is34a requirement because many people will use patterns like the35:ref:`app-factories` pattern to create their application as needed to aid
350 unmodified lines
38610. An extension currently has to support Python 2.6 as well as387 Python 2.7388389396.. _ext-import-transition:397390Extension Import Transition391---------------------------392393In early versions of Flask we recommended using namespace packages for Flask
10 unmodified lines
404schema. The ``flask.ext.foo`` compatibility alias is still in Flask 0.11 but is405now deprecated -- you should use ``flask_foo``.406407416.. _OAuth extension: http://pythonhosted.org/Flask-OAuth/408.. _OAuth extension: https://pythonhosted.org/Flask-OAuth/409.. _mailinglist: http://flask.pocoo.org/mailinglist/410.. _IRC channel: http://flask.pocoo.org/community/irc/
modified:docs/installation.rst+120 added-110 removed
1 unmodified line
23Installation4============56Flask depends on some external libraries, like `Werkzeug7<http://werkzeug.pocoo.org/>`_ and `Jinja2 <http://jinja.pocoo.org/>`_.8Werkzeug is a toolkit for WSGI, the standard Python interface between web9applications and a variety of servers for both development and deployment.10Jinja2 renders templates.6Python Version7--------------812So how do you get all that on your computer quickly? There are many ways you13could do that, but the most kick-ass method is virtualenv, so let's have a look14at that first.9We recommend using the latest version of Python 3. Flask supports Python 3.310and newer, Python 2.6 and newer, and PyPy.1116You will need Python 2.6 or newer to get started, so be sure to have an17up-to-date Python 2.x installation. For using Flask with Python 3 have a18look at :ref:`python3-support`.12Dependencies13------------1420.. _virtualenv:15These distributions will be installed automatically when installing Flask.1622virtualenv23----------17* `Werkzeug`_ implements WSGI, the standard Python interface between18 applications and servers.19* `Jinja`_ is a template language that renders the pages your application20 serves.21* `MarkupSafe`_ comes with Jinja. It escapes untrusted input when rendering22 templates to avoid injection attacks.23* `ItsDangerous`_ securely signs data to ensure its integrity. This is used24 to protect Flask's session cookie.25* `Click`_ is a framework for writing command line applications. It provides26 the ``flask`` command and allows adding custom management commands.2725Virtualenv is probably what you want to use during development, and if you have26shell access to your production machines, you'll probably want to use it there,27too.28.. _Werkzeug: http://werkzeug.pocoo.org/29.. _Jinja: http://jinja.pocoo.org/30.. _MarkupSafe: https://pypi.python.org/pypi/MarkupSafe31.. _ItsDangerous: https://pythonhosted.org/itsdangerous/32.. _Click: http://click.pocoo.org/3329What problem does virtualenv solve? If you like Python as much as I do,30chances are you want to use it for other projects besides Flask-based web31applications. But the more projects you have, the more likely it is that you32will be working with different versions of Python itself, or at least different33versions of Python libraries. Let's face it: quite often libraries break34backwards compatibility, and it's unlikely that any serious application will35have zero dependencies. So what do you do if two or more of your projects have36conflicting dependencies?34Optional dependencies35~~~~~~~~~~~~~~~~~~~~~3638Virtualenv to the rescue! Virtualenv enables multiple side-by-side39installations of Python, one for each project. It doesn't actually install40separate copies of Python, but it does provide a clever way to keep different41project environments isolated. Let's see how virtualenv works.37These distributions will not be installed automatically. Flask will detect and38use them if you install them.3943If you are on Mac OS X or Linux, chances are that the following44command will work for you::40* `Blinker`_ provides support for :ref:`signals`.41* `SimpleJSON`_ is a fast JSON implementation that is compatible with42 Python's ``json`` module. It is preferred for JSON operations if it is43 installed.4446 $ sudo pip install virtualenv45.. _Blinker: https://pythonhosted.org/blinker/46.. _SimpleJSON: https://simplejson.readthedocs.io/4748It will probably install virtualenv on your system. Maybe it's even49in your package manager. If you use Ubuntu, try::48Virtual environments49--------------------5051 $ sudo apt-get install python-virtualenv51Use a virtual environment to manage the dependencies for your project, both in52development and in production.5353If you are on Windows and don't have the ``easy_install`` command, you must54install it first. Check the :ref:`windows-easy-install` section for more55information about how to do that. Once you have it installed, run the same56commands as above, but without the ``sudo`` prefix.54What problem does a virtual environment solve? The more Python projects you55have, the more likely it is that you need to work with different versions of56Python libraries, or even Python itself. Newer versions of libraries for one57project can break compatibility in another project.5858Once you have virtualenv installed, just fire up a shell and create59your own environment. I usually create a project folder and a :file:`venv`60folder within::59Virtual environments are independent groups of Python libraries, one for each60project. Packages installed for one project will not affect other projects or61the operating system's packages.6262 $ mkdir myproject63 $ cd myproject64 $ virtualenv venv65 New python executable in venv/bin/python66 Installing setuptools, pip............done.63Python 3 comes bundled with the :mod:`venv` module to create virtual64environments. If you're using a modern version of Python, you can continue on65to the next section.6668Now, whenever you want to work on a project, you only have to activate the69corresponding environment. On OS X and Linux, do the following::67If you're using Python 2, see :ref:`install-install-virtualenv` first.6871 $ . venv/bin/activate69.. _install-create-env:7073If you are a Windows user, the following command is for you::71Create an environment72~~~~~~~~~~~~~~~~~~~~~7375 $ venv\scripts\activate74Create a project folder and a :file:`venv` folder within:7577Either way, you should now be using your virtualenv (notice how the prompt of78your shell has changed to show the active environment).76.. code-block:: sh7780And if you want to go back to the real world, use the following command::78 mkdir myproject79 cd myproject80 python3 -m venv venv8182 $ deactivate82On Windows:8384After doing this, the prompt of your shell should be as familiar as before.84.. code-block:: bat8586Now, let's move on. Enter the following command to get Flask activated in your87virtualenv::86 py -3 -m venv venv8789 $ pip install Flask88If you needed to install virtualenv because you are on an older version of89Python, use the following command instead:9091A few seconds later and you are good to go.91.. code-block:: sh9293 virtualenv venv9494System-Wide Installation95------------------------95On Windows:9697This is possible as well, though I do not recommend it. Just run98``pip`` with root privileges::97.. code-block:: bat98100 $ sudo pip install Flask99 \Python27\Scripts\virtualenv.exe venv100102(On Windows systems, run it in a command-prompt window with administrator103privileges, and leave out ``sudo``.)101Activate the environment102~~~~~~~~~~~~~~~~~~~~~~~~103104Before you work on your project, activate the corresponding environment:105106Living on the Edge107------------------106.. code-block:: sh107109If you want to work with the latest version of Flask, there are two ways: you110can either let ``pip`` pull in the development version, or you can tell111it to operate on a git checkout. Either way, virtualenv is recommended.108 . venv/bin/activate109113Get the git checkout in a new virtualenv and run in development mode::110On Windows:111115 $ git clone http://github.com/pallets/flask.git116 Initialized empty Git repository in ~/dev/flask/.git/117 $ cd flask118 $ virtualenv venv119 New python executable in venv/bin/python120 Installing setuptools, pip............done.121 $ . venv/bin/activate122 $ python setup.py develop123 ...124 Finished processing dependencies for Flask112.. code-block:: bat113126This will pull in the dependencies and activate the git head as the current127version inside the virtualenv. Then all you have to do is run ``git pull128origin`` to update to the latest version.114 venv\Scripts\activate115130.. _windows-easy-install:116Your shell prompt will change to show the name of the activated environment.117132`pip` and `setuptools` on Windows133---------------------------------118Install Flask119-------------120135Sometimes getting the standard "Python packaging tools" like ``pip``, ``setuptools``136and ``virtualenv`` can be a little trickier, but nothing very hard. The crucial137package you will need is pip - this will let you install138anything else (like virtualenv). Fortunately there is a "bootstrap script"139you can run to install.121Within the activated environment, use the following command to install Flask:122141If you don't currently have ``pip``, then `get-pip.py` will install it for you.123.. code-block:: sh124143`get-pip.py`_125 pip install Flask126145It should be double-clickable once you download it. If you already have ``pip``,146you can upgrade them by running::127Living on the edge128~~~~~~~~~~~~~~~~~~129148 > pip install --upgrade pip setuptools130If you want to work with the latest Flask code before it's released, install or131update the code from the master branch:132150Most often, once you pull up a command prompt you want to be able to type ``pip``151and ``python`` which will run those things, but this might not automatically happen152on Windows, because it doesn't know where those executables are (give either a try!).133.. code-block:: sh134154To fix this, you should be able to navigate to your Python install directory155(e.g :file:`C:\Python27`), then go to :file:`Tools`, then :file:`Scripts`, then find the156:file:`win_add2path.py` file and run that. Open a **new** Command Prompt and157check that you can now just type ``python`` to bring up the interpreter.135 pip install -U https://github.com/pallets/flask/archive/master.tar.gz136159Finally, to install `virtualenv`_, you can simply run::137.. _install-install-virtualenv:138161 > pip install virtualenv139Install virtualenv140------------------141163Then you can be off on your way following the installation instructions above.142If you are using Python 2, the venv module is not available. Instead,143install `virtualenv`_.144145On Linux, virtualenv is provided by your package manager:146147.. code-block:: sh148149 # Debian, Ubuntu150 sudo apt-get install python-virtualenv151152 # CentOS, Fedora153 sudo yum install python-virtualenv154155 # Arch156 sudo pacman -S python-virtualenv157158If you are on Mac OS X or Windows, download `get-pip.py`_, then:159160.. code-block:: sh161162 sudo python2 Downloads/get-pip.py163 sudo python2 -m pip install virtualenv164165On Windows, as an administrator:166167.. code-block:: bat168169 \Python27\python.exe Downloads\get-pip.py170 \Python27\python.exe -m pip install virtualenv171172Now you can continue to :ref:`install-create-env`.173174.. _virtualenv: https://virtualenv.pypa.io/175.. _get-pip.py: https://bootstrap.pypa.io/get-pip.py
modified:docs/quickstart.rst+103 added-159 removed
100 unmodified lines
101102Invalid Import Name103```````````````````104105The ``FLASK_APP`` environment variable is the name of the module to import at 106:command:`flask run`. In case that module is incorrectly named you will get an 107import error upon start (or if debug is enabled when you navigate to the 105The ``FLASK_APP`` environment variable is the name of the module to import at106:command:`flask run`. In case that module is incorrectly named you will get an107import error upon start (or if debug is enabled when you navigate to the108application). It will tell you what it tried to import and why it failed.109110The most common reason is a typo or because you did not actually create an111``app`` object.
46 unmodified lines
158159Routing160-------161162Modern web applications have beautiful URLs. This helps people remember163the URLs, which is especially handy for applications that are used from164mobile devices with slower network connections. If the user can directly165go to the desired page without having to hit the index page it is more166likely they will like the page and come back next time.162Modern web applications use meaningful URLs to help users. Users are more163likely to like a page and come back if the page uses a meaningful URL they can164remember and use to directly visit a page.165168As you have seen above, the :meth:`~flask.Flask.route` decorator is used to169bind a function to a URL. Here are some basic examples::166Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::167168 @app.route('/')169 def index():170 return 'Index Page'
1 unmodified line
172 @app.route('/hello')173 def hello():174 return 'Hello, World'175179But there is more to it! You can make certain parts of the URL dynamic and180attach multiple rules to a function.176You can do more! You can make parts of the URL dynamic and attach multiple177rules to a function.178179Variable Rules180``````````````181185To add variable parts to a URL you can mark these special sections as186``<variable_name>``. Such a part is then passed as a keyword argument to your187function. Optionally a converter can be used by specifying a rule with188``<converter:variable_name>``. Here are some nice examples::182You can add variable sections to a URL by marking sections with183``<variable_name>``. Your function then receives the ``<variable_name>``184as a keyword argument. Optionally, you can use a converter to specify the type185of the argument like ``<converter:variable_name>``. ::186187 @app.route('/user/<username>')188 def show_user_profile(username):189 # show the user profile for that user
3 unmodified lines
193 def show_post(post_id):194 # show the post with the given id, the id is an integer195 return 'Post %d' % post_id196200The following converters exist:197 @app.route('/path/<path:subpath>')198 def show_subpath(subpath):199 # show the subpath after /path/200 return 'Subpath %s' % subpath201202=========== ===============================================203`string` accepts any text without a slash (the default)204`int` accepts integers205`float` like ``int`` but for floating point values206`path` like the default but also accepts slashes207`any` matches one of the items provided208`uuid` accepts UUID strings209=========== ===============================================202Converter types:203211.. admonition:: Unique URLs / Redirection Behavior204========== ==========================================205``string`` (default) accepts any text without a slash206``int`` accepts positive integers207``float`` accepts positive floating point values208``path`` like ``string`` but also accepts slashes209``uuid`` accepts UUID strings210========== ==========================================211213 Flask's URL rules are based on Werkzeug's routing module. The idea214 behind that module is to ensure beautiful and unique URLs based on215 precedents laid down by Apache and earlier HTTP servers.212Unique URLs / Redirection Behavior213``````````````````````````````````214217 Take these two rules::215Take these two rules::216219 @app.route('/projects/')220 def projects():221 return 'The project page'217 @app.route('/projects/')218 def projects():219 return 'The project page'220223 @app.route('/about')224 def about():225 return 'The about page'221 @app.route('/about')222 def about():223 return 'The about page'224227 Though they look rather similar, they differ in their use of the trailing228 slash in the URL *definition*. In the first case, the canonical URL for the229 ``projects`` endpoint has a trailing slash. In that sense, it is similar to230 a folder on a filesystem. Accessing it without a trailing slash will cause231 Flask to redirect to the canonical URL with the trailing slash.225Though they look similar, they differ in their use of the trailing slash in226the URL. In the first case, the canonical URL for the ``projects`` endpoint227uses a trailing slash. It's similar to a folder in a file system; if you228access the URL without a trailing slash, Flask redirects you to the229canonical URL with the trailing slash.230233 In the second case, however, the URL is defined without a trailing slash,234 rather like the pathname of a file on UNIX-like systems. Accessing the URL235 with a trailing slash will produce a 404 "Not Found" error.231In the second case, however, the URL definition lacks a trailing slash,232like the pathname of a file on UNIX-like systems. Accessing the URL with a233trailing slash produces a 404 “Not Found” error.234237 This behavior allows relative URLs to continue working even if the trailing238 slash is omitted, consistent with how Apache and other servers work. Also,239 the URLs will stay unique, which helps search engines avoid indexing the240 same page twice.235This behavior allows relative URLs to continue working even if the trailing236slash is omitted, consistent with how Apache and other servers work. Also,237the URLs will stay unique, which helps search engines avoid indexing the238same page twice.239242240.. _url-building:241242URL Building243````````````244248If it can match URLs, can Flask also generate them? Of course it can. To249build a URL to a specific function you can use the :func:`~flask.url_for`250function. It accepts the name of the function as first argument and a number251of keyword arguments, each corresponding to the variable part of the URL rule.252Unknown variable parts are appended to the URL as query parameters. Here are253some examples::245To build a URL to a specific function, use the :func:`~flask.url_for` function.246It accepts the name of the function as its first argument and any number of247keyword arguments, each corresponding to a variable part of the URL rule.248Unknown variable parts are appended to the URL as query parameters.249255 >>> from flask import Flask, url_for256 >>> app = Flask(__name__)257 >>> @app.route('/')258 ... def index(): pass259 ...260 >>> @app.route('/login')261 ... def login(): pass262 ...263 >>> @app.route('/user/<username>')264 ... def profile(username): pass265 ...266 >>> with app.test_request_context():267 ... print url_for('index')268 ... print url_for('login')269 ... print url_for('login', next='/')270 ... print url_for('profile', username='John Doe')271 ...272 /273 /login274 /login?next=/275 /user/John%20Doe276277(This also uses the :meth:`~flask.Flask.test_request_context` method, explained278below. It tells Flask to behave as though it is handling a request, even279though we are interacting with it through a Python shell. Have a look at the280explanation below. :ref:`context-locals`).281250Why would you want to build URLs using the URL reversing function251:func:`~flask.url_for` instead of hard-coding them into your templates?284There are three good reasons for this:2522861. Reversing is often more descriptive than hard-coding the URLs. More287 importantly, it allows you to change URLs in one go, without having to288 remember to change URLs all over the place.2892. URL building will handle escaping of special characters and Unicode290 data transparently for you, so you don't have to deal with them.2913. If your application is placed outside the URL root - say, in292 ``/myapplication`` instead of ``/`` - :func:`~flask.url_for` will handle293 that properly for you.2531. Reversing is often more descriptive than hard-coding the URLs.2542. You can change your URLs in one go instead of needing to remember to255 manually change hard-coded URLs.2563. URL building handles escaping of special characters and Unicode data257 transparently.2584. If your application is placed outside the URL root, for example, in259 ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly260 handles that for you.261262For example, here we use the :meth:`~flask.Flask.test_request_context` method263to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`264tells Flask to behave as though it's handling a request even while we use a265Python shell. See :ref:`context-locals`. ::266267 from flask import Flask, url_for268269 app = Flask(__name__)270271 @app.route('/')272 def index():273 return 'index'274275 @app.route('/login')276 def login():277 return 'login'278279 @app.route('/user/<username>')280 def profile(username):281 return '{}'s profile'.format(username)282283 with app.test_request_context():284 print(url_for('index'))285 print(url_for('login'))286 print(url_for('login', next='/'))287 print(url_for('profile', username='John Doe'))288289 /290 /login291 /login?next=/292 /user/John%20Doe293294HTTP Methods295````````````296299HTTP (the protocol web applications are speaking) knows different methods for300accessing URLs. By default, a route only answers to ``GET`` requests, but that301can be changed by providing the ``methods`` argument to the302:meth:`~flask.Flask.route` decorator. Here are some examples::297Web applications use different HTTP methods when accessing URLs. You should298familiarize yourself with the HTTP methods as you work with Flask. By default,299a route only answers to ``GET`` requests. You can use the ``methods`` argument300of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.301::302304 from flask import request305303 @app.route('/login', methods=['GET', 'POST'])304 def login():305 if request.method == 'POST':306 do_the_login()307 else:308 show_the_login_form()309313If ``GET`` is present, ``HEAD`` will be added automatically for you. You314don't have to deal with that. It will also make sure that ``HEAD`` requests315are handled as the `HTTP RFC`_ (the document describing the HTTP316protocol) demands, so you can completely ignore that part of the HTTP317specification. Likewise, as of Flask 0.6, ``OPTIONS`` is implemented for you318automatically as well.310If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method311and handles ``HEAD`` requests according to the the `HTTP RFC`_. Likewise,312``OPTIONS`` is automatically implemented for you.313320You have no idea what an HTTP method is? Worry not, here is a quick321introduction to HTTP methods and why they matter:314.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt315323The HTTP method (also often called "the verb") tells the server what the324client wants to *do* with the requested page. The following methods are325very common:326327``GET``328 The browser tells the server to just *get* the information stored on329 that page and send it. This is probably the most common method.330331``HEAD``332 The browser tells the server to get the information, but it is only333 interested in the *headers*, not the content of the page. An334 application is supposed to handle that as if a ``GET`` request was335 received but to not deliver the actual content. In Flask you don't336 have to deal with that at all, the underlying Werkzeug library handles337 that for you.338339``POST``340 The browser tells the server that it wants to *post* some new341 information to that URL and that the server must ensure the data is342 stored and only stored once. This is how HTML forms usually343 transmit data to the server.344345``PUT``346 Similar to ``POST`` but the server might trigger the store procedure347 multiple times by overwriting the old values more than once. Now you348 might be asking why this is useful, but there are some good reasons349 to do it this way. Consider that the connection is lost during350 transmission: in this situation a system between the browser and the351 server might receive the request safely a second time without breaking352 things. With ``POST`` that would not be possible because it must only353 be triggered once.354355``DELETE``356 Remove the information at the given location.357358``OPTIONS``359 Provides a quick way for a client to figure out which methods are360 supported by this URL. Starting with Flask 0.6, this is implemented361 for you automatically.362363Now the interesting part is that in HTML4 and XHTML1, the only methods a364form can submit to the server are ``GET`` and ``POST``. But with JavaScript365and future HTML standards you can use the other methods as well. Furthermore366HTTP has become quite popular lately and browsers are no longer the only367clients that are using HTTP. For instance, many revision control systems368use it.369370.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt371316Static Files317------------318319Dynamic web applications also need static files. That's usually where
161 unmodified lines
481The Request Object482``````````````````483484The request object is documented in the API section and we will not cover541it here in detail (see :class:`~flask.request`). Here is a broad overview of485it here in detail (see :class:`~flask.Request`). Here is a broad overview of486some of the most common operations. First of all you have to import it from487the ``flask`` module::488489 from flask import request490491The current request method is available by using the548:attr:`~flask.request.method` attribute. To access form data (data492:attr:`~flask.Request.method` attribute. To access form data (data493transmitted in a ``POST`` or ``PUT`` request) you can use the550:attr:`~flask.request.form` attribute. Here is a full example of the two494:attr:`~flask.Request.form` attribute. Here is a full example of the two495attributes mentioned above::496497 @app.route('/login', methods=['POST', 'GET'])498 def login():
14 unmodified lines
513error page is shown instead. So for many situations you don't have to514deal with that problem.515516To access parameters submitted in the URL (``?key=value``) you can use the573:attr:`~flask.request.args` attribute::517:attr:`~flask.Request.args` attribute::518519 searchword = request.args.get('key', '')520521We recommend accessing URL parameters with `get` or by catching the522:exc:`KeyError` because users might change the URL and presenting them a 400523bad request page in that case is not user friendly.524525For a full list of methods and attributes of the request object, head over582to the :class:`~flask.request` documentation.526to the :class:`~flask.Request` documentation.527528529File Uploads530````````````
307 unmodified lines
modified:docs/security.rst+1 added-1 removed
13 unmodified lines
14it JavaScript) into the context of a website. To remedy this, developers15have to properly escape text so that it cannot include arbitrary HTML16tags. For more information on that have a look at the Wikipedia article17on `Cross-Site Scripting18<http://en.wikipedia.org/wiki/Cross-site_scripting>`_.18<https://en.wikipedia.org/wiki/Cross-site_scripting>`_.1920Flask configures Jinja2 to automatically escape all values unless21explicitly told otherwise. This should rule out all XSS problems caused22in templates, but there are still other places where you have to be
84 unmodified lines
modified:docs/styleguide.rst+1 added-1 removed
165 unmodified lines
166 is on its own line.167 """168169Module header:170 The module header consists of an utf-8 encoding declaration (if non170 The module header consists of a utf-8 encoding declaration (if non171 ASCII letters are used, but it is recommended all the time) and a172 standard docstring::173174 # -*- coding: utf-8 -*-
26 unmodified lines
modified:docs/testing.rst+6 added-4 removed
31 unmodified lines
32In order to test the application, we add a second module33(:file:`flaskr_tests.py`) and create a unittest skeleton there::3435 import os36 import flaskr36 from flaskr import flaskr37 import unittest38 import tempfile3940 class FlaskrTestCase(unittest.TestCase):4142 def setUp(self):43 self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()44 flaskr.app.config['TESTING'] = True44 flaskr.app.testing = True45 self.app = flaskr.app.test_client()46 with flaskr.app.app_context():47 flaskr.init_db()48
48 unmodified lines
97 class FlaskrTestCase(unittest.TestCase):9899 def setUp(self):100 self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()101 flaskr.app.testing = True102 self.app = flaskr.app.test_client()103 with flaskr.app.app_context():102 flaskr.init_db()104 flaskr.init_db()105106 def tearDown(self):107 os.close(self.db_fd)108 os.unlink(flaskr.app.config['DATABASE'])
100 unmodified lines
209:class:`~flask.g` and :class:`~flask.session` objects like in view210functions. Here is a full example that demonstrates this approach::211212 import flask211 213214 app = flask.Flask(__name__)215216 with app.test_request_context('/?name=Peter'):217 assert flask.request.path == '/'
140 unmodified lines
modified:docs/upgrading.rst+3 added-3 removed
47 unmodified lines
48 # ETag still needs to be manually set49 response = send_file(open(fname), attachment_filename=fname)50 response.set_etag(...)5152The reason for this is that some file-like objects have a invalid or even52The reason for this is that some file-like objects have an invalid or even53misleading ``name`` attribute. Silently swallowing errors in such cases was not54a satisfying solution.5556Additionally the default of falling back to ``application/octet-stream`` has
85 unmodified lines
142when there is no request context yet but an application context. The old143``flask.Flask.request_globals_class`` attribute was renamed to144:attr:`flask.Flask.app_ctx_globals_class`.145146.. _Flask-OldSessions: http://pythonhosted.org/Flask-OldSessions/146.. _Flask-OldSessions: https://pythonhosted.org/Flask-OldSessions/147148Version 0.9149-----------150
46 unmodified lines
197applications with Flask. Because we want to make upgrading as easy as198possible we tried to counter the problems arising from these changes by199providing a script that can ease the transition.200201The script scans your whole application and generates an unified diff with201The script scans your whole application and generates a unified diff with202changes it assumes are safe to apply. However as this is an automated203tool it won't be able to find all use cases and it might miss some. We204internally spread a lot of deprecation warnings all over the place to make205it easy to find pieces of code that it was unable to upgrade.
267 unmodified lines
modified:examples/flaskr/flaskr/__init__.py+1 added-1 removed
1from flaskr.flaskr import app1from .flaskr import app
modified:examples/flaskr/setup.cfg+1 added-1 removed
1[aliases]1[tool:pytest]2test=pytest
modified:examples/minitwit/minitwit/__init__.py+1 added-1 removed
1from minitwit import app1from .minitwit import app
modified:examples/minitwit/minitwit/minitwit.py+1 added-1 removed
83 unmodified lines
848586def gravatar_url(email, size=80):87 """Return the gravatar image for the given email address."""88 return 'http://www.gravatar.com/avatar/%s?d=identicon&s=%d' % \88 return 'https://www.gravatar.com/avatar/%s?d=identicon&s=%d' % \89 (md5(email.strip().lower().encode('utf-8')).hexdigest(), size)909192@app.before_request
164 unmodified lines
modified:examples/minitwit/README+7 added-3 removed
12 unmodified lines
13 1. edit the configuration in the minitwit.py file or14 export an MINITWIT_SETTINGS environment variable15 pointing to a configuration file.1617 2. tell flask about the right application:17 2. install the app from the root of the project directory1819 pip install --editable .2021 3. tell flask about the right application:2223 export FLASK_APP=minitwit2421 2. fire up a shell and run this:25 4. fire up a shell and run this:2627 flask initdb2825 3. now you can run minitwit:29 5. now you can run minitwit:3031 flask run3233 the application will greet you on
6 unmodified lines
added:examples/patterns/largerapp/tests/test_largerapp.py+12 added
1from yourapplication import app2import pytest34@pytest.fixture5def client():6 app.config['TESTING'] = True7 client = app.test_client()8 return client910def test_index(client):11 rv = client.get('/')12 assert b"Hello World!" in rv.data
added:examples/patterns/largerapp/yourapplication/static/style.css
added:examples/patterns/largerapp/yourapplication/templates/index.html
added:examples/patterns/largerapp/yourapplication/templates/layout.html
added:examples/patterns/largerapp/yourapplication/templates/login.html
added:examples/patterns/largerapp/yourapplication/__init__.py+4 added
1from flask import Flask2app = Flask(__name__)34import yourapplication.views
added:examples/patterns/largerapp/yourapplication/views.py+5 added
1from yourapplication import app23@app.route('/')4def index():5 return 'Hello World!'
added:examples/patterns/largerapp/setup.py+10 added
1from setuptools import setup23setup(4 name='yourapplication',5 packages=['yourapplication'],6 include_package_data=True,7 install_requires=[8 'flask',9 ],10)
modified:flask/__init__.py+2 added-2 removed
8 unmodified lines
9 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213__version__ = '0.11.2-dev'13__version__ = '0.13-dev'1415# utilities we import from Werkzeug and Jinja2 that are unused16# in the module but are exported as public interface.17from werkzeug.exceptions import abort
21 unmodified lines
39# We're not exposing the actual json module but a convenient wrapper around40# it.41from . import json4243# This was the only thing that flask used to export at one point and it had43# This was the only thing that Flask used to export at one point and it had44# a more generic name.45jsonify = json.jsonify4647# backwards compat, goes away in 1.0
2 unmodified lines
modified:flask/app.py+198 added-127 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11import os12import sys13from threading import Lock13from datetime import timedelta15from itertools import chain14from functools import update_wrapper17from collections import deque15from itertools import chain16from threading import Lock1719from werkzeug.datastructures import ImmutableDict20from werkzeug.routing import Map, Rule, RequestRedirect, BuildError21from werkzeug.exceptions import HTTPException, InternalServerError, \22 MethodNotAllowed, BadRequest, default_exceptions18from werkzeug.datastructures import ImmutableDict, Headers19from werkzeug.exceptions import BadRequest, HTTPException, \20 InternalServerError, MethodNotAllowed, default_exceptions21from werkzeug.routing import BuildError, Map, RequestRedirect, Rule2224from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \25 locked_cached_property, _endpoint_from_view_func, find_package, \26 get_debug_flag27from . import json, cli28from .wrappers import Request, Response29from .config import ConfigAttribute, Config30from .ctx import RequestContext, AppContext, _AppCtxGlobals31from .globals import _request_ctx_stack, request, session, g23from . import cli, json24from ._compat import integer_types, reraise, string_types, text_type25from .config import Config, ConfigAttribute26from .ctx import AppContext, RequestContext, _AppCtxGlobals27from .globals import _request_ctx_stack, g, request, session28from .helpers import _PackageBoundObject, \29 _endpoint_from_view_func, find_package, get_debug_flag, \30 get_flashed_messages, locked_cached_property, url_for31from .sessions import SecureCookieSessionInterface32from .signals import appcontext_tearing_down, got_request_exception, \33 request_finished, request_started, request_tearing_down34from .templating import DispatchingJinjaLoader, Environment, \34 _default_template_ctx_processor35from .signals import request_started, request_finished, got_request_exception, \36 request_tearing_down, appcontext_tearing_down37from ._compat import reraise, string_types, text_type, integer_types35 _default_template_ctx_processor36from .wrappers import Request, Response3738# a lock used for logger initialization39_logger_lock = Lock()40
81 unmodified lines
122123 .. versionadded:: 0.11124 The `root_path` parameter was added.125126 .. versionadded:: 0.13127 The `host_matching` and `static_host` parameters were added.128129 :param import_name: the name of the application package130 :param static_url_path: can be used to specify a different path for the131 static files on the web. Defaults to the name132 of the `static_folder` folder.133 :param static_folder: the folder with static files that should be served134 at `static_url_path`. Defaults to the ``'static'``135 folder in the root path of the application.136 folder in the root path of the application. Defaults137 to None.138 :param host_matching: sets the app's ``url_map.host_matching`` to the given139 given value. Defaults to False.140 :param static_host: the host to use when adding the static route. Defaults141 to None. Required when using ``host_matching=True``142 with a ``static_folder`` configured.143 :param template_folder: the folder that contains the templates that should144 be used by the application. Defaults to145 ``'templates'`` folder in the root path of the146 application.
176 unmodified lines
323 'EXPLAIN_TEMPLATE_LOADING': False,324 'PREFERRED_URL_SCHEME': 'http',325 'JSON_AS_ASCII': True,326 'JSON_SORT_KEYS': True,318 'JSONIFY_PRETTYPRINT_REGULAR': True,327 'JSONIFY_PRETTYPRINT_REGULAR': False,328 'JSONIFY_MIMETYPE': 'application/json',329 'TEMPLATES_AUTO_RELOAD': None,330 })331
14 unmodified lines
346 #: .. versionadded:: 0.8347 session_interface = SecureCookieSessionInterface()348349 def __init__(self, import_name, static_path=None, static_url_path=None,341 static_folder='static', template_folder='templates',350 static_folder='static', static_host=None,351 host_matching=False, template_folder='templates',352 instance_path=None, instance_relative_config=False,353 root_path=None):354 _PackageBoundObject.__init__(self, import_name,355 template_folder=template_folder,
45 unmodified lines
401 #: special key ``None`` points to a list of tuples where the first item402 #: is the class for the instance check and the second the error handler403 #: function.404 #:395 #: To register a error handler, use the :meth:`errorhandler`405 #: To register an error handler, use the :meth:`errorhandler`406 #: decorator.407 self.error_handler_spec = {None: self._error_handlers}408409 #: A list of functions that are called when :meth:`url_for` raises a
4 unmodified lines
414 #:415 #: .. versionadded:: 0.9416 self.url_build_error_handlers = []417408 #: A dictionary with lists of functions that should be called at the409 #: beginning of the request. The key of the dictionary is the name of410 #: the blueprint this function is active for, ``None`` for all requests.411 #: This can for example be used to open database connections or412 #: getting hold of the currently logged in user. To register a413 #: function here, use the :meth:`before_request` decorator.418 #: A dictionary with lists of functions that will be called at the419 #: beginning of each request. The key of the dictionary is the name of420 #: the blueprint this function is active for, or ``None`` for all421 #: requests. To register a function, use the :meth:`before_request`422 #: decorator.423 self.before_request_funcs = {}424416 #: A lists of functions that should be called at the beginning of the417 #: first request to this instance. To register a function here, use418 #: the :meth:`before_first_request` decorator.425 #: A list of functions that will be called at the beginning of the426 #: first request to this instance. To register a function, use the427 #: :meth:`before_first_request` decorator.428 #:429 #: .. versionadded:: 0.8430 self.before_first_request_funcs = []431
23 unmodified lines
455 #:456 #: .. versionadded:: 0.9457 self.teardown_appcontext_funcs = []458450 #: A dictionary with lists of functions that can be used as URL451 #: value processor functions. Whenever a URL is built these functions452 #: are called to modify the dictionary of values in place. The key453 #: ``None`` here is used for application wide454 #: callbacks, otherwise the key is the name of the blueprint.455 #: Each of these functions has the chance to modify the dictionary459 #: A dictionary with lists of functions that are called before the460 #: :attr:`before_request_funcs` functions. The key of the dictionary is461 #: the name of the blueprint this function is active for, or ``None``462 #: for all requests. To register a function, use463 #: :meth:`url_value_preprocessor`.464 #:465 #: .. versionadded:: 0.7466 self.url_value_preprocessors = {}467
65 unmodified lines
533 #: app = Flask(__name__)534 #: app.url_map.converters['list'] = ListConverter535 self.url_map = Map()536537 self.url_map.host_matching = host_matching538539 # tracks internally if the application already handled at least one540 # request.541 self._got_first_request = False542 self._before_request_lock = Lock()543534 # register the static folder for the application. Do that even535 # if the folder does not exist. First of all it might be created536 # while the server is running (usually happens during development)537 # but also because google appengine stores static files somewhere538 # else when mapped with the .yml file.544 # Add a static route using the provided static_url_path, static_host,545 # and static_folder if there is a configured static_folder.546 # Note we do this without checking if static_folder exists.547 # For one, it might be created while the server is running (e.g. during548 # development). Also, Google App Engine stores static files somewhere549 if self.has_static_folder:550 assert bool(static_host) == host_matching, 'Invalid static_host/host_matching combination'551 self.add_url_rule(self.static_url_path + '/<path:filename>',541 endpoint='static',552 endpoint='static', host=static_host,553 view_func=self.send_static_file)554555 #: The click command line context for this application. Commands556 #: registered here show up in the :command:`flask` command once the
267 unmodified lines
824 The default port is now picked from the ``SERVER_NAME`` variable.825826 :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to827 have the server available externally as well. Defaults to817 ``'127.0.0.1'``.828 ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config829 variable if present.830 :param port: the port of the webserver. Defaults to ``5000`` or the831 port defined in the ``SERVER_NAME`` config variable if832 present.833 :param debug: if given, enable or disable debug mode.
2 unmodified lines
836 Werkzeug server. See837 :func:`werkzeug.serving.run_simple` for more838 information.839 """840 # Change this into a no-op if the server is invoked from the841 # command line. Have a look at cli.py for more information.842 if os.environ.get('FLASK_RUN_FROM_CLI_SERVER') == '1':843 from .debughelpers import explain_ignored_app_run844 explain_ignored_app_run()845 return846847 from werkzeug.serving import run_simple829 if host is None:830 host = '127.0.0.1'831 if port is None:832 server_name = self.config['SERVER_NAME']833 if server_name and ':' in server_name:834 port = int(server_name.rsplit(':', 1)[1])835 else:836 port = 5000848 _host = '127.0.0.1'849 _port = 5000850 server_name = self.config.get("SERVER_NAME")851 sn_host, sn_port = None, None852 if server_name:853 sn_host, _, sn_port = server_name.partition(':')854 host = host or sn_host or _host855 port = int(port or sn_port or _port)856 if debug is not None:857 self.debug = bool(debug)858 options.setdefault('use_reloader', self.debug)859 options.setdefault('use_debugger', self.debug)
117 unmodified lines
977 """978 return iter(self._blueprint_order)979980 @setupmethod962 def add_url_rule(self, rule, endpoint=None, view_func=None, **options):981 def add_url_rule(self, rule, endpoint=None, view_func=None, provide_automatic_options=None, **options):982 """Connects a URL rule. Works exactly like the :meth:`route`983 decorator. If a view_func is provided it will be registered with the984 endpoint.985
31 unmodified lines
1017 itself assumes the name of the view function as1018 endpoint1019 :param view_func: the function to call when serving a request to the1020 provided endpoint1021 :param provide_automatic_options: controls whether the ``OPTIONS``1022 method should be added automatically. This can also be controlled1023 by setting the ``view_func.provide_automatic_options = False``1024 before adding the rule.1025 :param options: the options to be forwarded to the underlying1026 :class:`~werkzeug.routing.Rule` object. A change1027 to Werkzeug is handling of method options. methods1028 is a list of methods this rule should be limited
21 unmodified lines
1050 required_methods = set(getattr(view_func, 'required_methods', ()))10511052 # starting with Flask 0.8 the view_func object can disable and1053 # force-enable the automatic options handling.1054 if provide_automatic_options is None:1031 provide_automatic_options = getattr(view_func,1032 'provide_automatic_options', None)1055 provide_automatic_options = getattr(view_func,1056 'provide_automatic_options', None)10571058 if provide_automatic_options is None:1059 if 'OPTIONS' not in methods:1060 provide_automatic_options = True
115 unmodified lines
1176 One can now additionally also register custom exception types1177 that do not necessarily have to be a subclass of the1178 :class:`~werkzeug.exceptions.HTTPException` class.11791156 :param code: the code as integer for the handler1180 :param code_or_exception: the code as integer for the handler, or1181 an arbitrary exception1182 """1183 def decorator(f):1184 self._register_error_handler(None, code_or_exception, f)1185 return f
125 unmodified lines
13111312 @setupmethod1313 def before_request(self, f):1314 """Registers a function to run before each request.1315 1316 For example, this can be used to open a database connection, or to load1317 the logged in user from the session.13181291 The function will be called without any arguments.1292 If the function returns a non-None value, it's handled as1293 if it was the return value from the view and further1294 request handling is stopped.1319 The function will be called without any arguments. If it returns a1320 non-None value, the value is handled as if it was the return value from1321 the view, and further request handling is stopped.1322 """1323 self.before_request_funcs.setdefault(None, []).append(f)1324 return f1325
47 unmodified lines
1373 that they will fail. If they do execute code that might fail they1374 will have to surround the execution of these code by try/except1375 statements and log occurring errors.13761350 When a teardown function was called because of a exception it will1377 When a teardown function was called because of an exception it will1378 be passed an error object.13791380 The return values of teardown functions are ignored.1381
54 unmodified lines
1436 return f14371438 @setupmethod1439 def url_value_preprocessor(self, f):1413 """Registers a function as URL value preprocessor for all view1414 functions of the application. It's called before the view functions1415 are called and can modify the url values provided.1440 """Register a URL value preprocessor function for all view1441 functions in the application. These functions will be called before the1442 :meth:`before_request` functions.1443 1444 The function can modify the values captured from the matched url before1445 they are passed to the view. For example, this can be used to pop a1446 common language code value and place it in ``g`` rather than pass it to1447 every view.1448 1449 The function is passed the endpoint name and values dict. The return1450 value is ignored.1451 """1452 self.url_value_preprocessors.setdefault(None, []).append(f)1453 return f1454
15 unmodified lines
14701471 def find_handler(handler_map):1472 if not handler_map:1473 return1439 queue = deque(exc_class.__mro__)1440 # Protect from geniuses who might create circular references in1441 # __mro__1442 done = set()14431444 while queue:1445 cls = queue.popleft()1446 if cls in done:1447 continue1448 done.add(cls)1474 for cls in exc_class.__mro__:1475 handler = handler_map.get(cls)1476 if handler is not None:1477 # cache for next time exc_class is raised1478 handler_map[exc_class] = handler1479 return handler14801455 queue.extend(cls.__mro__)14561481 # try blueprint handlers1482 handler = find_handler(self.error_handler_spec1483 .get(request.blueprint, {})1484 .get(code))
237 unmodified lines
1722 """1723 return False17241725 def make_response(self, rv):1702 """Converts the return value from a view function to a real1703 response object that is an instance of :attr:`response_class`.1726 """Convert the return value from a view function to an instance of1727 :attr:`response_class`.17281705 The following types are allowed for `rv`:1729 :param rv: the return value from the view function. The view function1730 must return a response. Returning ``None``, or the view ending1731 without returning, is not allowed. The following types are allowed1732 for ``view_rv``:17331707 .. tabularcolumns:: |p{3.5cm}|p{9.5cm}|1734 ``str`` (``unicode`` in Python 2)1735 A response object is created with the string encoded to UTF-81736 as the body.1737 1738 ``bytes`` (``str`` in Python 2)1739 A response object is created with the bytes as the body.1740 1741 ``tuple``1742 Either ``(body, status, headers)``, ``(body, status)``, or1743 ``(body, headers)``, where ``body`` is any of the other types1744 allowed here, ``status`` is a string or an integer, and1745 ``headers`` is a dictionary or a list of ``(key, value)``1746 tuples. If ``body`` is a :attr:`response_class` instance,1747 ``status`` overwrites the exiting value and ``headers`` are1748 extended.1749 1750 :attr:`response_class`1751 The object is returned unchanged.1752 1753 other :class:`~werkzeug.wrappers.Response` class1754 The object is coerced to :attr:`response_class`.1755 1756 :func:`callable`1757 The function is called as a WSGI application. The result is1758 used to create a response object.17591709 ======================= ===========================================1710 :attr:`response_class` the object is returned unchanged1711 :class:`str` a response object is created with the1712 string as body1713 :class:`unicode` a response object is created with the1714 string encoded to utf-8 as body1715 a WSGI function the function is called as WSGI application1716 and buffered as response object1717 :class:`tuple` A tuple in the form ``(response, status,1718 headers)`` or ``(response, headers)``1719 where `response` is any of the1720 types defined here, `status` is a string1721 or an integer and `headers` is a list or1722 a dictionary with header values.1723 ======================= ===========================================17241725 :param rv: the return value from the view function17261760 .. versionchanged:: 0.91761 Previously a tuple was interpreted as the arguments for the1762 response object.1763 """1731 status_or_headers = headers = None1732 if isinstance(rv, tuple):1733 rv, status_or_headers, headers = rv + (None,) * (3 - len(rv))17641735 if rv is None:1736 raise ValueError('View function did not return a response')1765 status = headers = None17661738 if isinstance(status_or_headers, (dict, list)):1739 headers, status_or_headers = status_or_headers, None1767 # unpack tuple returns1768 if isinstance(rv, (tuple, list)):1769 len_rv = len(rv)17701771 # a 3-tuple is unpacked directly1772 if len_rv == 3:1773 rv, status, headers = rv1774 # decide if a 2-tuple has status or headers1775 elif len_rv == 2:1776 if isinstance(rv[1], (Headers, dict, tuple, list)):1777 rv, headers = rv1778 else:1779 rv, status = rv1780 # other sized tuples are not allowed1781 else:1782 raise TypeError(1783 'The view function did not return a valid response tuple.'1784 ' The tuple must have the form (body, status, headers),'1785 ' (body, status), or (body, headers).'1786 )17871788 # the body must not be None1789 if rv is None:1790 raise TypeError(1791 'The view function did not return a valid response. The'1792 ' function either returned None or ended without a return'1793 ' statement.'1794 )17951796 # make sure the body is an instance of the response class1797 if not isinstance(rv, self.response_class):1742 # When we create a response object directly, we let the constructor1743 # set the headers and status. We do this because there can be1744 # some extra logic involved when creating these objects with1745 # specific values (like default content type selection).1798 if isinstance(rv, (text_type, bytes, bytearray)):1747 rv = self.response_class(rv, headers=headers,1748 status=status_or_headers)1749 headers = status_or_headers = None1799 # let the response class set the status and headers instead of1800 # waiting to do it manually, so that the class can handle any1801 # special logic1802 rv = self.response_class(rv, status=status, headers=headers)1803 status = headers = None1804 else:1805 # evaluate a WSGI callable, or coerce a different response1806 # class to the correct type1807 try:1751 rv = self.response_class.force_type(rv, request.environ)1808 rv = self.response_class.force_type(rv, request.environ)1809 except TypeError as e:1810 new_error = TypeError(1811 '{e}\nThe view function did not return a valid'1812 ' response. The return type must be a string, tuple,'1813 ' Response instance, or WSGI callable, but it was a'1814 ' {rv.__class__.__name__}.'.format(e=e, rv=rv)1815 )1816 reraise(TypeError, new_error, sys.exc_info()[2])18171818 # prefer the status if it was provided1753 if status_or_headers is not None:1754 if isinstance(status_or_headers, string_types):1755 rv.status = status_or_headers1819 if status is not None:1820 if isinstance(status, (text_type, bytes, bytearray)):1821 rv.status = status1822 else:1757 rv.status_code = status_or_headers1823 rv.status_code = status18241825 # extend existing headers with provided headers1826 if headers:1827 rv.headers.extend(headers)18281829 return rv
54 unmodified lines
1884 reraise(exc_type, exc_value, tb)1885 raise error18861887 def preprocess_request(self):1820 """Called before the actual request dispatching and will1821 call each :meth:`before_request` decorated function, passing no1822 arguments.1823 If any of these functions returns a value, it's handled as1824 if it was the return value from the view and further1825 request handling is stopped.18261827 This also triggers the :meth:`url_value_preprocessor` functions before1828 the actual :meth:`before_request` functions are called.1888 """Called before the request is dispatched. Calls1889 :attr:`url_value_preprocessors` registered with the app and the1890 current blueprint (if any). Then calls :attr:`before_request_funcs`1891 registered with the app and the blueprint.1892 1893 If any :meth:`before_request` handler returns a non-None value, the1894 value is handled as if it was the return value from the view, and1895 further request handling is stopped.1896 """18971898 bp = _request_ctx_stack.top.request.blueprint18991900 funcs = self.url_value_preprocessors.get(None, ())1901 if bp is not None and bp in self.url_value_preprocessors:
151 unmodified lines
2053 a list of headers and an optional2054 exception context to start the response2055 """2056 ctx = self.request_context(environ)1989 ctx.push()2057 error = None2058 try:2059 try:2060 ctx.push()2061 response = self.full_dispatch_request()2062 except Exception as e:2063 error = e2064 response = self.handle_exception(e)2065 except:2066 error = sys.exc_info()[1]2067 raise2068 return response(environ, start_response)2069 finally:2070 if self.should_ignore_error(error):2071 error = None
11 unmodified lines
modified:flask/blueprints.py+7 added
87 unmodified lines
8889 warn_on_modifications = False90 _got_registered_once = False9192 #: Blueprint local JSON decoder class to use.93 #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_encoder`.94 json_encoder = None95 #: Blueprint local JSON decoder class to use.96 #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_decoder`.97 json_decoder = None9899 def __init__(self, name, import_name, static_folder=None,100 static_url_path=None, template_folder=None,101 url_prefix=None, subdomain=None, url_defaults=None,102 root_path=None):
318 unmodified lines
modified:flask/cli.py+78 added-9 removed
9 unmodified lines
10"""1112import os13import sys14from threading import Lock, Thread14import traceback15from functools import update_wrapper16from operator import attrgetter17from threading import Lock, Thread1819import click2021from . import __version__22from ._compat import iteritems, reraise23from .globals import current_app24from .helpers import get_debug_flag21from . import __version__252627class NoAppException(click.UsageError):28 """Raised if an application cannot be found or loaded."""2930
61 unmodified lines
9293 try:94 __import__(module)95 except ImportError:92 raise NoAppException('The file/path provided (%s) does not appear to '93 'exist. Please verify the path is correct. If '94 'app is not on PYTHONPATH, ensure the extension '95 'is .py' % module)96 # Reraise the ImportError if it occurred within the imported module.97 # Determine this by checking whether the trace has a depth > 1.98 if sys.exc_info()[-1].tb_next:99 stack_trace = traceback.format_exc()100 raise NoAppException('There was an error trying to import'101 ' the app (%s):\n%s' % (module, stack_trace))102 else:103 raise NoAppException('The file/path provided (%s) does not appear'104 ' to exist. Please verify the path is '105 'correct. If app is not on PYTHONPATH, '106 'ensure the extension is .py' % module)107108 mod = sys.modules[module]109 if app_obj is None:110 app = find_best_app(mod)111 else:
30 unmodified lines
142 callback=get_version,143 is_flag=True, is_eager=True)144145class DispatchingApp(object):134 """Special application that dispatches to a flask application which146 """Special application that dispatches to a Flask application which147 is imported by name in a background thread. If an error happens136 it is is recorded and shows as part of the WSGI handling which in case148 it is recorded and shown as part of the WSGI handling which in case149 of the Werkzeug debugger means that it shows up in the browser.150 """151152 def __init__(self, loader, use_eager_loading=False):
168 unmodified lines
321322 if add_default_commands:323 self.add_command(run_command)324 self.add_command(shell_command)325 self.add_command(routes_command)326327 self._loaded_plugin_commands = False328329 def _load_plugin_commands(self):
44 unmodified lines
374 # Here we intentionally swallow all exceptions as we don't375 # want the help page to break if the app does not exist.376 # If someone attempts to use the command we try to create377 # the app again and this will give us the error.365 pass378 # However, we will not do so silently because that would confuse379 # users.380 traceback.print_exc()381 return sorted(rv)382383 def main(self, *args, **kwargs):384 obj = kwargs.get('obj')
35 unmodified lines
420 Flask is enabled and disabled otherwise.421 """422 from werkzeug.serving import run_simple423424 # Set a global flag that indicates that we were invoked from the425 # command line interface provided server command. This is detected426 # by Flask.run to make the call into a no-op. This is necessary to427 # avoid ugly errors when the script that is loaded here also attempts428 # to start a server.429 os.environ['FLASK_RUN_FROM_CLI_SERVER'] = '1'430431 debug = get_debug_flag()432 if reload is None:433 reload = bool(debug)434 if debugger is None:
52 unmodified lines
487488 code.interact(banner=banner, local=ctx)489490491@click.command('routes', short_help='Show the routes for the app.')492@click.option(493 '--sort', '-s',494 type=click.Choice(('endpoint', 'methods', 'rule', 'match')),495 default='endpoint',496 help=(497 'Method to sort routes by. "match" is the order that Flask will match '498 'routes when dispatching a request.'499 )500)501@click.option(502 '--all-methods',503 is_flag=True,504 help="Show HEAD and OPTIONS methods."505)506@with_appcontext507def routes_command(sort, all_methods):508 """Show all registered routes with endpoints and methods."""509510 rules = list(current_app.url_map.iter_rules())511 ignored_methods = set(() if all_methods else ('HEAD', 'OPTIONS'))512513 if sort in ('endpoint', 'rule'):514 rules = sorted(rules, key=attrgetter(sort))515 elif sort == 'methods':516 rules = sorted(rules, key=lambda rule: sorted(rule.methods))517518 rule_methods = [519 ', '.join(sorted(rule.methods - ignored_methods)) for rule in rules520 ]521522 headers = ('Endpoint', 'Methods', 'Rule')523 widths = (524 max(len(rule.endpoint) for rule in rules),525 max(len(methods) for methods in rule_methods),526 max(len(rule.rule) for rule in rules),527 )528 widths = [max(len(h), w) for h, w in zip(headers, widths)]529 row = '{{0:<{0}}} {{1:<{1}}} {{2:<{2}}}'.format(*widths)530531 click.echo(row.format(*headers).strip())532 click.echo(row.format(*('-' * width for width in widths)))533534 for rule, methods in zip(rules, rule_methods):535 click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())536537538cli = FlaskGroup(help="""\539This shell command acts as general utility script for Flask applications.540541It loads the application configured (through the FLASK_APP environment
39 unmodified lines
modified:flask/config.py+1 added-1 removed
124 unmodified lines
125 filename = os.path.join(self.root_path, filename)126 d = types.ModuleType('config')127 d.__file__ = filename128 try:129 with open(filename) as config_file:129 with open(filename, mode='rb') as config_file:130 exec(compile(config_file.read(), filename, 'exec'), d.__dict__)131 except IOError as e:132 if silent and e.errno in (errno.ENOENT, errno.EISDIR):133 return False
130 unmodified lines
modified:flask/debughelpers.py+12 added
6 unmodified lines
78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import os12from warnings import warn1314from ._compat import implements_to_string, text_type15from .app import Flask16from .blueprints import Blueprint17from .globals import _request_ctx_stack
137 unmodified lines
155 info.append(' Maybe you did not place a template in the right folder?')156 info.append(' See http://flask.pocoo.org/docs/blueprints/#templates')157158 app.logger.info('\n'.join(info))159160161def explain_ignored_app_run():162 if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':163 warn(Warning('Silently ignoring app.run() because the '164 'application is run from the flask command line '165 'executable. Consider putting app.run() behind an '166 'if __name__ == "__main__" guard to silence this '167 'warning.'), stacklevel=3)
modified:flask/helpers.py+44 added-4 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""1112import os13import socket14import sys15import pkgutil16import posixpath17import mimetypes18from time import time19from zlib import adler3220from threading import RLock21import unicodedata22from werkzeug.routing import BuildError23from functools import update_wrapper2425try:
33 unmodified lines
59def get_debug_flag(default=None):60 val = os.environ.get('FLASK_DEBUG')61 if not val:62 return default61 return val not in ('0', 'false', 'no')63 return val.lower() not in ('0', 'false', 'no')646566def _endpoint_from_view_func(view_func):67 """Internal helper that returns the default endpoint for a given
263 unmodified lines
331 # deal with that sort of stuff.332 values['_external'] = external333 values['_anchor'] = anchor334 values['_method'] = method335 values['_scheme'] = scheme336 return appctx.app.handle_url_build_error(error, endpoint, values)337338 if anchor is not None:339 rv += '#' + url_quote(anchor)
139 unmodified lines
479480 .. versionchanged:: 0.12481 The `attachment_filename` is preferred over `filename` for MIME-type482 detection.483 484 .. versionchanged:: 0.13485 UTF-8 filenames, as specified in `RFC 2231`_, are supported.486 487 .. _RFC 2231: https://tools.ietf.org/html/rfc2231#section-4488481 :param filename_or_fp: the filename of the file to send in `latin-1`.489 :param filename_or_fp: the filename of the file to send.490 This is relative to the :attr:`~Flask.root_path`491 if a relative path is specified.492 Alternatively a file object might be provided in493 which case ``X-Sendfile`` might not work and fall
47 unmodified lines
541 if as_attachment:542 if attachment_filename is None:543 raise TypeError('filename unavailable, required for '544 'sending as attachment')537 headers.add('Content-Disposition', 'attachment',538 filename=attachment_filename)545546 try:547 attachment_filename = attachment_filename.encode('latin-1')548 except UnicodeEncodeError:549 filenames = {550 'filename': unicodedata.normalize(551 'NFKD', attachment_filename).encode('latin-1', 'ignore'),552 'filename*': "UTF-8''%s" % url_quote(attachment_filename),553 }554 else:555 filenames = {'filename': attachment_filename}556557 headers.add('Content-Disposition', 'attachment', **filenames)558559 if current_app.use_x_sendfile and filename:560 if file is not None:561 file.close()562 headers['X-Sendfile'] = filename
413 unmodified lines
976 :returns: number of seconds977 :rtype: int978 """979 return td.days * 60 * 60 * 24 + td.seconds980981982def is_ip(value):983 """Determine if the given string is an IP address.984985 :param value: value to check986 :type value: str987988 :return: True if string is an IP address989 :rtype: bool990 """991992 for family in (socket.AF_INET, socket.AF_INET6):993 try:994 socket.inet_pton(family, value)995 except socket.error:996 pass997 else:998 return True9991000 return False
modified:flask/json.py+21 added-10 removed
1# -*- coding: utf-8 -*-2"""3 flask.jsonimpl4 ~~~~~~~~~~~~~~3 flask.json4 ~~~~~~~~~~56 Implementation helpers for the JSON support in Flask.78 :copyright: (c) 2015 by Armin Ronacher.
81 unmodified lines
9091def _dump_arg_defaults(kwargs):92 """Inject default arguments for dump functions."""93 if current_app:94 kwargs.setdefault('cls', current_app.json_encoder)94 bp = current_app.blueprints.get(request.blueprint) if request else None95 kwargs.setdefault(96 'cls',97 bp.json_encoder if bp and bp.json_encoder98 else current_app.json_encoder99 )100101 if not current_app.config['JSON_AS_ASCII']:102 kwargs.setdefault('ensure_ascii', False)103104 kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS'])105 else:106 kwargs.setdefault('sort_keys', True)107 kwargs.setdefault('cls', JSONEncoder)
1 unmodified line
109110def _load_arg_defaults(kwargs):111 """Inject default arguments for load functions."""112 if current_app:106 kwargs.setdefault('cls', current_app.json_decoder)113 bp = current_app.blueprints.get(request.blueprint) if request else None114 kwargs.setdefault(115 'cls',116 bp.json_decoder if bp and bp.json_decoder117 else current_app.json_decoder118 )119 else:120 kwargs.setdefault('cls', JSONDecoder)121122
124 unmodified lines
247 .. versionchanged:: 0.11248 Added support for serializing top-level arrays. This introduces a249 security risk in ancient browsers. See :ref:`json-security` for details.250239 This function's response will be pretty printed if it was not requested240 with ``X-Requested-With: XMLHttpRequest`` to simplify debugging unless241 the ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to false.242 Compressed (not pretty) formatting currently means no indents and no243 spaces after separators.251 This function's response will be pretty printed if the252 ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to True or the253 Flask app is running in debug mode. Compressed (not pretty) formatting254 currently means no indents and no spaces after separators.255256 .. versionadded:: 0.2257 """258259 indent = None260 separators = (',', ':')261251 if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and not request.is_xhr:262 if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug:263 indent = 2264 separators = (', ', ': ')265266 if args and kwargs:
14 unmodified lines
modified:flask/sessions.py+69 added-32 removed
9 unmodified lines
10"""1112import uuid13import hashlib14import warnings15from base64 import b64encode, b64decode16from datetime import datetime17from werkzeug.http import http_date, parse_date18from werkzeug.datastructures import CallbackDict19from . import Markup, json20from ._compat import iteritems, text_type20from .helpers import total_seconds21from .helpers import total_seconds, is_ip2223from itsdangerous import URLSafeTimedSerializer, BadSignature2425
58 unmodified lines
8485 def dumps(self, value):86 return json.dumps(_tag(value), separators=(',', ':'))8788 LOADS_MAP = {89 ' t': tuple,90 ' u': uuid.UUID,91 ' b': b64decode,92 ' m': Markup,93 ' d': parse_date,94 }9596 def loads(self, value):97 def object_hook(obj):98 if len(obj) != 1:99 return obj100 the_key, the_value = next(iteritems(obj))92 if the_key == ' t':93 return tuple(the_value)94 elif the_key == ' u':95 return uuid.UUID(the_value)96 elif the_key == ' b':97 return b64decode(the_value)98 elif the_key == ' m':99 return Markup(the_value)100 elif the_key == ' d':101 return parse_date(the_value)101 # Check the key for a corresponding function102 return_function = self.LOADS_MAP.get(the_key)103 if return_function:104 # Pass the value to the function105 return return_function(the_value)106 # Didn't find a function for this object107 return obj108 return json.loads(value, object_hook=object_hook)109110
61 unmodified lines
172 #: this type.173 null_session_class = NullSession174175 #: A flag that indicates if the session interface is pickle based.171 #: This can be used by flask extensions to make a decision in regards176 #: This can be used by Flask extensions to make a decision in regards177 #: to how to deal with the session object.178 #:179 #: .. versionadded:: 0.10180 pickle_based = False
19 unmodified lines
200 """201 return isinstance(obj, self.null_session_class)202203 def get_cookie_domain(self, app):199 """Helpful helper method that returns the cookie domain that should200 be used for the session cookie if session cookies are used.204 """Returns the domain that should be set for the session cookie.205 206 Uses ``SESSION_COOKIE_DOMAIN`` if it is configured, otherwise207 falls back to detecting the domain based on ``SERVER_NAME``.208 209 Once detected (or if not set at all), ``SESSION_COOKIE_DOMAIN`` is210 updated to avoid re-running the logic.211 """202 if app.config['SESSION_COOKIE_DOMAIN'] is not None:203 return app.config['SESSION_COOKIE_DOMAIN']204 if app.config['SERVER_NAME'] is not None:205 # chop off the port which is usually not supported by browsers206 rv = '.' + app.config['SERVER_NAME'].rsplit(':', 1)[0]212208 # Google chrome does not like cookies set to .localhost, so209 # we just go with no domain then. Flask documents anyways that210 # cross domain cookies need a fully qualified domain name211 if rv == '.localhost':212 rv = None213 rv = app.config['SESSION_COOKIE_DOMAIN']214214 # If we infer the cookie domain from the server name we need215 # to check if we are in a subpath. In that case we can't216 # set a cross domain cookie.217 if rv is not None:218 path = self.get_cookie_path(app)219 if path != '/':220 rv = rv.lstrip('.')215 # set explicitly, or cached from SERVER_NAME detection216 # if False, return None217 if rv is not None:218 return rv if rv else None219222 return rv220 rv = app.config['SERVER_NAME']221222 # server name not set, cache False to return none next time223 if not rv:224 app.config['SESSION_COOKIE_DOMAIN'] = False225 return None226227 # chop off the port which is usually not supported by browsers228 # remove any leading '.' since we'll add that later229 rv = rv.rsplit(':', 1)[0].lstrip('.')230231 if '.' not in rv:232 # Chrome doesn't allow names without a '.'233 # this should only come up with localhost234 # hack around this by not setting the name, and show a warning235 warnings.warn(236 '"{rv}" is not a valid cookie domain, it must contain a ".".'237 ' Add an entry to your hosts file, for example'238 ' "{rv}.localdomain", and use that instead.'.format(rv=rv)239 )240 app.config['SESSION_COOKIE_DOMAIN'] = False241 return None242243 ip = is_ip(rv)244245 if ip:246 warnings.warn(247 'The session cookie domain is an IP address. This may not work'248 ' as intended in some browsers. Add an entry to your hosts'249 ' file, for example "localhost.localdomain", and use that'250 ' instead.'251 )252253 # if this is not an ip and app is mounted at the root, allow subdomain254 # matching by adding a '.' prefix255 if self.get_cookie_path(app) == '/' and not ip:256 rv = '.' + rv257258 app.config['SESSION_COOKIE_DOMAIN'] = rv259 return rv260261 def get_cookie_path(self, app):262 """Returns the path for which the cookie should be valid. The263 default implementation uses the value from the ``SESSION_COOKIE_PATH``264 config var if it's set, and falls back to ``APPLICATION_ROOT`` or
135 unmodified lines
modified:flask/signals.py+1 added-1 removed
35 unmodified lines
36 connect = disconnect = has_receivers_for = receivers_for = \37 temporarily_connected_to = connected_to = _fail38 del _fail3940# The namespace for code signals. If you are not flask code, do40# The namespace for code signals. If you are not Flask code, do41# not put signals in here. Create your own namespace instead.42_signals = Namespace()4344
12 unmodified lines
modified:flask/testing.py+14 added
8 unmodified lines
9 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213import werkzeug14from contextlib import contextmanager15from werkzeug.test import Client, EnvironBuilder16from flask import _request_ctx_stack17
25 unmodified lines
43 end of a ``with`` body when used in a ``with`` statement. For general44 information about how to use this class refer to45 :class:`werkzeug.test.Client`.4647 .. versionchanged:: 0.1248 `app.test_client()` includes preset default environment, which can be49 set after instantiation of the `app.test_client()` object in50 `client.environ_base`.5152 Basic usage is outlined in the :ref:`testing` chapter.53 """5455 preserve_context = False5657 def __init__(self, *args, **kwargs):58 super(FlaskClient, self).__init__(*args, **kwargs)59 self.environ_base = {60 "REMOTE_ADDR": "127.0.0.1",61 "HTTP_USER_AGENT": "werkzeug/" + werkzeug.__version__62 }6364 @contextmanager65 def session_transaction(self, *args, **kwargs):66 """When used in combination with a ``with`` statement this opens a67 session transaction. This can be used to modify the session that
45 unmodified lines
113114 def open(self, *args, **kwargs):115 kwargs.setdefault('environ_overrides', {}) \116 ['flask._preserve_context'] = self.preserve_context117 kwargs.setdefault('environ_base', self.environ_base)118119 as_tuple = kwargs.pop('as_tuple', False)120 buffered = kwargs.pop('buffered', False)121 follow_redirects = kwargs.pop('follow_redirects', False)
22 unmodified lines
modified:flask/views.py+22 added-18 removed
101 unmodified lines
102 return view103104105class MethodViewType(type):106 """Metaclass for :class:`MethodView` that determines what methods the view107 defines.108 """109107 def __new__(cls, name, bases, d):108 rv = type.__new__(cls, name, bases, d)110 def __init__(cls, name, bases, d):111 super(MethodViewType, cls).__init__(name, bases, d)112113 if 'methods' not in d:110 methods = set(rv.methods or [])111 for key in d:112 if key in http_method_funcs:114 methods = set()115116 for key in http_method_funcs:117 if hasattr(cls, key):118 methods.add(key.upper())114 # If we have no method at all in there we don't want to115 # add a method list. (This is for instance the case for116 # the base class or another subclass of a base method view117 # that does not introduce new methods).119120 # If we have no method at all in there we don't want to add a121 # method list. This is for instance the case for the base class122 # or another subclass of a base method view that does not introduce123 # new methods.124 if methods:119 rv.methods = sorted(methods)120 return rv125 cls.methods = methods126127128class MethodView(with_metaclass(MethodViewType, View)):124 """Like a regular class-based view but that dispatches requests to125 particular methods. For instance if you implement a method called126 :meth:`get` it means it will respond to ``'GET'`` requests and127 the :meth:`dispatch_request` implementation will automatically128 forward your request to that. Also :attr:`options` is set for you129 automatically::129 """A class-based view that dispatches request methods to the corresponding130 class methods. For example, if you implement a ``get`` method, it will be131 used to handle ``GET`` requests. ::132133 class CounterAPI(MethodView):132134 def get(self):135 return session.get('counter', 0)136137 def post(self):
1 unmodified line
139 return 'OK'140141 app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))142 """143144 def dispatch_request(self, *args, **kwargs):145 meth = getattr(self, request.method.lower(), None)146147 # If the request method is HEAD and we don't have a handler for it148 # retry with GET.149 if meth is None and request.method == 'HEAD':150 meth = getattr(self, 'get', None)151152 assert meth is not None, 'Unimplemented method %r' % request.method153 return meth(*args, **kwargs)
modified:flask/wrappers.py+2 added-1 removed
135 unmodified lines
136 :param cache: if set to ``True`` the parsed JSON data is remembered137 on the request.138 """139 rv = getattr(self, '_cached_json', _missing)140 # We return cached JSON only when the cache is enabled.140 if rv is not _missing:141 if cache and rv is not _missing:142 return rv143144 if not (force or self.is_json):145 return None
60 unmodified lines
modified:scripts/flask-07-upgrade.py+1 added-1 removed
3 unmodified lines
4 flask-07-upgrade5 ~~~~~~~~~~~~~~~~67 This command line script scans a whole application tree and attempts to8 output an unified diff with all the changes that are necessary to easily8 output a unified diff with all the changes that are necessary to easily9 upgrade the application to 0.7 and to not yield deprecation warnings.1011 This will also attempt to find `after_request` functions that don't modify12 the response and appear to be better suited for `teardown_request`.
286 unmodified lines
added:tests/test_apps/cliapp/importerrorapp.py+7 added
1from __future__ import absolute_import, print_function23from flask import Flask45raise ImportError()67testapp = Flask('testapp')
modified:tests/test_basic.py+251 added-48 removed
48 unmodified lines
49 rv = app.test_client().open('/', method='OPTIONS')50 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']515253def test_options_handling_disabled():53def test_provide_automatic_options_attr():54 app = flask.Flask(__name__)5556 def index():57 return 'Hello World!'
11 unmodified lines
69 rv = app.test_client().open('/', method='OPTIONS')70 assert sorted(rv.allow) == ['OPTIONS']717273def test_provide_automatic_options_kwarg():74 app = flask.Flask(__name__)7576 def index():77 return flask.request.method7879 def more():80 return flask.request.method8182 app.add_url_rule('/', view_func=index, provide_automatic_options=False)83 app.add_url_rule(84 '/more', view_func=more, methods=['GET', 'POST'],85 provide_automatic_options=False86 )8788 c = app.test_client()89 assert c.get('/').data == b'GET'9091 rv = c.post('/')92 assert rv.status_code == 40593 assert sorted(rv.allow) == ['GET', 'HEAD']9495 # Older versions of Werkzeug.test.Client don't have an options method96 if hasattr(c, 'options'):97 rv = c.options('/')98 else:99 rv = c.open('/', method='OPTIONS')100101 assert rv.status_code == 405102103 rv = c.head('/')104 assert rv.status_code == 200105 assert not rv.data # head truncates106 assert c.post('/more').data == b'POST'107 assert c.get('/more').data == b'GET'108109 rv = c.delete('/more')110 assert rv.status_code == 405111 assert sorted(rv.allow) == ['GET', 'HEAD', 'POST']112113 if hasattr(c, 'options'):114 rv = c.options('/more')115 else:116 rv = c.open('/more', method='OPTIONS')117118 assert rv.status_code == 405119120121def test_request_dispatching():122 app = flask.Flask(__name__)123124 @app.route('/')
225 unmodified lines
350 assert 'secure' in cookie351 assert 'httponly' not in cookie352353354def test_session_localhost_warning(recwarn):355 app = flask.Flask(__name__)356 app.config.update(357 SECRET_KEY='testing',358 SERVER_NAME='localhost:5000',359 )360361 @app.route('/')362 def index():363 flask.session['testing'] = 42364 return 'testing'365366 rv = app.test_client().get('/', 'http://localhost:5000/')367 assert 'domain' not in rv.headers['set-cookie'].lower()368 w = recwarn.pop(UserWarning)369 assert '"localhost" is not a valid cookie domain' in str(w.message)370371372def test_session_ip_warning(recwarn):373 app = flask.Flask(__name__)374 app.config.update(375 SECRET_KEY='testing',376 SERVER_NAME='127.0.0.1:5000',377 )378379 @app.route('/')380 def index():381 flask.session['testing'] = 42382 return 'testing'383384 rv = app.test_client().get('/', 'http://127.0.0.1:5000/')385 assert 'domain=127.0.0.1' in rv.headers['set-cookie'].lower()386 w = recwarn.pop(UserWarning)387 assert 'cookie domain is an IP' in str(w.message)388389390def test_missing_session():391 app = flask.Flask(__name__)392393 def expect_exception(f, *args, **kwargs):
22 unmodified lines
416417 client = app.test_client()418 rv = client.get('/')419 assert 'set-cookie' in rv.headers336 match = re.search(r'\bexpires=([^;]+)(?i)', rv.headers['set-cookie'])420 match = re.search(r'(?i)\bexpires=([^;]+)', rv.headers['set-cookie'])421 expires = parse_date(match.group())422 expected = datetime.utcnow() + app.permanent_session_lifetime423 assert expires.year == expected.year424 assert expires.month == expected.month
449 unmodified lines
874 assert resp.mimetype == 'text/x-special'875 assert resp.data == b'internal server error'876877878def test_baseexception_error_handling():879 app = flask.Flask(__name__)880 app.config['LOGGER_HANDLER_POLICY'] = 'never'881882 @app.route('/')883 def broken_func():884 raise KeyboardInterrupt()885886 with app.test_client() as c:887 with pytest.raises(KeyboardInterrupt):888 c.get('/')889890 ctx = flask._request_ctx_stack.top891 assert ctx.preserved892 assert type(ctx._preserved_exc) is KeyboardInterrupt893894895def test_before_request_and_routing_errors():896 app = flask.Flask(__name__)897898 @app.before_request
111 unmodified lines
1010 assert 'no file contents were transmitted' in str(e.value)1011 assert 'This was submitted: "index.txt"' in str(e.value)10121013913def test_response_creation():1014def test_response_types():1015 app = flask.Flask(__name__)1016 app.testing = True1017916 @app.route('/unicode')917 def from_unicode():1018 @app.route('/text')1019 def from_text():1020 return u'Hällo Wörld'1021920 @app.route('/string')921 def from_string():1022 @app.route('/bytes')1023 def from_bytes():1024 return u'Hällo Wörld'.encode('utf-8')1025924 @app.route('/args')925 def from_tuple():1026 @app.route('/full_tuple')1027 def from_full_tuple():1028 return 'Meh', 400, {1029 'X-Foo': 'Testing',1030 'Content-Type': 'text/plain; charset=utf-8'1031 }1032931 @app.route('/two_args')932 def from_two_args_tuple():1033 @app.route('/text_headers')1034 def from_text_headers():1035 return 'Hello', {1036 'X-Foo': 'Test',1037 'Content-Type': 'text/plain; charset=utf-8'1038 }1039938 @app.route('/args_status')939 def from_status_tuple():1040 @app.route('/text_status')1041 def from_text_status():1042 return 'Hi, status!', 4001043942 @app.route('/args_header')943 def from_response_instance_status_tuple():944 return flask.Response('Hello world', 404), {1044 @app.route('/response_headers')1045 def from_response_headers():1046 return flask.Response('Hello world', 404, {'X-Foo': 'Baz'}), {1047 "X-Foo": "Bar",1048 "X-Bar": "Foo"1049 }10501051 @app.route('/response_status')1052 def from_response_status():1053 return app.response_class('Hello world', 400), 50010541055 @app.route('/wsgi')1056 def from_wsgi():1057 return NotFound()10581059 c = app.test_client()950 assert c.get('/unicode').data == u'Hällo Wörld'.encode('utf-8')951 assert c.get('/string').data == u'Hällo Wörld'.encode('utf-8')952 rv = c.get('/args')10601061 assert c.get('/text').data == u'Hällo Wörld'.encode('utf-8')1062 assert c.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')10631064 rv = c.get('/full_tuple')1065 assert rv.data == b'Meh'1066 assert rv.headers['X-Foo'] == 'Testing'1067 assert rv.status_code == 4001068 assert rv.mimetype == 'text/plain'957 rv2 = c.get('/two_args')958 assert rv2.data == b'Hello'959 assert rv2.headers['X-Foo'] == 'Test'960 assert rv2.status_code == 200961 assert rv2.mimetype == 'text/plain'962 rv3 = c.get('/args_status')963 assert rv3.data == b'Hi, status!'964 assert rv3.status_code == 400965 assert rv3.mimetype == 'text/html'966 rv4 = c.get('/args_header')967 assert rv4.data == b'Hello world'968 assert rv4.headers['X-Foo'] == 'Bar'969 assert rv4.headers['X-Bar'] == 'Foo'970 assert rv4.status_code == 40410691070 rv = c.get('/text_headers')1071 assert rv.data == b'Hello'1072 assert rv.headers['X-Foo'] == 'Test'1073 assert rv.status_code == 2001074 assert rv.mimetype == 'text/plain'10751076 rv = c.get('/text_status')1077 assert rv.data == b'Hi, status!'1078 assert rv.status_code == 4001079 assert rv.mimetype == 'text/html'10801081 rv = c.get('/response_headers')1082 assert rv.data == b'Hello world'1083 assert rv.headers.getlist('X-Foo') == ['Baz', 'Bar']1084 assert rv.headers['X-Bar'] == 'Foo'1085 assert rv.status_code == 40410861087 rv = c.get('/response_status')1088 assert rv.data == b'Hello world'1089 assert rv.status_code == 50010901091 rv = c.get('/wsgi')1092 assert b'Not Found' in rv.data1093 assert rv.status_code == 404109410951096def test_response_type_errors():1097 app = flask.Flask(__name__)1098 app.testing = True10991100 @app.route('/none')1101 def from_none():1102 pass11031104 @app.route('/small_tuple')1105 def from_small_tuple():1106 return 'Hello',11071108 @app.route('/large_tuple')1109 def from_large_tuple():1110 return 'Hello', 234, {'X-Foo': 'Bar'}, '???'11111112 @app.route('/bad_type')1113 def from_bad_type():1114 return True11151116 @app.route('/bad_wsgi')1117 def from_bad_wsgi():1118 return lambda: None11191120 c = app.test_client()11211122 with pytest.raises(TypeError) as e:1123 c.get('/none')1124 assert 'returned None' in str(e)11251126 with pytest.raises(TypeError) as e:1127 c.get('/small_tuple')1128 assert 'tuple must have the form' in str(e)11291130 pytest.raises(TypeError, c.get, '/large_tuple')11311132 with pytest.raises(TypeError) as e:1133 c.get('/bad_type')1134 assert 'it was a bool' in str(e)11351136 pytest.raises(TypeError, c.get, '/bad_wsgi')113711381139def test_make_response():1140 app = flask.Flask(__name__)1141 with app.test_request_context():1142 rv = flask.make_response()
17 unmodified lines
1160 with app.test_request_context():1161 rv = flask.make_response(1162 flask.jsonify({'msg': 'W00t'}), 400)1163 assert rv.status_code == 400998 assert rv.data == b'{\n "msg": "W00t"\n}\n'1164 assert rv.data == b'{"msg":"W00t"}\n'1165 assert rv.mimetype == 'application/json'11661167 rv = flask.make_response(1168 flask.Response(''), 400)
110 unmodified lines
1279 with app.test_request_context():1280 pytest.raises(BuildError, flask.url_for, 'not.existing')128112821283def test_url_for_passes_special_values_to_build_error_handler():1284 app = flask.Flask(__name__)12851286 @app.url_build_error_handlers.append1287 def handler(error, endpoint, values):1288 assert values == {1289 '_external': False,1290 '_anchor': None,1291 '_method': None,1292 '_scheme': None,1293 }1294 return 'handled'12951296 with app.test_request_context():1297 flask.url_for('/')129812991300def test_custom_converters():1301 from werkzeug.routing import BaseConverter13021303 class ListConverter(BaseConverter):
49 unmodified lines
1353 with app.test_request_context():1354 assert flask.url_for('static', filename='index.html') == '/foo/index.html'135513561174def test_none_response():1175 app = flask.Flask(__name__)1176 app.testing = True1357def test_static_route_with_host_matching():1358 app = flask.Flask(__name__, host_matching=True, static_host='example.com')1359 c = app.test_client()1360 rv = c.get('http://example.com/static/index.html')1361 assert rv.status_code == 2001362 rv.close()1363 with app.test_request_context():1364 rv = flask.url_for('static', filename='index.html', _external=True)1365 assert rv == 'http://example.com/static/index.html'1366 # Providing static_host without host_matching=True should error.1367 with pytest.raises(Exception):1368 flask.Flask(__name__, static_host='example.com')1369 # Providing host_matching=True with static_folder but without static_host should error.1370 with pytest.raises(Exception):1371 flask.Flask(__name__, host_matching=True)1372 # Providing host_matching=True without static_host but with static_folder=None should not error.1373 flask.Flask(__name__, host_matching=True, static_folder=None)13741178 @app.route('/')1179 def test():1180 return None1181 try:1182 app.test_client().get('/')1183 except ValueError as e:1184 assert str(e) == 'View function did not return a response'1185 pass1186 else:1187 assert "Expected ValueError"137511891376def test_request_locals():1377 assert repr(flask.g) == '<LocalProxy unbound>'1378 assert not flask.g1379
486 unmodified lines
1866 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1867 hostname, port = 'localhost', 80001868 app.run(hostname, port, debug=True)1869 assert rv['result'] == 'running on %s:%s ...' % (hostname, port)187018711872@pytest.mark.parametrize('host,port,expect_host,expect_port', (1873 (None, None, 'pocoo.org', 8080),1874 ('localhost', None, 'localhost', 8080),1875 (None, 80, 'pocoo.org', 80),1876 ('localhost', 80, 'localhost', 80),1877))1878def test_run_from_config(monkeypatch, host, port, expect_host, expect_port):1879 def run_simple_mock(hostname, port, *args, **kwargs):1880 assert hostname == expect_host1881 assert port == expect_port18821883 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1884 app = flask.Flask(__name__)1885 app.config['SERVER_NAME'] = 'pocoo.org:8080'1886 app.run(host, port)
modified:tests/test_blueprints.py+19 added
353 unmodified lines
354 assert rv.status_code == 404355 rv = c.get('/py/bar/123')356 assert rv.status_code == 404357358359def test_endpoint_decorator():360 from werkzeug.routing import Rule361 app = flask.Flask(__name__)362 app.url_map.add(Rule('/foo', endpoint='bar'))363364 bp = flask.Blueprint('bp', __name__)365366 @bp.endpoint('bar')367 def foobar():368 return flask.request.endpoint369370 app.register_blueprint(bp, url_prefix='/bp_prefix')371372 c = app.test_client()373 assert c.get('/foo').data == b'bar'374 assert c.get('/bp_prefix/bar').status_code == 404375376377def test_template_filter():378 bp = flask.Blueprint('bp', __name__)379 @bp.app_template_filter()380 def my_reverse(s):
213 unmodified lines
modified:tests/test_cli.py+85 added-7 removed
12 unmodified lines
13#14from __future__ import absolute_import, print_function15import os16import sys17from functools import partial1819import click20import pytest21from click.testing import CliRunner22from flask import Flask, current_app2323from flask.cli import AppGroup, FlaskGroup, NoAppException, ScriptInfo, \24from flask.cli import cli, AppGroup, FlaskGroup, NoAppException, ScriptInfo, \25 find_best_app, locate_app, with_appcontext, prepare_exec_for_file, \26 find_default_import_path, get_version272829@pytest.fixture30def runner():31 return CliRunner()323334def test_cli_name(test_apps):35 """Make sure the CLI object's name is the app's name and not the app itself"""36 from cliapp.app import testapp37 assert testapp.cli.name == testapp.name
50 unmodified lines
88 assert locate_app("cliapp.multiapp:app1").name == "app1"89 pytest.raises(NoAppException, locate_app, "notanpp.py")90 pytest.raises(NoAppException, locate_app, "cliapp/app")91 pytest.raises(RuntimeError, locate_app, "cliapp.app:notanapp")92 pytest.raises(NoAppException, locate_app, "cliapp.importerrorapp")939495def test_find_default_import_path(test_apps, monkeypatch, tmpdir):96 """Test of find_default_import_path."""
37 unmodified lines
134 assert app.name == "createapp"135 assert obj.load_app() == app136137131def test_with_appcontext():138def test_with_appcontext(runner):139 """Test of with_appcontext."""140 @click.command()141 @with_appcontext142 def testcmd():143 click.echo(current_app.name)144145 obj = ScriptInfo(create_app=lambda info: Flask("testapp"))146140 runner = CliRunner()147 result = runner.invoke(testcmd, obj=obj)148 assert result.exit_code == 0149 assert result.output == 'testapp\n'150151146def test_appgroup():152def test_appgroup(runner):153 """Test of with_appcontext."""154 @click.group(cls=AppGroup)155 def cli():156 pass
11 unmodified lines
168 click.echo(current_app.name)169170 obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))171166 runner = CliRunner()172 result = runner.invoke(cli, ['test'], obj=obj)173 assert result.exit_code == 0174 assert result.output == 'testappgroup\n'175
1 unmodified line
177 assert result.exit_code == 0178 assert result.output == 'testappgroup\n'179180176def test_flaskgroup():181def test_flaskgroup(runner):182 """Test FlaskGroup."""183 def create_app(info):184 return Flask("flaskgroup")185
4 unmodified lines
190 @cli.command()191 def test():192 click.echo(current_app.name)193189 runner = CliRunner()194 result = runner.invoke(cli, ['test'])195 assert result.exit_code == 0196 assert result.output == 'flaskgroup\n'197198199def test_print_exceptions(runner):200 """Print the stacktrace if the CLI."""201 def create_app(info):202 raise Exception("oh no")203 return Flask("flaskgroup")204205 @click.group(cls=FlaskGroup, create_app=create_app)206 def cli(**params):207 pass208209 result = runner.invoke(cli, ['--help'])210 assert result.exit_code == 0211 assert 'Exception: oh no' in result.output212 assert 'Traceback' in result.output213214215class TestRoutes:216 @pytest.fixture217 def invoke(self, runner):218 def create_app(info):219 app = Flask(__name__)220 app.testing = True221222 @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])223 def yyy_get_post(x, y):224 pass225226 @app.route('/zzz_post', methods=['POST'])227 def aaa_post():228 pass229230 return app231232 cli = FlaskGroup(create_app=create_app)233 return partial(runner.invoke, cli)234235 def expect_order(self, order, output):236 # skip the header and match the start of each row237 for expect, line in zip(order, output.splitlines()[2:]):238 # do this instead of startswith for nicer pytest output239 assert line[:len(expect)] == expect240241 def test_simple(self, invoke):242 result = invoke(['routes'])243 assert result.exit_code == 0244 self.expect_order(245 ['aaa_post', 'static', 'yyy_get_post'],246 result.output247 )248249 def test_sort(self, invoke):250 default_output = invoke(['routes']).output251 endpoint_output = invoke(['routes', '-s', 'endpoint']).output252 assert default_output == endpoint_output253 self.expect_order(254 ['static', 'yyy_get_post', 'aaa_post'],255 invoke(['routes', '-s', 'methods']).output256 )257 self.expect_order(258 ['yyy_get_post', 'static', 'aaa_post'],259 invoke(['routes', '-s', 'rule']).output260 )261 self.expect_order(262 ['aaa_post', 'yyy_get_post', 'static'],263 invoke(['routes', '-s', 'match']).output264 )265266 def test_all_methods(self, invoke):267 output = invoke(['routes']).output268 assert 'GET, HEAD, OPTIONS, POST' not in output269 output = invoke(['routes', '--all-methods']).output270 assert 'GET, HEAD, OPTIONS, POST' in output
modified:tests/test_config.py+20 added-2 removed
5 unmodified lines
6 :copyright: (c) 2015 by the Flask Team, see AUTHORS for more details.7 :license: BSD, see LICENSE for more details.8"""910import pytest1012import os11from datetime import timedelta12import os13import textwrap1415import flask16from flask._compat import PY217import pytest181920# config keys used for the TestConfig21TEST_KEY = 'foo'
167 unmodified lines
189 bar_options = app.config.get_namespace('BAR_', lowercase=False, trim_namespace=False)190 assert 2 == len(bar_options)191 assert 'bar stuff 1' == bar_options['BAR_STUFF_1']192 assert 'bar stuff 2' == bar_options['BAR_STUFF_2']193194195@pytest.mark.parametrize('encoding', ['utf-8', 'iso-8859-15', 'latin-1'])196def test_from_pyfile_weird_encoding(tmpdir, encoding):197 f = tmpdir.join('my_config.py')198 f.write_binary(textwrap.dedent(u'''199 # -*- coding: {0} -*-200 TEST_VALUE = "föö"201 '''.format(encoding)).encode(encoding))202 app = flask.Flask(__name__)203 app.config.from_pyfile(str(f))204 value = app.config['TEST_VALUE']205 if PY2:206 value = value.decode(encoding)207 assert value == u'föö'
modified:tests/test_ext.py+2 added-2 removed
177 unmodified lines
178179def test_no_error_swallowing(flaskext_broken):180 with pytest.raises(ImportError) as excinfo:181 import flask.ext.broken182183 assert excinfo.type is ImportError182 # python3.6 raises a subclass of ImportError: 'ModuleNotFoundError'183 assert issubclass(excinfo.type, ImportError)184 if PY2:185 message = 'No module named missing_module'186 else:187 message = 'No module named \'missing_module\''
12 unmodified lines
modified:tests/test_helpers.py+76 added-17 removed
33 unmodified lines
343536class TestJSON(object):3738 def test_ignore_cached_json(self):39 app = flask.Flask(__name__)40 with app.test_request_context('/', method='POST', data='malformed',41 content_type='application/json'):42 assert flask.request.get_json(silent=True, cache=True) is None43 with pytest.raises(BadRequest):44 flask.request.get_json(silent=False, cache=False)4546 def test_post_empty_json_adds_exception_to_response_content_in_debug(self):47 app = flask.Flask(__name__)48 app.config['DEBUG'] = True49 @app.route('/json', methods=['POST'])
70 unmodified lines
120 out.seek(0)121 rv = flask.json.load(out)122 assert rv == test_data123124 @pytest.mark.parametrize('test_value', [0, -1, 1, 23, 3.14, 's', "longer string", True, False, None])116 def test_jsonify_basic_types(self):125 def test_jsonify_basic_types(self, test_value):126 """Test jsonify with basic types."""118 # Should be able to use pytest parametrize on this, but I couldn't119 # figure out the correct syntax120 # https://pytest.org/latest/parametrize.html#pytest-mark-parametrize-parametrizing-test-functions121 test_data = (0, 1, 23, 3.14, 's', "longer string", True, False,)127 app = flask.Flask(__name__)128 c = app.test_client()124 for i, d in enumerate(test_data):125 url = '/jsonify_basic_types{0}'.format(i)126 app.add_url_rule(url, str(i), lambda x=d: flask.jsonify(x))127 rv = c.get(url)128 assert rv.mimetype == 'application/json'129 assert flask.json.loads(rv.data) == d129130 url = '/jsonify_basic_types'131 app.add_url_rule(url, url, lambda x=test_value: flask.jsonify(x))132 rv = c.get(url)133 assert rv.mimetype == 'application/json'134 assert flask.json.loads(rv.data) == test_value135136 def test_jsonify_dicts(self):137 """Test jsonify with dicts and kwargs unpacking."""138 d = dict(139 a=0, b=23, c=3.14, d='t', e='Hi', f=True, g=False,
34 unmodified lines
174 assert flask.json.loads(rv.data) == l175176 def test_jsonify_date_types(self):177 """Test jsonify with datetime.date and datetime.datetime types."""173178 test_dates = (179 datetime.datetime(1973, 3, 11, 6, 30, 45),180 datetime.date(1975, 1, 5)181 )178182 app = flask.Flask(__name__)183 c = app.test_client()184185 for i, d in enumerate(test_dates):
5 unmodified lines
191192 def test_jsonify_uuid_types(self):193 """Test jsonify with uuid.UUID types"""194192 test_uuid = uuid.UUID(bytes=b'\xDE\xAD\xBE\xEF'*4)193195 test_uuid = uuid.UUID(bytes=b'\xDE\xAD\xBE\xEF' * 4)196 app = flask.Flask(__name__)197 url = '/uuid_test'198 app.add_url_rule(url, url, lambda: flask.jsonify(x=test_uuid))199
66 unmodified lines
266 'x': {'_foo': 42}267 }), content_type='application/json')268 assert rv.data == b'"<42>"'269270 def test_blueprint_json_customization(self):271 class X(object):272 def __init__(self, val):273 self.val = val274275 class MyEncoder(flask.json.JSONEncoder):276 def default(self, o):277 if isinstance(o, X):278 return '<%d>' % o.val279280 return flask.json.JSONEncoder.default(self, o)281282 class MyDecoder(flask.json.JSONDecoder):283 def __init__(self, *args, **kwargs):284 kwargs.setdefault('object_hook', self.object_hook)285 flask.json.JSONDecoder.__init__(self, *args, **kwargs)286287 def object_hook(self, obj):288 if len(obj) == 1 and '_foo' in obj:289 return X(obj['_foo'])290291 return obj292293 bp = flask.Blueprint('bp', __name__)294 bp.json_encoder = MyEncoder295 bp.json_decoder = MyDecoder296297 @bp.route('/bp', methods=['POST'])298 def index():299 return flask.json.dumps(flask.request.get_json()['x'])300301 app = flask.Flask(__name__)302 app.testing = True303 app.register_blueprint(bp)304305 c = app.test_client()306 rv = c.post('/bp', data=flask.json.dumps({307 'x': {'_foo': 42}308 }), content_type='application/json')309 assert rv.data == b'"<42>"'310311 def test_modified_url_encoding(self):312 class ModifiedRequest(flask.Request):313 url_charset = 'euc-kr'314 app = flask.Flask(__name__)
14 unmodified lines
329330 def test_json_key_sorting(self):331 app = flask.Flask(__name__)332 app.testing = True333 app.debug = True334335 assert app.config['JSON_SORT_KEYS'] == True336 d = dict.fromkeys(range(20), 'foo')337338 @app.route('/')
218 unmodified lines
557 rv = c.get('/', headers={'Range': 'somethingsomething'})558 assert rv.status_code == 416559 rv.close()560516 last_modified = datetime.datetime.fromtimestamp(os.path.getmtime(561 last_modified = datetime.datetime.utcfromtimestamp(os.path.getmtime(562 os.path.join(app.root_path, 'static/index.html'))).replace(563 microsecond=0)564565 rv = c.get('/', headers={'Range': 'bytes=4-15',
14 unmodified lines
580 attachment_filename='index.html')581 value, options = \582 parse_options_header(rv.headers['Content-Disposition'])583 assert value == 'attachment'584 assert options['filename'] == 'index.html'585 assert 'filename*' not in rv.headers['Content-Disposition']586 rv.close()587588 with app.test_request_context():542 assert options['filename'] == 'index.html'589 rv = flask.send_file('static/index.html', as_attachment=True)590 value, options = parse_options_header(rv.headers['Content-Disposition'])591 assert value == 'attachment'592 assert options['filename'] == 'index.html'
8 unmodified lines
601 assert value == 'attachment'602 assert options['filename'] == 'index.txt'603 rv.close()604605 def test_attachment_with_utf8_filename(self):606 app = flask.Flask(__name__)607608 with app.test_request_context():609 rv = flask.send_file('static/index.html', as_attachment=True, attachment_filename=u'Ñandú/pingüino.txt')610 content_disposition = set(rv.headers['Content-Disposition'].split('; '))611 assert content_disposition == set((612 'attachment',613 'filename="Nandu/pinguino.txt"',614 "filename*=UTF-8''%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt"615 ))616 rv.close()617618 def test_static_file(self):619 app = flask.Flask(__name__)620 # default cache timeout is 12 hours621 with app.test_request_context():
323 unmodified lines
modified:tests/test_reqctx.py+25 added
10 unmodified lines
1112import pytest1314import flask15from flask.sessions import SessionInterface1617try:18 from greenlet import greenlet19except ImportError:
173 unmodified lines
193 assert rv.data == b'Hello World!'194195 result = greenlets[0].run()196 assert result == 42197198199def test_session_error_pops_context():200 class SessionError(Exception):201 pass202203 class FailingSessionInterface(SessionInterface):204 def open_session(self, app, request):205 raise SessionError()206207 class CustomFlask(flask.Flask):208 session_interface = FailingSessionInterface()209210 app = CustomFlask(__name__)211212 @app.route('/')213 def index():214 # shouldn't get here215 assert False216217 response = app.test_client().get('/')218 assert response.status_code == 500219 assert not flask.request220 assert not flask.current_app
modified:tests/test_testing.py+35 added
9 unmodified lines
10"""11import pytest1213import flask14import werkzeug1516from flask._compat import text_type1718
24 unmodified lines
43 with app.test_client() as c:44 rv = c.get('/')45 assert rv.data == b'http://localhost/'4647def test_environ_base_default():48 app = flask.Flask(__name__)49 app.testing = True50 @app.route('/')51 def index():52 flask.g.user_agent = flask.request.headers["User-Agent"]53 return flask.request.remote_addr5455 with app.test_client() as c:56 rv = c.get('/')57 assert rv.data == b'127.0.0.1'58 assert flask.g.user_agent == 'werkzeug/' + werkzeug.__version__5960def test_environ_base_modified():61 app = flask.Flask(__name__)62 app.testing = True63 @app.route('/')64 def index():65 flask.g.user_agent = flask.request.headers["User-Agent"]66 return flask.request.remote_addr6768 with app.test_client() as c:69 c.environ_base['REMOTE_ADDR'] = '0.0.0.0'70 c.environ_base['HTTP_USER_AGENT'] = 'Foo'71 rv = c.get('/')72 assert rv.data == b'0.0.0.0'73 assert flask.g.user_agent == 'Foo'7475 c.environ_base['REMOTE_ADDR'] = '0.0.0.1'76 c.environ_base['HTTP_USER_AGENT'] = 'Bar'77 rv = c.get('/')78 assert rv.data == b'0.0.0.1'79 assert flask.g.user_agent == 'Bar'8081def test_redirect_keep_session():82 app = flask.Flask(__name__)83 app.secret_key = 'testing'84
187 unmodified lines
modified:tests/test_views.py+42 added
158 unmodified lines
159 app.add_url_rule('/', view_func=Index.as_view('index'))160161 # But these tests should still pass. We just log a warning.162 common_test(app)163164def test_multiple_inheritance():165 app = flask.Flask(__name__)166167 class GetView(flask.views.MethodView):168 def get(self):169 return 'GET'170171 class DeleteView(flask.views.MethodView):172 def delete(self):173 return 'DELETE'174175 class GetDeleteView(GetView, DeleteView):176 pass177178 app.add_url_rule('/', view_func=GetDeleteView.as_view('index'))179180 c = app.test_client()181 assert c.get('/').data == b'GET'182 assert c.delete('/').data == b'DELETE'183 assert sorted(GetDeleteView.methods) == ['DELETE', 'GET']184185def test_remove_method_from_parent():186 app = flask.Flask(__name__)187188 class GetView(flask.views.MethodView):189 def get(self):190 return 'GET'191192 class OtherView(flask.views.MethodView):193 def post(self):194 return 'POST'195196 class View(GetView, OtherView):197 methods = ['GET']198199 app.add_url_rule('/', view_func=View.as_view('index'))200201 c = app.test_client()202 assert c.get('/').data == b'GET'203 assert c.post('/').status_code == 405204 assert sorted(View.methods) == ['GET']
modified:.gitignore+6 added
9 unmodified lines
10_mailinglist11.tox12.cache/13.idea/1415# Coverage reports16htmlcov17.coverage18.coverage.*19*,cover
modified:.travis.yml+5 added-1 removed
6 unmodified lines
7 - "pypy"8 - "3.3"9 - "3.4"10 - "3.5"11 - "3.6"1213env:14 - REQUIREMENTS=lowest15 - REQUIREMENTS=lowest-simplejson
16 unmodified lines
32 - python: "3.5"33 env: REQUIREMENTS=lowest34 - python: "3.5"35 env: REQUIREMENTS=lowest-simplejson36 - python: "3.6"37 env: REQUIREMENTS=lowest38 - python: "3.6"39 env: REQUIREMENTS=lowest-simplejson403641install:42 - pip install tox4344script:
15 unmodified lines
modified:AUTHORS+1 added
19 unmodified lines
20- Edmond Burnett21- Florent Xicluna22- Georg Brandl23- Jeff Widman @jeffwidman24- Joshua Bronson @jab25- Justin Quick26- Kenneth Reitz27- Keyan Pishdadian28- Marian Sigler
10 unmodified lines
modified:CHANGES+67 added
1 unmodified line
2===============34Here you can see the full list of changes between each Flask release.56Version 0.137------------89Major release, unreleased1011- Make `app.run()` into a noop if a Flask application is run from the12 development server on the command line. This avoids some behavior that13 was confusing to debug for newcomers.14- Change default configuration `JSONIFY_PRETTYPRINT_REGULAR=False`. jsonify()15 method returns compressed response by default, and pretty response in16 debug mode.17- Change Flask.__init__ to accept two new keyword arguments, ``host_matching``18 and ``static_host``. This enables ``host_matching`` to be set properly by the19 time the constructor adds the static route, and enables the static route to20 be properly associated with the required host. (``#1559``)21- ``send_file`` supports Unicode in ``attachment_filename``. (`#2223`_)22- Pass ``_scheme`` argument from ``url_for`` to ``handle_build_error``.23 (`#2017`_)24- Add support for ``provide_automatic_options`` in ``add_url_rule`` to disable25 adding OPTIONS method when the ``view_func`` argument is not a class.26 (`#1489`_).27- ``MethodView`` can inherit method handlers from base classes. (`#1936`_)28- Errors caused while opening the session at the beginning of the request are29 handled by the app's error handlers. (`#2254`_)30- Blueprints gained ``json_encoder`` and ``json_decoder`` attributes to31 override the app's encoder and decoder. (`#1898`_)32- ``Flask.make_response`` raises ``TypeError`` instead of ``ValueError`` for33 bad response types. The error messages have been improved to describe why the34 type is invalid. (`#2256`_)35- Add ``routes`` CLI command to output routes registered on the application.36 (`#2259`_)37- Show warning when session cookie domain is a bare hostname or an IP38 address, as these may not behave properly in some browsers, such as Chrome.39 (`#2282`_)40- Allow IP address as exact session cookie domain. (`#2282`_)41- ``SESSION_COOKIE_DOMAIN`` is set if it is detected through ``SERVER_NAME``.42 (`#2282`_)4344.. _#1489: https://github.com/pallets/flask/pull/148945.. _#1898: https://github.com/pallets/flask/pull/189846.. _#1936: https://github.com/pallets/flask/pull/193647.. _#2017: https://github.com/pallets/flask/pull/201748.. _#2223: https://github.com/pallets/flask/pull/222349.. _#2254: https://github.com/pallets/flask/pull/225450.. _#2256: https://github.com/pallets/flask/pull/225651.. _#2259: https://github.com/pallets/flask/pull/225952.. _#2282: https://github.com/pallets/flask/pull/22825354Version 0.12.155--------------5657Bugfix release, released on March 31st 20175859- Prevent `flask run` from showing a NoAppException when an ImportError occurs60 within the imported application module.61- Fix encoding behavior of ``app.config.from_pyfile`` for Python 3. Fix62 ``#2118``.63- Use the ``SERVER_NAME`` config if it is present as default values for64 ``app.run``. ``#2109``, ``#2152``65- Call `ctx.auto_pop` with the exception object instead of `None`, in the66 event that a `BaseException` such as `KeyboardInterrupt` is raised in a67 request handler.6869Version 0.1270------------7172Released on December 21st 2016, codename Punsch.7374- the cli command now responds to `--version`.75- Mimetype guessing and ETag generation for file-like objects in ``send_file``76 has been removed, as per issue ``#104``. See pull request ``#1849``.77- Mimetype guessing in ``send_file`` now fails loudly and doesn't fall back to
5 unmodified lines
83- Correctly invoke response handlers for both regular request dispatching as84 well as error handlers.85- Disable logger propagation by default for the app logger.86- Add support for range requests in ``send_file``.87- ``app.test_client`` includes preset default environment, which can now be88 directly set, instead of per ``client.get``.8990Version 0.11.291--------------92
572 unmodified lines
modified:CONTRIBUTING.rst+31 added-6 removed
26 unmodified lines
27- Include tests if your patch is supposed to solve a bug, and explain28 clearly under which circumstances the bug happens. Make sure the test fails29 without your patch.3031- Try to follow `PEP8 <http://legacy.python.org/dev/peps/pep-0008/>`_, but you31- Try to follow `PEP8 <https://www.python.org/dev/peps/pep-0008/>`_, but you32 may ignore the line-length-limit if following it would make the code uglier.333435Running the testsuite
1 unmodified line
3738You probably want to set up a `virtualenv39<https://virtualenv.readthedocs.io/en/latest/index.html>`_.4041The minimal requirement for running the testsuite is ``py.test``. You can41The minimal requirement for running the testsuite is ``pytest``. You can42install it with::4344 pip install pytest45
7 unmodified lines
53 pip install --editable .5455Then you can run the testsuite with::5657 py.test57 pytest tests/5859With only py.test installed, a large part of the testsuite will get skipped59With only pytest installed, a large part of the testsuite will get skipped60though. Whether this is relevant depends on which part of Flask you're working61on. Travis is set up to run the full testsuite when you submit your pull62request anyways.63
14 unmodified lines
78 pip install pytest-cov7980After this has been installed, you can output a report to the command line using this command::8182 py.test --cov=flask tests/82 pytest --cov=flask tests/8384Generate a HTML report can be done using this command::8586 py.test --cov-report html --cov=flask tests/86 pytest --cov-report html --cov=flask tests/8788Full docs on ``coverage.py`` are here: https://coverage.readthedocs.io8990Caution91=======92pushing93-------94This repository contains several zero-padded file modes that may cause issues when pushing this repository to git hosts other than github. Fixing this is destructive to the commit history, so we suggest ignoring these warnings. If it fails to push and you're using a self-hosted git service like Gitlab, you can turn off repository checks in the admin panel.959697cloning98-------99The zero-padded file modes files above can cause issues while cloning, too. If you have100101::102103 [fetch]104 fsckobjects = true105106or107108::109110 [receive]111 fsckObjects = true112113114set in your git configuration file, cloning this repository will fail. The only solution is to set both of the above settings to false while cloning, and then setting them back to true after the cloning is finished.
modified:Makefile+2 added-5 removed
1 unmodified line
23all: clean-pyc test45test:6 pip install -r test-requirements.txt -q7 FLASK_DEBUG= py.test tests examples6 pip install -r test-requirements.txt7 tox -e py-release89tox-test:10 tox119audit:10 python setup.py audit1112release:
29 unmodified lines
modified:README+2 added-2 removed
31 unmodified lines
32 ~ Where are the tests?3334 Good that you're asking. The tests are in the35 tests/ folder. To run the tests use the36 `py.test` testing tool:36 `pytest` testing tool:3738 $ py.test38 $ pytest3940 Details on contributing can be found in CONTRIBUTING.rst4142 ~ Where can I get help?
7 unmodified lines
modified:setup.cfg+5 added-2 removed
1[aliases]2release = egg_info -RDb ''34[wheel]4[bdist_wheel]5universal = 167[metadata]8license_file = LICENSE910[tool:pytest]8norecursedirs = .* *.egg *.egg-info env* artwork docs examples11norecursedirs = .* *.egg *.egg-info env* artwork docs
modified:setup.py+2 added-2 removed
39 unmodified lines
4041* `website <http://flask.pocoo.org/>`_42* `documentation <http://flask.pocoo.org/docs/>`_43* `development version44 <http://github.com/pallets/flask/zipball/master#egg=Flask-dev>`_44 <https://github.com/pallets/flask/zipball/master#egg=Flask-dev>`_4546"""47import re48import ast
9 unmodified lines
5859setup(60 name='Flask',61 version=version,62 url='http://github.com/pallets/flask/',62 url='https://github.com/pallets/flask/',63 license='BSD',64 author='Armin Ronacher',65 author_email='armin.ronacher@active-4.com',66 description='A microframework based on Werkzeug, Jinja2 '
34 unmodified lines
modified:test-requirements.txt+1 added-1 removed
1pytest1tox
modified:tox.ini+9 added-3 removed
1[tox]2envlist = {py26,py27,pypy}-{lowest,release,devel}{,-simplejson}, {py33,py34,py35}-{release,devel}{,-simplejson}2envlist = {py26,py27,pypy}-{lowest,release,devel}{,-simplejson}, {py33,py34,py35,py36}-{release,devel}{,-simplejson}3456[testenv]7passenv = LANG8usedevelop=true9commands =8 py.test []910 # We need to install those after Flask is installed.11 pip install -e examples/flaskr12 pip install -e examples/minitwit13 pip install -e examples/patterns/largerapp14 pytest --cov=flask --cov-report html []15deps=16 pytest17 pytest-cov18 greenlet1920 lowest: Werkzeug==0.721 lowest: Jinja2==2.4
12 unmodified lines