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
Provenance
- Commit
f13e3fc- Tree
87beb7f- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
2b03eca- Parent 2
ff361d3
81 files changed+1639 added−800 removed
modified:docs/_templates/sidebarintro.html+3 added-3 removed
14 unmodified lines151617181920211920212214 unmodified lines</ul><h3>Useful Links</h3><ul> <li><a href="http://flask.pocoo.org/">The Flask Website</a></li> <li><a href="http://pypi.python.org/pypi/Flask">Flask @ PyPI</a></li> <li><a href="http://github.com/pallets/flask">Flask @ GitHub</a></li> <li><a href="http://github.com/pallets/flask/issues">Issue Tracker</a></li> <li><a href="https://pypi.python.org/pypi/Flask">Flask @ PyPI</a></li> <li><a href="https://github.com/pallets/flask">Flask @ GitHub</a></li> <li><a href="https://github.com/pallets/flask/issues">Issue Tracker</a></li></ul>modified:docs/deploying/fastcgi.rst+4 added-4 removed
142 unmodified lines143 ))144 )145 146 alias.url = (147- "/static/" => "/path/to/your/static"147+ "/static/" => "/path/to/your/static/"148 )149 150 url.rewrite-once = (151 "^(/static($|/.*))$" => "$1",6 unmodified lines158 :class:`~werkzeug.contrib.fixers.LighttpdCGIRootFix` middleware.159 160 Make sure to apply it only if you are mounting the application the URL161 root. 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 that163 explicitly passing a socket to run() is no longer necessary).164 165 Configuring nginx166 -----------------66 unmodified lines233 - The code depending on environment variables that are not set by the234 web server.235 - Different python interpreters being used.236 237-.. _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/flupmodified:docs/deploying/index.rst+2 added
19 unmodified lines20 - `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/>`_28 29 Self-hosted options30 -------------------31 8 unmodified linesmodified:docs/deploying/mod_wsgi.rst+4 added-4 removed
11 unmodified lines12 '__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.15 16-.. _Apache: http://httpd.apache.org/16+.. _Apache: https://httpd.apache.org/17 18 Installing `mod_wsgi`19 ---------------------20 92 unmodified lines113 </VirtualHost>114 115 Note: There have been some changes in access control configuration for `Apache 2.4`_.116 117-.. _Apache 2.4: http://httpd.apache.org/docs/trunk/upgrading.html117+.. _Apache 2.4: https://httpd.apache.org/docs/trunk/upgrading.html118 119 Most notably, the syntax for directory permissions has changed from httpd 2.2120 121 .. sourcecode:: apache10 unmodified lines132 133 For more information consult the `mod_wsgi documentation`_.134 135 .. _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.html139 140 Troubleshooting141 ---------------142 75 unmodified linesmodified:docs/deploying/uwsgi.rst+2 added-2 removed
64 unmodified lines65 include uwsgi_params;66 uwsgi_pass unix:/tmp/yourapplication.sock;67 }68 69-.. _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 lines5 6 If you are already using packages and blueprints for your application7 (:ref:`blueprints`) there are a couple of really nice ways to further improve8 the experience. A common pattern is creating the application object when9-the blueprint is imported. But if you move the creation of this object,9+the blueprint is imported. But if you move the creation of this object10 into a function, you can then create multiple instances of this app later.11 12 So why would you want to do this?13 45 unmodified lines59 60 It's preferable to create your extensions and app factories so that the61 extension object does not initially get bound to the application.62 63-Using `Flask-SQLAlchemy <http://pythonhosted.org/Flask-SQLAlchemy/>`_,63+Using `Flask-SQLAlchemy <http://flask-sqlalchemy.pocoo.org/>`_,64 as an example, you should not do something along those lines::65 66 def create_app(config_filename):67 app = Flask(__name__)49 unmodified linesmodified:docs/patterns/deferredcallbacks.rst+24 added-52 removed
1 unmodified line2 3 Deferred Request Callbacks4 ==========================5 6-One of the design principles of Flask is that response objects are created7-and passed down a chain of potential callbacks that can modify them or8-replace them. When the request handling starts, there is no response9-object yet. It is created as necessary either by a view function or by10-some other component in the system.6+One of the design principles of Flask is that response objects are created and7+passed down a chain of potential callbacks that can modify them or replace8+them. When the request handling starts, there is no response object yet. It is9+created as necessary either by a view function or by some other component in10+the system.11 12-But what happens if you want to modify the response at a point where the13-response does not exist yet? A common example for that would be a14-before-request function that wants to set a cookie on the response object.12+What happens if you want to modify the response at a point where the response13+does not exist yet? A common example for that would be a14+:meth:`~flask.Flask.before_request` callback that wants to set a cookie on the15+response object.16 16-One way is to avoid the situation. Very often that is possible. For17-instance you can try to move that logic into an after-request callback18-instead. Sometimes however moving that code there is just not a very19-pleasant experience or makes code look very awkward.17+One way is to avoid the situation. Very often that is possible. For instance18+you can try to move that logic into a :meth:`~flask.Flask.after_request`19+callback instead. However, sometimes moving code there makes it more20+more complicated or awkward to reason about.21 21-As an alternative possibility you can attach a bunch of callback functions22-to the :data:`~flask.g` object and call them at the end of the request.23-This way you can defer code execution from anywhere in the application.22+As an alternative, you can use :func:`~flask.after_this_request` to register23+callbacks that will execute after only the current request. This way you can24+defer code execution from anywhere in the application, based on the current25+request.26 25-26-The Decorator27--------------28-29-The following decorator is the key. It registers a function on a list on30-the :data:`~flask.g` object::31-32- from flask import g33-34- 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 f39-40-41-Calling the Deferred42---------------------43-44-Now you can use the `after_this_request` decorator to mark a function to45-be called at the end of the request. But we still need to call them. For46-this the following function needs to be registered as47-:meth:`~flask.Flask.after_request` callback::48-49- @app.after_request50- def call_after_request_callbacks(response):51- for callback in getattr(g, 'after_request_callbacks', ()):52- callback(response)53- return response54-55-56-A Practical Example57--------------------58-27 At any time during a request, we can register a function to be called at the60-end of the request. For example you can remember the current language of the61-user in a cookie in the before-request function::28+end of the request. For example you can remember the current language of the29+user in a cookie in a :meth:`~flask.Flask.before_request` callback::30 63- from flask import request31+ from flask import request, after_this_request32 33 @app.before_request34 def detect_user_language():35 language = request.cookies.get('user_lang')36+37 if language is None:38 language = guess_language_from_request()39+40+ # when the response exists, set a cookie with the language41 @after_this_request42 def remember_language(response):43 response.set_cookie('user_lang', language)44+45 g.language = languagemodified:docs/patterns/distribute.rst+1 added-1 removed
172 unmodified lines173 the code without having to run ``install`` again after each change.174 175 176 .. _pip: https://pypi.python.org/pypi/pip177-.. _Setuptools: https://pythonhosted.org/setuptools177+.. _Setuptools: https://pypi.python.org/pypi/setuptoolsmodified:docs/patterns/errorpages.rst+35 added-19 removed
45 unmodified lines46 47 Error Handlers48 --------------49 50-An error handler is a function, just like a view function, but it is51-called when an error happens and is passed that error. The error is most52-likely a :exc:`~werkzeug.exceptions.HTTPException`, but in one case it53-can be a different error: a handler for internal server errors will be54-passed other exception instances as well if they are uncaught.50+An error handler is a function that returns a response when a type of error is51+raised, similar to how a view is a function that returns a response when a52+request URL is matched. It is passed the instance of the error being handled,53+which is most likely a :exc:`~werkzeug.exceptions.HTTPException`. An error54+handler for "500 Internal Server Error" will be passed uncaught exceptions in55+addition to explicit 500 errors.56 57 An error handler is registered with the :meth:`~flask.Flask.errorhandler`57-decorator and the error code of the exception. Keep in mind that Flask58-will *not* set the error code for you, so make sure to also provide the59-HTTP status code when returning a response.58+decorator or the :meth:`~flask.Flask.register_error_handler` method. A handler59+can be registered for a status code, like 404, or for an exception class.60 61-Please note that if you add an error handler for "500 Internal Server62-Error", Flask will not trigger it if it's running in Debug mode.61+The status code of the response will not be set to the handler's code. Make62+sure to provide the appropriate HTTP status code when returning a response from63+a handler.64 64-Here an example implementation for a "404 Page Not Found" exception::65+A handler for "500 Internal Server Error" will not be used when running in66+debug mode. Instead, the interactive debugger will be shown.67 68+Here is an example implementation for a "404 Page Not Found" exception::69+70 from flask import render_template71 72 @app.errorhandler(404)73 def page_not_found(e):74+ # note that we set the 404 status explicitly75 return render_template('404.html'), 40476 77+When using the :ref:`application factory pattern <app-factories>`::78+79+ from flask import Flask, render_template80+81+ def page_not_found(e):82+ return render_template('404.html'), 40483+84+ def create_app(config_filename):85+ app = Flask(__name__)86+ app.register_error_handler(404, page_not_found)87+ return app88+89 An example template might be this:90 91 .. sourcecode:: html+jinja92 76- {% 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 %}83-93+ {% 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 lines48 49 See also50 --------51 52-* The `Favicon <http://en.wikipedia.org/wiki/Favicon>`_ article on52+* The `Favicon <https://en.wikipedia.org/wiki/Favicon>`_ article on53 Wikipediamodified:docs/patterns/fileuploads.rst+5 added-5 removed
19 unmodified lines20 specific upload folder and displays a file to the user. Let's look at the21 bootstrapping code for our application::22 23 import os24- from flask import Flask, request, redirect, url_for24+ from flask import Flask, flash, request, redirect, url_for25 from werkzeug.utils import secure_filename26 27 UPLOAD_FOLDER = '/path/to/the/uploads'28 ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])28 unmodified lines57 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 lines71 <!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 '''79 80 So what does that :func:`~werkzeug.utils.secure_filename` function actually do?99 unmodified lines180 `Flask-Uploads`_ that implements a full fledged upload mechanism with white and181 blacklisting of extensions and more.182 183 .. _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 lines16 index.html17 login.html18 ...19 20+If you find yourself stuck on something, feel free21+to take a look at the source code for this example.22+You'll find `the full src for this example here`_.23+24 Simple Packages25 ---------------26 27 To convert that into a larger one, just create a new folder36 unmodified lines64 65 export FLASK_APP=yourapplication66 67 If you are outside of the project directory make sure to provide the exact 64-path to your application directory. Similiarly you can turn on "debug 68+path to your application directory. Similarly you can turn on "debug 69 mode" with this environment variable:: 70 71 export FLASK_DEBUG=true 72 60 unmodified lines133 :ref:`becomingbig` section for some inspiration how to deal with that.134 135 136 .. _working-with-modules:137+.. _the full src for this example here: https://github.com/pallets/flask/tree/master/examples/patterns/largerapp138 139 Working with Blueprints140 -----------------------141 4 unmodified linesmodified:docs/patterns/sqlalchemy.rst+5 added-5 removed
20 unmodified lines21 22 You can download `Flask-SQLAlchemy`_ from `PyPI23 <https://pypi.python.org/pypi/Flask-SQLAlchemy>`_.24 25-.. _Flask-SQLAlchemy: http://pythonhosted.org/Flask-SQLAlchemy/25+.. _Flask-SQLAlchemy: http://flask-sqlalchemy.pocoo.org/26 27 28 Declarative29 -----------77 unmodified lines107 [<User u'admin'>]108 >>> User.query.filter(User.name == 'admin').first()109 <User u'admin'>110 111-.. _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/114 115 Manual Object Relational Mapping116 --------------------------------117 16 unmodified lines134 bind=engine))135 def init_db():136 metadata.create_all(bind=engine)137 138-As for the declarative approach you need to close the session after138+As in the declarative approach, you need to close the session after139 each request or application context shutdown. Put this into your140 application module::141 142 from yourapplication.database import db_session71 unmodified lines214 >>> engine.execute('select * from users where id = :1', [1]).first()215 (1, u'admin', u'admin@localhost')216 217 For 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 line2 3 Using SQLite 3 with Flask4 =========================5 6-In Flask you can easily implement the opening of database connections on 7-demand and closing them when the context dies (usually at the end of the 6+In Flask you can easily implement the opening of database connections on7+demand and closing them when the context dies (usually at the end of the8 request).9 10 Here is a simple example of how you can use SQLite 3 with Flask::11 58 unmodified lines70 Now in each request handling function you can access `g.db` to get the71 current open database connection. To simplify working with SQLite, a72 row factory function is useful. It is executed for every result returned73 from the database to convert the result. For instance, in order to get74-dictionaries instead of tuples, this could be inserted into the ``get_db`` 74+dictionaries instead of tuples, this could be inserted into the ``get_db``75 function we created above::76 77 def make_dicts(cursor, row):78 return dict((cursor.description[idx][0], value)22 unmodified lines101 M102 103 Additionally, it is a good idea to provide a query function that combines104 getting the cursor, executing and fetching the results::105- 105+106 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 rv111 112-This handy little function, in combination with a row factory, makes 113-working with the database much more pleasant than it is by just using the 112+This handy little function, in combination with a row factory, makes113+working with the database much more pleasant than it is by just using the114 raw cursor and connection objects.115 116 Here is how you can use it::117 12 unmodified lines130 To pass variable parts to the SQL statement, use a question mark in the131 statement and pass in the arguments as a list. Never directly add them to132 the SQL statement with string formatting because this makes it possible133 to attack the application using `SQL Injections134-<http://en.wikipedia.org/wiki/SQL_injection>`_.134+<https://en.wikipedia.org/wiki/SQL_injection>`_.135 136 Initial Schemas137 ---------------138 16 unmodified linesmodified:docs/patterns/wtforms.rst+1 added-1 removed
17 unmodified lines18 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>`_.21 22-.. _Flask-WTF: http://pythonhosted.org/Flask-WTF/22+.. _Flask-WTF: https://flask-wtf.readthedocs.io/en/stable/23 24 The Forms25 ---------26 100 unmodified linesmodified:docs/tutorial/introduction.rst+1 added-1 removed
29 unmodified lines30 :alt: screenshot of the final application31 32 Continue with :ref:`tutorial-folders`.33 34-.. _SQLAlchemy: http://www.sqlalchemy.org/34+.. _SQLAlchemy: https://www.sqlalchemy.org/modified:docs/tutorial/packaging.rst+1 added-1 removed
53 unmodified lines54 into this file, :file:`flaskr/__init__.py`:55 56 .. sourcecode:: python57 58- from flaskr import app58+ from .flaskr import app59 60 This import statement brings the application instance into the top-level 61 of the application package. When it is time to run the application, the 62 Flask development server needs the location of the app instance. This 46 unmodified linesmodified:docs/tutorial/templates.rst+3 added-3 removed
57 unmodified lines58 59 This template extends the :file:`layout.html` template from above to display the60 messages. Note that the ``for`` loop iterates over the messages we passed61 in with the :func:`~flask.render_template` function. Notice that the form is62-configured to to submit to the `add_entry` view function and use ``POST`` as62+configured to submit to the `add_entry` view function and use ``POST`` as63 HTTP method:64 65 .. sourcecode:: html+jinja66 11 unmodified lines78 </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 linesmodified:docs/tutorial/testing.rst+1 added-1 removed
44 unmodified lines45 46 Run and watch the tests pass, within the top-level :file:`flaskr/` 47 directory as::48 49- py.test49+ pytest50 51 Testing + setuptools52 --------------------53 43 unmodified linesmodified:docs/api.rst+2 added-58 removed
28 unmodified lines29 ---------------------30 31 .. autoclass:: Request32 :members:33+ :inherited-members:34 34- .. attribute:: form35-36- 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.39-40- .. attribute:: args41-42- A :class:`~werkzeug.datastructures.MultiDict` with the parsed contents of the query43- string. (The part in the URL after the question mark).44-45- .. attribute:: values46-47- A :class:`~werkzeug.datastructures.CombinedMultiDict` with the contents of both48- :attr:`form` and :attr:`args`.49-50- .. attribute:: cookies51-52- A :class:`dict` with the contents of all cookies transmitted with53- the request.54-55- .. attribute:: stream56-57- 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.61-62- .. attribute:: headers63-64- The incoming request headers as a dictionary like object.65-66- .. attribute:: data67-68- Contains the incoming request data as string in case it came with69- a mimetype Flask does not handle.70-71- .. attribute:: files72-73- 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.79-35 .. attribute:: environ36 37 The underlying WSGI environment.38 84- .. attribute:: method85-86- The current request method (``POST``, ``GET`` etc.)87-39 .. attribute:: path40 .. attribute:: full_path41 .. attribute:: script_root42 .. attribute:: url21 unmodified lines64 `url` ``u'http://www.example.com/myapplication/π/page.html?x=y'``65 `url_root` ``u'http://www.example.com/myapplication/'``66 ============= ======================================================67 117- .. attribute:: is_xhr68 119- ``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:: request70 125-.. class:: request126-71 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 you761 unmodified linesmodified:docs/becomingbig.rst+1 added-1 removed
10 unmodified lines11 Flask started in part to demonstrate how to build your own framework on top of12 existing well-used tools Werkzeug (WSGI) and Jinja (templating), and as it13 developed, it became useful to a wide audience. As you grow your codebase,14 don't just use Flask -- understand it. Read the source. Flask's code is15-written to be read; it's documentation is published so you can use its internal15+written to be read; its documentation is published so you can use its internal16 APIs. Flask sticks to documented APIs in upstream libraries, and documents its17 internal utilities so that you can find the hook points needed for your18 project.19 82 unmodified linesmodified:docs/blueprints.rst+23 added-5 removed
175 unmodified lines176 177 admin = Blueprint('admin', __name__, template_folder='templates')178 179 For static files, the path can be absolute or relative to the blueprint180-resource folder. 180+resource folder.181 182-The template folder is added to the search path of templates but with a lower 183-priority than the actual application's template folder. That way you can 184-easily override templates that a blueprint provides in the actual application. 182+The template folder is added to the search path of templates but with a lower183+priority than the actual application's template folder. That way you can184+easily override templates that a blueprint provides in the actual application.185 This also means that if you don't want a blueprint template to be accidentally186 overridden, make sure that no other blueprint or actual application template187 has the same relative path. When multiple blueprints provide the same relative188 template path the first blueprint registered takes precedence over the others.4 unmodified lines193 ``templates`` as a `template_folder` you will have to create a file like194 this: :file:`yourapplication/admin/templates/admin/index.html`. The reason195 for the extra ``admin`` folder is to avoid getting our template overridden196 by a template named ``index.html`` in the actual application template197-folder. 197+folder.198 199 To further reiterate this: if you have a blueprint named ``admin`` and you200 want to render a template called :file:`index.html` which is specific to this201 blueprint, the best idea is to lay out your templates like this::42 unmodified lines244 @simple_page.errorhandler(404)245 def page_not_found(e):246 return render_template('pages/404.html')247 248+Most errorhandlers will simply work as expected; however, there is a caveat249+concerning handlers for 404 and 405 exceptions. These errorhandlers are only250+invoked from an appropriate ``raise`` statement or a call to ``abort`` in another251+of the blueprint's view functions; they are not invoked by, e.g., an invalid URL252+access. This is because the blueprint does not "own" a certain URL space, so253+the application instance has no way of knowing which blueprint errorhandler it254+should run if given an invalid URL. If you would like to execute different255+handling strategies for these errors based on URL prefixes, they may be defined256+at the application level using the ``request`` proxy object::257+258+ @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 ex265+266 More information on error handling see :ref:`errorpages`.modified:docs/cli.rst+14 added-2 removed
54 unmodified lines55 ``export FLASK_APP`` into your ``activate`` script by adding it to the56 bottom of the file. That way every time you activate your virtualenv you57 automatically also activate the correct application name.58 59+Edit the activate script for the shell you use. For example:60+61+Unix Bash: ``venv/bin/activate``::62+63+ FLASK_APP=hello64+ export FLASK_APP65+66+Windows CMD.exe: ``venv\Scripts\activate.bat``::67+68+ set "FLASK_APP=hello"69+ :END70+71 Debug Flag72 ----------73 74 The :command:`flask` script can also be instructed to enable the debug75 unmodified lines150 import os151 from yourapplication import create_app152 app = create_app(os.environ['YOURAPPLICATION_CONFIG'])153 142-Once this has happened you can make the flask command automatically pick143-it up::154+Once this has happened you can make the :command:`flask` command automatically155+pick it up::156 157 export YOURAPPLICATION_CONFIG=/path/to/config.cfg158 export FLASK_APP=/path/to/autoapp.py159 101 unmodified linesmodified:docs/conf.py+15 added-4 removed
9 unmodified lines10 #11 # All configuration values have a default; values that are commented out12 # serve to show the default.13 from __future__ import print_function14-from datetime import datetime14 import os15 import sys16 import pkg_resources17+import time18+import datetime19 20+BUILD_DATE = datetime.datetime.utcfromtimestamp(int(os.environ.get('SOURCE_DATE_EPOCH', time.time())))21+22 # 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.25 sys.path.append(os.path.join(os.path.dirname(__file__), '_themes'))11 unmodified lines37 'sphinx.ext.intersphinx',38 'flaskdocext'39 ]40 41+try:42+ __import__('sphinxcontrib.log_cabinet')43+except ImportError:44+ print('sphinxcontrib-log-cabinet is not installed.')45+ print('Changelog directives will not be re-organized.')46+else:47+ extensions.append('sphinxcontrib.log_cabinet')48+49 # Add any paths that contain templates here, relative to this directory.50 templates_path = ['_templates']51 52 # The suffix of source filenames.6 unmodified lines59 master_doc = 'index'60 61 # General information about the project.62 project = u'Flask'52-copyright = u'2010 - {0}, Armin Ronacher'.format(datetime.utcnow().year)63+copyright = u'2010 - {0}, Armin Ronacher'.format(BUILD_DATE.year)64 65 # 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 lines241 242 # The scheme of the identifier. Typical schemes are ISBN or URL.243 #epub_scheme = ''244 234-# 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 = ''248 249 # A unique identification for the text.17 unmodified lines267 '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 linesmodified:docs/config.rst+28 added-14 removed
42 unmodified lines43 DEBUG=True,44 SECRET_KEY='...'45 )46 47+.. admonition:: Debug Mode with the ``flask`` Script48+49+ 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::52+53+ $ export FLASK_DEBUG=154+ $ flask run55+56+ (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+ 62 Builtin Configuration Values63 ----------------------------64 65 The following configuration values are used internally by Flask:66 67 .. tabularcolumns:: |p{6.5cm}|p{8.5cm}|68 69 ================================= =========================================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 is55 unmodified lines131 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 lines193 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 is71 unmodified lines275 app.config.from_envvar('YOURAPPLICATION_SETTINGS')276 277 This first loads the configuration from the278 `yourapplication.default_settings` module and then overrides the values265-with the contents of the file the :envvar:``YOURAPPLICATION_SETTINGS``279+with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS`280 environment variable points to. This environment variable can be set on281 Linux or OS X with the export command in the shell before starting the282 server::283 196 unmodified linesmodified:docs/errorhandling.rst+6 added-5 removed
32 unmodified lines33 34 Sending error mails, even if just for critical ones, can become35 overwhelming if enough users are hitting the error and log files are36 typically 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's38 available 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. Sentry41 aggregates duplicate errors, captures the full stack trace and local46 unmodified lines88 89 @app.errorhandler(werkzeug.exceptions.BadRequest)90 def handle_bad_request(e):91 return 'bad request!'92- 92+93 app.register_error_handler(400, lambda e: 'bad request!')94 95 Those two ways are equivalent, but the first one is more clear and leaves96 you with a function to call on your whim (and in tests). Note that118 unmodified lines215 A formatter can be instantiated with a format string. Note that216 tracebacks are appended to the log entry automatically. You don't have to217 do that in the log formatter format string.218 219-Here some example setups:219+Here are some example setups:220 221 Email222 `````223 51 unmodified lines275 +------------------+----------------------------------------------------+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 linesmodified:docs/extensiondev.rst+1 added-9 removed
27 unmodified lines28 "Flask" somewhere in that name and that you check the capitalization.29 This is how users can then register dependencies to your extension in30 their :file:`setup.py` files.31 32-Flask sets up a redirect package called :data:`flask.ext` where users33-should import the extensions from. If you for instance have a package34-called ``flask_something`` users would import it as35-``flask.ext.something``. This is done to transition from the old36-namespace packages. See :ref:`ext-import-transition` for more details.37-32 But what do extensions look like themselves? An extension has to ensure33 that it works with multiple Flask application instances at once. This is34 a requirement because many people will use patterns like the35 :ref:`app-factories` pattern to create their application as needed to aid350 unmodified lines386 10. An extension currently has to support Python 2.6 as well as387 Python 2.7388 389 396-.. _ext-import-transition:397-390 Extension Import Transition391 ---------------------------392 393 In early versions of Flask we recommended using namespace packages for Flask10 unmodified lines404 schema. The ``flask.ext.foo`` compatibility alias is still in Flask 0.11 but is405 now deprecated -- you should use ``flask_foo``.406 407 416-.. _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 line2 3 Installation4 ============5 6-Flask depends on some external libraries, like `Werkzeug7-<http://werkzeug.pocoo.org/>`_ and `Jinja2 <http://jinja.pocoo.org/>`_.8-Werkzeug is a toolkit for WSGI, the standard Python interface between web9-applications and a variety of servers for both development and deployment.10-Jinja2 renders templates.6+Python Version7+--------------8 12-So how do you get all that on your computer quickly? There are many ways you13-could do that, but the most kick-ass method is virtualenv, so let's have a look14-at that first.9+We recommend using the latest version of Python 3. Flask supports Python 3.310+and newer, Python 2.6 and newer, and PyPy.11 16-You will need Python 2.6 or newer to get started, so be sure to have an17-up-to-date Python 2.x installation. For using Flask with Python 3 have a18-look at :ref:`python3-support`.12+Dependencies13+------------14 20-.. _virtualenv:15+These distributions will be installed automatically when installing Flask.16 22-virtualenv23-----------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.27 25-Virtualenv is probably what you want to use during development, and if you have26-shell access to your production machines, you'll probably want to use it there,27-too.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/33 29-What problem does virtualenv solve? If you like Python as much as I do,30-chances are you want to use it for other projects besides Flask-based web31-applications. But the more projects you have, the more likely it is that you32-will be working with different versions of Python itself, or at least different33-versions of Python libraries. Let's face it: quite often libraries break34-backwards compatibility, and it's unlikely that any serious application will35-have zero dependencies. So what do you do if two or more of your projects have36-conflicting dependencies?34+Optional dependencies35+~~~~~~~~~~~~~~~~~~~~~36 38-Virtualenv to the rescue! Virtualenv enables multiple side-by-side39-installations of Python, one for each project. It doesn't actually install40-separate copies of Python, but it does provide a clever way to keep different41-project environments isolated. Let's see how virtualenv works.37+These distributions will not be installed automatically. Flask will detect and38+use them if you install them.39 43-If you are on Mac OS X or Linux, chances are that the following44-command 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.44 46- $ sudo pip install virtualenv45+.. _Blinker: https://pythonhosted.org/blinker/46+.. _SimpleJSON: https://simplejson.readthedocs.io/47 48-It will probably install virtualenv on your system. Maybe it's even49-in your package manager. If you use Ubuntu, try::48+Virtual environments49+--------------------50 51- $ sudo apt-get install python-virtualenv51+Use a virtual environment to manage the dependencies for your project, both in52+development and in production.53 53-If you are on Windows and don't have the ``easy_install`` command, you must54-install it first. Check the :ref:`windows-easy-install` section for more55-information about how to do that. Once you have it installed, run the same56-commands as above, but without the ``sudo`` prefix.54+What problem does a virtual environment solve? The more Python projects you55+have, the more likely it is that you need to work with different versions of56+Python libraries, or even Python itself. Newer versions of libraries for one57+project can break compatibility in another project.58 58-Once you have virtualenv installed, just fire up a shell and create59-your own environment. I usually create a project folder and a :file:`venv`60-folder within::59+Virtual environments are independent groups of Python libraries, one for each60+project. Packages installed for one project will not affect other projects or61+the operating system's packages.62 62- $ mkdir myproject63- $ cd myproject64- $ virtualenv venv65- New python executable in venv/bin/python66- Installing setuptools, pip............done.63+Python 3 comes bundled with the :mod:`venv` module to create virtual64+environments. If you're using a modern version of Python, you can continue on65+to the next section.66 68-Now, whenever you want to work on a project, you only have to activate the69-corresponding environment. On OS X and Linux, do the following::67+If you're using Python 2, see :ref:`install-install-virtualenv` first.68 71- $ . venv/bin/activate69+.. _install-create-env:70 73-If you are a Windows user, the following command is for you::71+Create an environment72+~~~~~~~~~~~~~~~~~~~~~73 75- $ venv\scripts\activate74+Create a project folder and a :file:`venv` folder within:75 77-Either way, you should now be using your virtualenv (notice how the prompt of78-your shell has changed to show the active environment).76+.. code-block:: sh77 80-And if you want to go back to the real world, use the following command::78+ mkdir myproject79+ cd myproject80+ python3 -m venv venv81 82- $ deactivate82+On Windows:83 84-After doing this, the prompt of your shell should be as familiar as before.84+.. code-block:: bat85 86-Now, let's move on. Enter the following command to get Flask activated in your87-virtualenv::86+ py -3 -m venv venv87 89- $ pip install Flask88+If you needed to install virtualenv because you are on an older version of89+Python, use the following command instead:90 91-A few seconds later and you are good to go.91+.. code-block:: sh92 93+ virtualenv venv94 94-System-Wide Installation95-------------------------95+On Windows:96 97-This is possible as well, though I do not recommend it. Just run98-``pip`` with root privileges::97+.. code-block:: bat98 100- $ sudo pip install Flask99+ \Python27\Scripts\virtualenv.exe venv100 102-(On Windows systems, run it in a command-prompt window with administrator103-privileges, and leave out ``sudo``.)101+Activate the environment102+~~~~~~~~~~~~~~~~~~~~~~~~103 104+Before you work on your project, activate the corresponding environment:105 106-Living on the Edge107-------------------106+.. code-block:: sh107 109-If you want to work with the latest version of Flask, there are two ways: you110-can either let ``pip`` pull in the development version, or you can tell111-it to operate on a git checkout. Either way, virtualenv is recommended.108+ . venv/bin/activate109 113-Get the git checkout in a new virtualenv and run in development mode::110+On Windows:111 115- $ 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:: bat113 126-This will pull in the dependencies and activate the git head as the current127-version inside the virtualenv. Then all you have to do is run ``git pull128-origin`` to update to the latest version.114+ venv\Scripts\activate115 130-.. _windows-easy-install:116+Your shell prompt will change to show the name of the activated environment.117 132-`pip` and `setuptools` on Windows133----------------------------------118+Install Flask119+-------------120 135-Sometimes getting the standard "Python packaging tools" like ``pip``, ``setuptools``136-and ``virtualenv`` can be a little trickier, but nothing very hard. The crucial137-package you will need is pip - this will let you install138-anything else (like virtualenv). Fortunately there is a "bootstrap script"139-you can run to install.121+Within the activated environment, use the following command to install Flask:122 141-If you don't currently have ``pip``, then `get-pip.py` will install it for you.123+.. code-block:: sh124 143-`get-pip.py`_125+ pip install Flask126 145-It should be double-clickable once you download it. If you already have ``pip``,146-you can upgrade them by running::127+Living on the edge128+~~~~~~~~~~~~~~~~~~129 148- > pip install --upgrade pip setuptools130+If you want to work with the latest Flask code before it's released, install or131+update the code from the master branch:132 150-Most often, once you pull up a command prompt you want to be able to type ``pip``151-and ``python`` which will run those things, but this might not automatically happen152-on Windows, because it doesn't know where those executables are (give either a try!).133+.. code-block:: sh134 154-To 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 and157-check that you can now just type ``python`` to bring up the interpreter.135+ pip install -U https://github.com/pallets/flask/archive/master.tar.gz136 159-Finally, to install `virtualenv`_, you can simply run::137+.. _install-install-virtualenv:138 161- > pip install virtualenv139+Install virtualenv140+------------------141 163-Then you can be off on your way following the installation instructions above.142+If you are using Python 2, the venv module is not available. Instead,143+install `virtualenv`_.144 145+On Linux, virtualenv is provided by your package manager:146+147+.. code-block:: sh148+149+ # Debian, Ubuntu150+ sudo apt-get install python-virtualenv151+152+ # CentOS, Fedora153+ sudo yum install python-virtualenv154+155+ # Arch156+ sudo pacman -S python-virtualenv157+158+If you are on Mac OS X or Windows, download `get-pip.py`_, then:159+160+.. code-block:: sh161+162+ sudo python2 Downloads/get-pip.py163+ sudo python2 -m pip install virtualenv164+165+On Windows, as an administrator:166+167+.. code-block:: bat168+169+ \Python27\python.exe Downloads\get-pip.py170+ \Python27\python.exe -m pip install virtualenv171+172+Now you can continue to :ref:`install-create-env`.173+174+.. _virtualenv: https://virtualenv.pypa.io/175 .. _get-pip.py: https://bootstrap.pypa.io/get-pip.pymodified:docs/quickstart.rst+103 added-159 removed
100 unmodified lines101 102 Invalid Import Name103 ```````````````````104 105-The ``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 107-import error upon start (or if debug is enabled when you navigate to the 105+The ``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 an107+import error upon start (or if debug is enabled when you navigate to the108 application). It will tell you what it tried to import and why it failed.109 110 The most common reason is a typo or because you did not actually create an111 ``app`` object.46 unmodified lines158 159 Routing160 -------161 162-Modern web applications have beautiful URLs. This helps people remember163-the URLs, which is especially handy for applications that are used from164-mobile devices with slower network connections. If the user can directly165-go to the desired page without having to hit the index page it is more166-likely they will like the page and come back next time.162+Modern web applications use meaningful URLs to help users. Users are more163+likely to like a page and come back if the page uses a meaningful URL they can164+remember and use to directly visit a page.165 168-As you have seen above, the :meth:`~flask.Flask.route` decorator is used to169-bind a function to a URL. Here are some basic examples::166+Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::167 168 @app.route('/')169 def index():170 return 'Index Page'1 unmodified line172 @app.route('/hello')173 def hello():174 return 'Hello, World'175 179-But there is more to it! You can make certain parts of the URL dynamic and180-attach multiple rules to a function.176+You can do more! You can make parts of the URL dynamic and attach multiple177+rules to a function.178 179 Variable Rules180 ``````````````181 185-To 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 your187-function. Optionally a converter can be used by specifying a rule with188-``<converter:variable_name>``. Here are some nice examples::182+You can add variable sections to a URL by marking sections with183+``<variable_name>``. Your function then receives the ``<variable_name>``184+as a keyword argument. Optionally, you can use a converter to specify the type185+of the argument like ``<converter:variable_name>``. ::186 187 @app.route('/user/<username>')188 def show_user_profile(username):189 # show the user profile for that user3 unmodified lines193 def show_post(post_id):194 # show the post with the given id, the id is an integer195 return 'Post %d' % post_id196 200-The following converters exist:197+ @app.route('/path/<path:subpath>')198+ def show_subpath(subpath):199+ # show the subpath after /path/200+ return 'Subpath %s' % subpath201 202-=========== ===============================================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-=========== ===============================================202+Converter types:203 211-.. 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+========== ==========================================211 213- 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.212+Unique URLs / Redirection Behavior213+``````````````````````````````````214 217- Take these two rules::215+Take these two rules::216 219- @app.route('/projects/')220- def projects():221- return 'The project page'217+ @app.route('/projects/')218+ def projects():219+ return 'The project page'220 223- @app.route('/about')224- def about():225- return 'The about page'221+ @app.route('/about')222+ def about():223+ return 'The about page'224 227- 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.225+Though they look similar, they differ in their use of the trailing slash in226+the URL. In the first case, the canonical URL for the ``projects`` endpoint227+uses a trailing slash. It's similar to a folder in a file system; if you228+access the URL without a trailing slash, Flask redirects you to the229+canonical URL with the trailing slash.230 233- 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.231+In the second case, however, the URL definition lacks a trailing slash,232+like the pathname of a file on UNIX-like systems. Accessing the URL with a233+trailing slash produces a 404 “Not Found” error.234 237- 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.235+This behavior allows relative URLs to continue working even if the trailing236+slash is omitted, consistent with how Apache and other servers work. Also,237+the URLs will stay unique, which helps search engines avoid indexing the238+same page twice.239 242-240 .. _url-building:241 242 URL Building243 ````````````244 248-If it can match URLs, can Flask also generate them? Of course it can. To249-build a URL to a specific function you can use the :func:`~flask.url_for`250-function. It accepts the name of the function as first argument and a number251-of keyword arguments, each corresponding to the variable part of the URL rule.252-Unknown variable parts are appended to the URL as query parameters. Here are253-some examples::245+To build a URL to a specific function, use the :func:`~flask.url_for` function.246+It accepts the name of the function as its first argument and any number of247+keyword arguments, each corresponding to a variable part of the URL rule.248+Unknown variable parts are appended to the URL as query parameters.249 255- >>> 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%20Doe276-277-(This also uses the :meth:`~flask.Flask.test_request_context` method, explained278-below. It tells Flask to behave as though it is handling a request, even279-though we are interacting with it through a Python shell. Have a look at the280-explanation below. :ref:`context-locals`).281-250 Why would you want to build URLs using the URL reversing function251 :func:`~flask.url_for` instead of hard-coding them into your templates?284-There are three good reasons for this:252 286-1. 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.289-2. URL building will handle escaping of special characters and Unicode290- data transparently for you, so you don't have to deal with them.291-3. If your application is placed outside the URL root - say, in292- ``/myapplication`` instead of ``/`` - :func:`~flask.url_for` will handle293- that properly for you.253+1. Reversing is often more descriptive than hard-coding the URLs.254+2. You can change your URLs in one go instead of needing to remember to255+ manually change hard-coded URLs.256+3. URL building handles escaping of special characters and Unicode data257+ transparently.258+4. If your application is placed outside the URL root, for example, in259+ ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly260+ handles that for you.261 262+For example, here we use the :meth:`~flask.Flask.test_request_context` method263+to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`264+tells Flask to behave as though it's handling a request even while we use a265+Python shell. See :ref:`context-locals`. ::266 267+ from flask import Flask, url_for268+269+ app = Flask(__name__)270+271+ @app.route('/')272+ def index():273+ return 'index'274+275+ @app.route('/login')276+ def login():277+ return 'login'278+279+ @app.route('/user/<username>')280+ def profile(username):281+ return '{}'s profile'.format(username)282+283+ 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'))288+289+ /290+ /login291+ /login?next=/292+ /user/John%20Doe293+294 HTTP Methods295 ````````````296 299-HTTP (the protocol web applications are speaking) knows different methods for300-accessing URLs. By default, a route only answers to ``GET`` requests, but that301-can be changed by providing the ``methods`` argument to the302-:meth:`~flask.Flask.route` decorator. Here are some examples::297+Web applications use different HTTP methods when accessing URLs. You should298+familiarize yourself with the HTTP methods as you work with Flask. By default,299+a route only answers to ``GET`` requests. You can use the ``methods`` argument300+of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.301+::302 304- from flask import request305-303 @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()309 313-If ``GET`` is present, ``HEAD`` will be added automatically for you. You314-don't have to deal with that. It will also make sure that ``HEAD`` requests315-are handled as the `HTTP RFC`_ (the document describing the HTTP316-protocol) demands, so you can completely ignore that part of the HTTP317-specification. Likewise, as of Flask 0.6, ``OPTIONS`` is implemented for you318-automatically as well.310+If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method311+and handles ``HEAD`` requests according to the the `HTTP RFC`_. Likewise,312+``OPTIONS`` is automatically implemented for you.313 320-You have no idea what an HTTP method is? Worry not, here is a quick321-introduction to HTTP methods and why they matter:314+.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt315 323-The HTTP method (also often called "the verb") tells the server what the324-client wants to *do* with the requested page. The following methods are325-very common:326-327-``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.330-331-``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.338-339-``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.344-345-``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.354-355-``DELETE``356- Remove the information at the given location.357-358-``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.362-363-Now the interesting part is that in HTML4 and XHTML1, the only methods a364-form can submit to the server are ``GET`` and ``POST``. But with JavaScript365-and future HTML standards you can use the other methods as well. Furthermore366-HTTP has become quite popular lately and browsers are no longer the only367-clients that are using HTTP. For instance, many revision control systems368-use it.369-370-.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt371-316 Static Files317 ------------318 319 Dynamic web applications also need static files. That's usually where161 unmodified lines481 The Request Object482 ``````````````````483 484 The request object is documented in the API section and we will not cover541-it here in detail (see :class:`~flask.request`). Here is a broad overview of485+it here in detail (see :class:`~flask.Request`). Here is a broad overview of486 some of the most common operations. First of all you have to import it from487 the ``flask`` module::488 489 from flask import request490 491 The 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 (data493 transmitted 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 two495 attributes mentioned above::496 497 @app.route('/login', methods=['POST', 'GET'])498 def login():14 unmodified lines513 error page is shown instead. So for many situations you don't have to514 deal with that problem.515 516 To access parameters submitted in the URL (``?key=value``) you can use the573-:attr:`~flask.request.args` attribute::517+:attr:`~flask.Request.args` attribute::518 519 searchword = request.args.get('key', '')520 521 We recommend accessing URL parameters with `get` or by catching the522 :exc:`KeyError` because users might change the URL and presenting them a 400523 bad request page in that case is not user friendly.524 525 For a full list of methods and attributes of the request object, head over582-to the :class:`~flask.request` documentation.526+to the :class:`~flask.Request` documentation.527 528 529 File Uploads530 ````````````307 unmodified linesmodified:docs/security.rst+1 added-1 removed
13 unmodified lines14 it JavaScript) into the context of a website. To remedy this, developers15 have to properly escape text so that it cannot include arbitrary HTML16 tags. For more information on that have a look at the Wikipedia article17 on `Cross-Site Scripting18-<http://en.wikipedia.org/wiki/Cross-site_scripting>`_.18+<https://en.wikipedia.org/wiki/Cross-site_scripting>`_.19 20 Flask configures Jinja2 to automatically escape all values unless21 explicitly told otherwise. This should rule out all XSS problems caused22 in templates, but there are still other places where you have to be84 unmodified linesmodified:docs/styleguide.rst+1 added-1 removed
165 unmodified lines166 is on its own line.167 """168 169 Module 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::173 174 # -*- coding: utf-8 -*-26 unmodified linesmodified:docs/testing.rst+6 added-4 removed
31 unmodified lines32 In order to test the application, we add a second module33 (:file:`flaskr_tests.py`) and create a unittest skeleton there::34 35 import os36- import flaskr36+ from flaskr import flaskr37 import unittest38 import tempfile39 40 class FlaskrTestCase(unittest.TestCase):41 42 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 lines97 class FlaskrTestCase(unittest.TestCase):98 99 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()105 106 def tearDown(self):107 os.close(self.db_fd)108 os.unlink(flaskr.app.config['DATABASE'])100 unmodified lines209 :class:`~flask.g` and :class:`~flask.session` objects like in view210 functions. Here is a full example that demonstrates this approach::211 212 import flask211- 213+214 app = flask.Flask(__name__)215 216 with app.test_request_context('/?name=Peter'):217 assert flask.request.path == '/'140 unmodified linesmodified:docs/upgrading.rst+3 added-3 removed
47 unmodified lines48 # ETag still needs to be manually set49 response = send_file(open(fname), attachment_filename=fname)50 response.set_etag(...)51 52-The reason for this is that some file-like objects have a invalid or even52+The reason for this is that some file-like objects have an invalid or even53 misleading ``name`` attribute. Silently swallowing errors in such cases was not54 a satisfying solution.55 56 Additionally the default of falling back to ``application/octet-stream`` has85 unmodified lines142 when 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`.145 146-.. _Flask-OldSessions: http://pythonhosted.org/Flask-OldSessions/146+.. _Flask-OldSessions: https://pythonhosted.org/Flask-OldSessions/147 148 Version 0.9149 -----------150 46 unmodified lines197 applications with Flask. Because we want to make upgrading as easy as198 possible we tried to counter the problems arising from these changes by199 providing a script that can ease the transition.200 201-The script scans your whole application and generates an unified diff with201+The script scans your whole application and generates a unified diff with202 changes it assumes are safe to apply. However as this is an automated203 tool it won't be able to find all use cases and it might miss some. We204 internally spread a lot of deprecation warnings all over the place to make205 it easy to find pieces of code that it was unable to upgrade.267 unmodified linesmodified:examples/flaskr/flaskr/__init__.py+1 added-1 removed
1-from flaskr.flaskr import app1+from .flaskr import appmodified:examples/flaskr/setup.cfg+1 added-1 removed
1-[aliases]1+[tool:pytest]2 test=pytestmodified:examples/minitwit/minitwit/__init__.py+1 added-1 removed
1-from minitwit import app1+from .minitwit import appmodified:examples/minitwit/minitwit/minitwit.py+1 added-1 removed
83 unmodified lines84 85 86 def 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)90 91 92 @app.before_request164 unmodified linesmodified:examples/minitwit/README+7 added-3 removed
12 unmodified lines13 1. edit the configuration in the minitwit.py file or14 export an MINITWIT_SETTINGS environment variable15 pointing to a configuration file.16 17- 2. tell flask about the right application:17+ 2. install the app from the root of the project directory18 19+ pip install --editable .20+21+ 3. tell flask about the right application:22+23 export FLASK_APP=minitwit24 21- 2. fire up a shell and run this:25+ 4. fire up a shell and run this:26 27 flask initdb28 25- 3. now you can run minitwit:29+ 5. now you can run minitwit:30 31 flask run32 33 the application will greet you on6 unmodified linesadded:examples/patterns/largerapp/tests/test_largerapp.py+12 added
1+from yourapplication import app2+import pytest3+4+@pytest.fixture5+def client():6+ app.config['TESTING'] = True7+ client = app.test_client()8+ return client9+10+def test_index(client):11+ rv = client.get('/')12+ assert b"Hello World!" in rv.dataadded: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
1+from flask import Flask2+app = Flask(__name__)3+4+import yourapplication.viewsadded:examples/patterns/largerapp/yourapplication/views.py+5 added
1+from yourapplication import app2+3+@app.route('/')4+def index():5+ return 'Hello World!'added:examples/patterns/largerapp/setup.py+10 added
1+from setuptools import setup2+3+setup(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 lines9 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11 """12 13-__version__ = '0.11.2-dev'13+__version__ = '0.13-dev'14 15 # utilities we import from Werkzeug and Jinja2 that are unused16 # in the module but are exported as public interface.17 from werkzeug.exceptions import abort21 unmodified lines39 # We're not exposing the actual json module but a convenient wrapper around40 # it.41 from . import json42 43-# 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.45 jsonify = json.jsonify46 47 # backwards compat, goes away in 1.02 unmodified linesmodified:flask/app.py+198 added-127 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 import os12 import sys13-from threading import Lock13 from datetime import timedelta15-from itertools import chain14 from functools import update_wrapper17-from collections import deque15+from itertools import chain16+from threading import Lock17 19-from werkzeug.datastructures import ImmutableDict20-from werkzeug.routing import Map, Rule, RequestRedirect, BuildError21-from werkzeug.exceptions import HTTPException, InternalServerError, \22- MethodNotAllowed, BadRequest, default_exceptions18+from werkzeug.datastructures import ImmutableDict, Headers19+from werkzeug.exceptions import BadRequest, HTTPException, \20+ InternalServerError, MethodNotAllowed, default_exceptions21+from werkzeug.routing import BuildError, Map, RequestRedirect, Rule22 24-from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \25- locked_cached_property, _endpoint_from_view_func, find_package, \26- get_debug_flag27-from . import json, cli28-from .wrappers import Request, Response29-from .config import ConfigAttribute, Config30-from .ctx import RequestContext, AppContext, _AppCtxGlobals31-from .globals import _request_ctx_stack, request, session, g23+from . import cli, json24+from ._compat import integer_types, reraise, string_types, text_type25+from .config import Config, ConfigAttribute26+from .ctx import AppContext, RequestContext, _AppCtxGlobals27+from .globals import _request_ctx_stack, g, request, session28+from .helpers import _PackageBoundObject, \29+ _endpoint_from_view_func, find_package, get_debug_flag, \30+ get_flashed_messages, locked_cached_property, url_for31 from .sessions import SecureCookieSessionInterface32+from .signals import appcontext_tearing_down, got_request_exception, \33+ request_finished, request_started, request_tearing_down34 from .templating import DispatchingJinjaLoader, Environment, \34- _default_template_ctx_processor35-from .signals import request_started, request_finished, got_request_exception, \36- request_tearing_down, appcontext_tearing_down37-from ._compat import reraise, string_types, text_type, integer_types35+ _default_template_ctx_processor36+from .wrappers import Request, Response37 38 # a lock used for logger initialization39 _logger_lock = Lock()40 81 unmodified lines122 123 .. versionadded:: 0.11124 The `root_path` parameter was added.125 126+ .. versionadded:: 0.13127+ The `host_matching` and `static_host` parameters were added.128+129 :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 lines323 '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 lines346 #: .. versionadded:: 0.8347 session_interface = SecureCookieSessionInterface()348 349 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 lines401 #: 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}408 409 #: A list of functions that are called when :meth:`url_for` raises a4 unmodified lines414 #:415 #: .. versionadded:: 0.9416 self.url_build_error_handlers = []417 408- #: 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 = {}424 416- #: 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 lines455 #:456 #: .. versionadded:: 0.9457 self.teardown_appcontext_funcs = []458 450- #: 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 lines533 #: app = Flask(__name__)534 #: app.url_map.converters['list'] = ListConverter535 self.url_map = Map()536 537+ self.url_map.host_matching = host_matching538+539 # tracks internally if the application already handled at least one540 # request.541 self._got_first_request = False542 self._before_request_lock = Lock()543 534- # 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)554 555 #: The click command line context for this application. Commands556 #: registered here show up in the :command:`flask` command once the267 unmodified lines824 The default port is now picked from the ``SERVER_NAME`` variable.825 826 :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 lines836 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+ return846+847 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 lines977 """978 return iter(self._blueprint_order)979 980 @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 lines1017 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 limited21 unmodified lines1050 required_methods = set(getattr(view_func, 'required_methods', ()))1051 1052 # 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)1057 1058 if provide_automatic_options is None:1059 if 'OPTIONS' not in methods:1060 provide_automatic_options = True115 unmodified lines1176 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.1179 1156- :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 f125 unmodified lines1311 1312 @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.1318 1291- 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 lines1373 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.1376 1350- 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.1379 1380 The return values of teardown functions are ignored.1381 54 unmodified lines1436 return f1437 1438 @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 lines1470 1471 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()1443-1444- 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 handler1480 1455- queue.extend(cls.__mro__)1456-1481 # try blueprint handlers1482 handler = find_handler(self.error_handler_spec1483 .get(request.blueprint, {})1484 .get(code))237 unmodified lines1722 """1723 return False1724 1725 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`.1728 1705- 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``:1733 1707- .. 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.1759 1709- ======================= ===========================================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- ======================= ===========================================1724-1725- :param rv: the return value from the view function1726-1760 .. 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))1764 1735- if rv is None:1736- raise ValueError('View function did not return a response')1765+ status = headers = None1766 1738- 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)1770 1771+ # 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+ )1787+1788+ # 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+ )1795+1796+ # 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])1817 1818+ # 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 = status1824+1825+ # extend existing headers with provided headers1826 if headers:1827 rv.headers.extend(headers)1828 1829 return rv54 unmodified lines1884 reraise(exc_type, exc_value, tb)1885 raise error1886 1887 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.1826-1827- 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 """1897+1898 bp = _request_ctx_stack.top.request.blueprint1899 1900 funcs = self.url_value_preprocessors.get(None, ())1901 if bp is not None and bp in self.url_value_preprocessors:151 unmodified lines2053 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 = None11 unmodified linesmodified:flask/blueprints.py+7 added
87 unmodified lines88 89 warn_on_modifications = False90 _got_registered_once = False91 92+ #: 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 = None98+99 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 linesmodified:flask/cli.py+78 added-9 removed
9 unmodified lines10 """11 12 import os13 import sys14-from threading import Lock, Thread14+import traceback15 from functools import update_wrapper16+from operator import attrgetter17+from threading import Lock, Thread18 19 import click20 21+from . import __version__22 from ._compat import iteritems, reraise23+from .globals import current_app24 from .helpers import get_debug_flag21-from . import __version__25 26+27 class NoAppException(click.UsageError):28 """Raised if an application cannot be found or loaded."""29 30 61 unmodified lines92 93 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)107+108 mod = sys.modules[module]109 if app_obj is None:110 app = find_best_app(mod)111 else:30 unmodified lines142 callback=get_version,143 is_flag=True, is_eager=True)144 145 class 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 """151 152 def __init__(self, loader, use_eager_loading=False):168 unmodified lines321 322 if add_default_commands:323 self.add_command(run_command)324 self.add_command(shell_command)325+ self.add_command(routes_command)326 327 self._loaded_plugin_commands = False328 329 def _load_plugin_commands(self):44 unmodified lines374 # 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)382 383 def main(self, *args, **kwargs):384 obj = kwargs.get('obj')35 unmodified lines420 Flask is enabled and disabled otherwise.421 """422 from werkzeug.serving import run_simple423 424+ # 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'430+431 debug = get_debug_flag()432 if reload is None:433 reload = bool(debug)434 if debugger is None:52 unmodified lines487 488 code.interact(banner=banner, local=ctx)489 490 491+@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_appcontext507+def routes_command(sort, all_methods):508+ """Show all registered routes with endpoints and methods."""509+510+ rules = list(current_app.url_map.iter_rules())511+ ignored_methods = set(() if all_methods else ('HEAD', 'OPTIONS'))512+513+ 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))517+518+ rule_methods = [519+ ', '.join(sorted(rule.methods - ignored_methods)) for rule in rules520+ ]521+522+ 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)530+531+ click.echo(row.format(*headers).strip())532+ click.echo(row.format(*('-' * width for width in widths)))533+534+ for rule, methods in zip(rules, rule_methods):535+ click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())536+537+538 cli = FlaskGroup(help="""\539 This shell command acts as general utility script for Flask applications.540 541 It loads the application configured (through the FLASK_APP environment39 unmodified linesmodified:flask/config.py+1 added-1 removed
124 unmodified lines125 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 False130 unmodified linesmodified:flask/debughelpers.py+12 added
6 unmodified lines7 8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11+import os12+from warnings import warn13+14 from ._compat import implements_to_string, text_type15 from .app import Flask16 from .blueprints import Blueprint17 from .globals import _request_ctx_stack137 unmodified lines155 info.append(' Maybe you did not place a template in the right folder?')156 info.append(' See http://flask.pocoo.org/docs/blueprints/#templates')157 158 app.logger.info('\n'.join(info))159+160+161+def 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 lines9 :license: BSD, see LICENSE for more details.10 """11 12 import os13+import socket14 import sys15 import pkgutil16 import posixpath17 import mimetypes18 from time import time19 from zlib import adler3220 from threading import RLock21+import unicodedata22 from werkzeug.routing import BuildError23 from functools import update_wrapper24 25 try:33 unmodified lines59 def 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')64 65 66 def _endpoint_from_view_func(view_func):67 """Internal helper that returns the default endpoint for a given263 unmodified lines331 # 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)337 338 if anchor is not None:339 rv += '#' + url_quote(anchor)139 unmodified lines479 480 .. 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-4488 481- :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 fall47 unmodified lines541 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)545 546+ 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}556+557+ headers.add('Content-Disposition', 'attachment', **filenames)558+559 if current_app.use_x_sendfile and filename:560 if file is not None:561 file.close()562 headers['X-Sendfile'] = filename413 unmodified lines976 :returns: number of seconds977 :rtype: int978 """979 return td.days * 60 * 60 * 24 + td.seconds980+981+982+def is_ip(value):983+ """Determine if the given string is an IP address.984+985+ :param value: value to check986+ :type value: str987+988+ :return: True if string is an IP address989+ :rtype: bool990+ """991+992+ 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 True999+1000+ return Falsemodified:flask/json.py+21 added-10 removed
1 # -*- coding: utf-8 -*-2 """3- flask.jsonimpl4- ~~~~~~~~~~~~~~3+ flask.json4+ ~~~~~~~~~~5 6 Implementation helpers for the JSON support in Flask.7 8 :copyright: (c) 2015 by Armin Ronacher.81 unmodified lines90 91 def _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+ )100+101 if not current_app.config['JSON_AS_ASCII']:102 kwargs.setdefault('ensure_ascii', False)103+104 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 line109 110 def _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)121 122 124 unmodified lines247 .. versionchanged:: 0.11248 Added support for serializing top-level arrays. This introduces a249 security risk in ancient browsers. See :ref:`json-security` for details.250 239- 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.255 256 .. versionadded:: 0.2257 """258 259 indent = None260 separators = (',', ':')261 251- 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 = (', ', ': ')265 266 if args and kwargs:14 unmodified linesmodified:flask/sessions.py+69 added-32 removed
9 unmodified lines10 """11 12 import uuid13 import hashlib14+import warnings15 from base64 import b64encode, b64decode16 from datetime import datetime17 from werkzeug.http import http_date, parse_date18 from werkzeug.datastructures import CallbackDict19 from . import Markup, json20 from ._compat import iteritems, text_type20-from .helpers import total_seconds21+from .helpers import total_seconds, is_ip22 23 from itsdangerous import URLSafeTimedSerializer, BadSignature24 25 58 unmodified lines84 85 def dumps(self, value):86 return json.dumps(_tag(value), separators=(',', ':'))87 88+ LOADS_MAP = {89+ ' t': tuple,90+ ' u': uuid.UUID,91+ ' b': b64decode,92+ ' m': Markup,93+ ' d': parse_date,94+ }95+96 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)109 110 61 unmodified lines172 #: this type.173 null_session_class = NullSession174 175 #: 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 = False19 unmodified lines200 """201 return isinstance(obj, self.null_session_class)202 203 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]212 208- # 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']214 214- # 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 None219 222- return rv220+ rv = app.config['SERVER_NAME']221 222+ # server name not set, cache False to return none next time223+ if not rv:224+ app.config['SESSION_COOKIE_DOMAIN'] = False225+ return None226+227+ # 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('.')230+231+ 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 None242+243+ ip = is_ip(rv)244+245+ 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+ )252+253+ # 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 = '.' + rv257+258+ app.config['SESSION_COOKIE_DOMAIN'] = rv259+ return rv260+261 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`` or135 unmodified linesmodified:flask/signals.py+1 added-1 removed
35 unmodified lines36 connect = disconnect = has_receivers_for = receivers_for = \37 temporarily_connected_to = connected_to = _fail38 del _fail39 40-# 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()43 44 12 unmodified linesmodified:flask/testing.py+14 added
8 unmodified lines9 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11 """12 13+import werkzeug14 from contextlib import contextmanager15 from werkzeug.test import Client, EnvironBuilder16 from flask import _request_ctx_stack17 25 unmodified lines43 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`.46 47+ .. 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`.51+52 Basic usage is outlined in the :ref:`testing` chapter.53 """54 55 preserve_context = False56 57+ 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+ }63+64 @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 that45 unmodified lines113 114 def open(self, *args, **kwargs):115 kwargs.setdefault('environ_overrides', {}) \116 ['flask._preserve_context'] = self.preserve_context117+ kwargs.setdefault('environ_base', self.environ_base)118 119 as_tuple = kwargs.pop('as_tuple', False)120 buffered = kwargs.pop('buffered', False)121 follow_redirects = kwargs.pop('follow_redirects', False)22 unmodified linesmodified:flask/views.py+22 added-18 removed
101 unmodified lines102 return view103 104 105 class MethodViewType(type):106+ """Metaclass for :class:`MethodView` that determines what methods the view107+ defines.108+ """109 107- 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)112+113 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()115+116+ 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).119+120+ # 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 = methods126 127 128 class 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. ::132 133 class CounterAPI(MethodView):132-134 def get(self):135 return session.get('counter', 0)136 137 def post(self):1 unmodified line139 return 'OK'140 141 app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))142 """143+144 def dispatch_request(self, *args, **kwargs):145 meth = getattr(self, request.method.lower(), None)146+147 # 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)151+152 assert meth is not None, 'Unimplemented method %r' % request.method153 return meth(*args, **kwargs)modified:flask/wrappers.py+2 added-1 removed
135 unmodified lines136 :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 rv143 144 if not (force or self.is_json):145 return None60 unmodified linesmodified:scripts/flask-07-upgrade.py+1 added-1 removed
3 unmodified lines4 flask-07-upgrade5 ~~~~~~~~~~~~~~~~6 7 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.10 11 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 linesadded:tests/test_apps/cliapp/importerrorapp.py+7 added
1+from __future__ import absolute_import, print_function2+3+from flask import Flask4+5+raise ImportError()6+7+testapp = Flask('testapp')modified:tests/test_basic.py+251 added-48 removed
48 unmodified lines49 rv = app.test_client().open('/', method='OPTIONS')50 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']51 52 53-def test_options_handling_disabled():53+def test_provide_automatic_options_attr():54 app = flask.Flask(__name__)55 56 def index():57 return 'Hello World!'11 unmodified lines69 rv = app.test_client().open('/', method='OPTIONS')70 assert sorted(rv.allow) == ['OPTIONS']71 72 73+def test_provide_automatic_options_kwarg():74+ app = flask.Flask(__name__)75+76+ def index():77+ return flask.request.method78+79+ def more():80+ return flask.request.method81+82+ 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+ )87+88+ c = app.test_client()89+ assert c.get('/').data == b'GET'90+91+ rv = c.post('/')92+ assert rv.status_code == 40593+ assert sorted(rv.allow) == ['GET', 'HEAD']94+95+ # 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')100+101+ assert rv.status_code == 405102+103+ 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'108+109+ rv = c.delete('/more')110+ assert rv.status_code == 405111+ assert sorted(rv.allow) == ['GET', 'HEAD', 'POST']112+113+ if hasattr(c, 'options'):114+ rv = c.options('/more')115+ else:116+ rv = c.open('/more', method='OPTIONS')117+118+ assert rv.status_code == 405119+120+121 def test_request_dispatching():122 app = flask.Flask(__name__)123 124 @app.route('/')225 unmodified lines350 assert 'secure' in cookie351 assert 'httponly' not in cookie352 353 354+def test_session_localhost_warning(recwarn):355+ app = flask.Flask(__name__)356+ app.config.update(357+ SECRET_KEY='testing',358+ SERVER_NAME='localhost:5000',359+ )360+361+ @app.route('/')362+ def index():363+ flask.session['testing'] = 42364+ return 'testing'365+366+ 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)370+371+372+def 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+ )378+379+ @app.route('/')380+ def index():381+ flask.session['testing'] = 42382+ return 'testing'383+384+ 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)388+389+390 def test_missing_session():391 app = flask.Flask(__name__)392 393 def expect_exception(f, *args, **kwargs):22 unmodified lines416 417 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.month449 unmodified lines874 assert resp.mimetype == 'text/x-special'875 assert resp.data == b'internal server error'876 877 878+def test_baseexception_error_handling():879+ app = flask.Flask(__name__)880+ app.config['LOGGER_HANDLER_POLICY'] = 'never'881+882+ @app.route('/')883+ def broken_func():884+ raise KeyboardInterrupt()885+886+ with app.test_client() as c:887+ with pytest.raises(KeyboardInterrupt):888+ c.get('/')889+890+ ctx = flask._request_ctx_stack.top891+ assert ctx.preserved892+ assert type(ctx._preserved_exc) is KeyboardInterrupt893+894+895 def test_before_request_and_routing_errors():896 app = flask.Flask(__name__)897 898 @app.before_request111 unmodified lines1010 assert 'no file contents were transmitted' in str(e.value)1011 assert 'This was submitted: "index.txt"' in str(e.value)1012 1013 913-def test_response_creation():1014+def test_response_types():1015 app = flask.Flask(__name__)1016+ app.testing = True1017 916- @app.route('/unicode')917- def from_unicode():1018+ @app.route('/text')1019+ def from_text():1020 return u'Hällo Wörld'1021 920- @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')1025 924- @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 }1032 931- @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 }1039 938- @app.route('/args_status')939- def from_status_tuple():1040+ @app.route('/text_status')1041+ def from_text_status():1042 return 'Hi, status!', 4001043 942- @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 }1050 1051+ @app.route('/response_status')1052+ def from_response_status():1053+ return app.response_class('Hello world', 400), 5001054+1055+ @app.route('/wsgi')1056+ def from_wsgi():1057+ return NotFound()1058+1059 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')1060+1061+ 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')1063+1064+ 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 == 4041069 1070+ 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'1075 1076+ rv = c.get('/text_status')1077+ assert rv.data == b'Hi, status!'1078+ assert rv.status_code == 4001079+ assert rv.mimetype == 'text/html'1080+1081+ 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 == 4041086+1087+ rv = c.get('/response_status')1088+ assert rv.data == b'Hello world'1089+ assert rv.status_code == 5001090+1091+ rv = c.get('/wsgi')1092+ assert b'Not Found' in rv.data1093+ assert rv.status_code == 4041094+1095+1096+def test_response_type_errors():1097+ app = flask.Flask(__name__)1098+ app.testing = True1099+1100+ @app.route('/none')1101+ def from_none():1102+ pass1103+1104+ @app.route('/small_tuple')1105+ def from_small_tuple():1106+ return 'Hello',1107+1108+ @app.route('/large_tuple')1109+ def from_large_tuple():1110+ return 'Hello', 234, {'X-Foo': 'Bar'}, '???'1111+1112+ @app.route('/bad_type')1113+ def from_bad_type():1114+ return True1115+1116+ @app.route('/bad_wsgi')1117+ def from_bad_wsgi():1118+ return lambda: None1119+1120+ c = app.test_client()1121+1122+ with pytest.raises(TypeError) as e:1123+ c.get('/none')1124+ assert 'returned None' in str(e)1125+1126+ with pytest.raises(TypeError) as e:1127+ c.get('/small_tuple')1128+ assert 'tuple must have the form' in str(e)1129+1130+ pytest.raises(TypeError, c.get, '/large_tuple')1131+1132+ with pytest.raises(TypeError) as e:1133+ c.get('/bad_type')1134+ assert 'it was a bool' in str(e)1135+1136+ pytest.raises(TypeError, c.get, '/bad_wsgi')1137+1138+1139 def test_make_response():1140 app = flask.Flask(__name__)1141 with app.test_request_context():1142 rv = flask.make_response()17 unmodified lines1160 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'1166 1167 rv = flask.make_response(1168 flask.Response(''), 400)110 unmodified lines1279 with app.test_request_context():1280 pytest.raises(BuildError, flask.url_for, 'not.existing')1281 1282 1283+def test_url_for_passes_special_values_to_build_error_handler():1284+ app = flask.Flask(__name__)1285+1286+ @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'1295+1296+ with app.test_request_context():1297+ flask.url_for('/')1298+1299+1300 def test_custom_converters():1301 from werkzeug.routing import BaseConverter1302 1303 class ListConverter(BaseConverter):49 unmodified lines1353 with app.test_request_context():1354 assert flask.url_for('static', filename='index.html') == '/foo/index.html'1355 1356 1174-def test_none_response():1175- app = flask.Flask(__name__)1176- app.testing = True1357+def 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)1374 1178- @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"1375 1189-1376 def test_request_locals():1377 assert repr(flask.g) == '<LocalProxy unbound>'1378 assert not flask.g1379 486 unmodified lines1866 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)1870+1871+1872+@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+))1878+def 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_port1882+1883+ 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 lines354 assert rv.status_code == 404355 rv = c.get('/py/bar/123')356 assert rv.status_code == 404357 358+359+def test_endpoint_decorator():360+ from werkzeug.routing import Rule361+ app = flask.Flask(__name__)362+ app.url_map.add(Rule('/foo', endpoint='bar'))363+364+ bp = flask.Blueprint('bp', __name__)365+366+ @bp.endpoint('bar')367+ def foobar():368+ return flask.request.endpoint369+370+ app.register_blueprint(bp, url_prefix='/bp_prefix')371+372+ c = app.test_client()373+ assert c.get('/foo').data == b'bar'374+ assert c.get('/bp_prefix/bar').status_code == 404375+376+377 def test_template_filter():378 bp = flask.Blueprint('bp', __name__)379 @bp.app_template_filter()380 def my_reverse(s):213 unmodified linesmodified:tests/test_cli.py+85 added-7 removed
12 unmodified lines13 #14 from __future__ import absolute_import, print_function15 import os16 import sys17+from functools import partial18 19 import click20 import pytest21 from click.testing import CliRunner22 from flask import Flask, current_app23 23-from flask.cli import AppGroup, FlaskGroup, NoAppException, ScriptInfo, \24+from 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_version27 28 29+@pytest.fixture30+def runner():31+ return CliRunner()32+33+34 def 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.name50 unmodified lines88 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")93 94 95 def test_find_default_import_path(test_apps, monkeypatch, tmpdir):96 """Test of find_default_import_path."""37 unmodified lines134 assert app.name == "createapp"135 assert obj.load_app() == app136 137 131-def test_with_appcontext():138+def test_with_appcontext(runner):139 """Test of with_appcontext."""140 @click.command()141 @with_appcontext142 def testcmd():143 click.echo(current_app.name)144 145 obj = ScriptInfo(create_app=lambda info: Flask("testapp"))146 140- runner = CliRunner()147 result = runner.invoke(testcmd, obj=obj)148 assert result.exit_code == 0149 assert result.output == 'testapp\n'150 151 146-def test_appgroup():152+def test_appgroup(runner):153 """Test of with_appcontext."""154 @click.group(cls=AppGroup)155 def cli():156 pass11 unmodified lines168 click.echo(current_app.name)169 170 obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))171 166- runner = CliRunner()172 result = runner.invoke(cli, ['test'], obj=obj)173 assert result.exit_code == 0174 assert result.output == 'testappgroup\n'175 1 unmodified line177 assert result.exit_code == 0178 assert result.output == 'testappgroup\n'179 180 176-def test_flaskgroup():181+def test_flaskgroup(runner):182 """Test FlaskGroup."""183 def create_app(info):184 return Flask("flaskgroup")185 4 unmodified lines190 @cli.command()191 def test():192 click.echo(current_app.name)193 189- runner = CliRunner()194 result = runner.invoke(cli, ['test'])195 assert result.exit_code == 0196 assert result.output == 'flaskgroup\n'197+198+199+def 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")204+205+ @click.group(cls=FlaskGroup, create_app=create_app)206+ def cli(**params):207+ pass208+209+ result = runner.invoke(cli, ['--help'])210+ assert result.exit_code == 0211+ assert 'Exception: oh no' in result.output212+ assert 'Traceback' in result.output213+214+215+class TestRoutes:216+ @pytest.fixture217+ def invoke(self, runner):218+ def create_app(info):219+ app = Flask(__name__)220+ app.testing = True221+222+ @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])223+ def yyy_get_post(x, y):224+ pass225+226+ @app.route('/zzz_post', methods=['POST'])227+ def aaa_post():228+ pass229+230+ return app231+232+ cli = FlaskGroup(create_app=create_app)233+ return partial(runner.invoke, cli)234+235+ 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)] == expect240+241+ 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+ )248+249+ 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+ )265+266+ 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 outputmodified:tests/test_config.py+20 added-2 removed
5 unmodified lines6 :copyright: (c) 2015 by the Flask Team, see AUTHORS for more details.7 :license: BSD, see LICENSE for more details.8 """9 10-import pytest10 12-import os11 from datetime import timedelta12+import os13+import textwrap14+15 import flask16+from flask._compat import PY217+import pytest18 19 20 # config keys used for the TestConfig21 TEST_KEY = 'foo'167 unmodified lines189 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']193+194+195+@pytest.mark.parametrize('encoding', ['utf-8', 'iso-8859-15', 'latin-1'])196+def 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 lines178 179 def test_no_error_swallowing(flaskext_broken):180 with pytest.raises(ImportError) as excinfo:181 import flask.ext.broken182-183- 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 linesmodified:tests/test_helpers.py+76 added-17 removed
33 unmodified lines34 35 36 class TestJSON(object):37 38+ 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)45+46 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 lines120 out.seek(0)121 rv = flask.json.load(out)122 assert rv == test_data123 124+ @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) == d129 130+ 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_value135+136 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 lines174 assert flask.json.loads(rv.data) == l175 176 def test_jsonify_date_types(self):177 """Test jsonify with datetime.date and datetime.datetime types."""173-178 test_dates = (179 datetime.datetime(1973, 3, 11, 6, 30, 45),180 datetime.date(1975, 1, 5)181 )178-182 app = flask.Flask(__name__)183 c = app.test_client()184 185 for i, d in enumerate(test_dates):5 unmodified lines191 192 def test_jsonify_uuid_types(self):193 """Test jsonify with uuid.UUID types"""194 192- test_uuid = uuid.UUID(bytes=b'\xDE\xAD\xBE\xEF'*4)193-195+ 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 lines266 'x': {'_foo': 42}267 }), content_type='application/json')268 assert rv.data == b'"<42>"'269 270+ def test_blueprint_json_customization(self):271+ class X(object):272+ def __init__(self, val):273+ self.val = val274+275+ class MyEncoder(flask.json.JSONEncoder):276+ def default(self, o):277+ if isinstance(o, X):278+ return '<%d>' % o.val279+280+ return flask.json.JSONEncoder.default(self, o)281+282+ 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)286+287+ def object_hook(self, obj):288+ if len(obj) == 1 and '_foo' in obj:289+ return X(obj['_foo'])290+291+ return obj292+293+ bp = flask.Blueprint('bp', __name__)294+ bp.json_encoder = MyEncoder295+ bp.json_decoder = MyDecoder296+297+ @bp.route('/bp', methods=['POST'])298+ def index():299+ return flask.json.dumps(flask.request.get_json()['x'])300+301+ app = flask.Flask(__name__)302+ app.testing = True303+ app.register_blueprint(bp)304+305+ 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>"'310+311 def test_modified_url_encoding(self):312 class ModifiedRequest(flask.Request):313 url_charset = 'euc-kr'314 app = flask.Flask(__name__)14 unmodified lines329 330 def test_json_key_sorting(self):331 app = flask.Flask(__name__)332 app.testing = True333+ app.debug = True334+335 assert app.config['JSON_SORT_KEYS'] == True336 d = dict.fromkeys(range(20), 'foo')337 338 @app.route('/')218 unmodified lines557 rv = c.get('/', headers={'Range': 'somethingsomething'})558 assert rv.status_code == 416559 rv.close()560 516- 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)564 565 rv = c.get('/', headers={'Range': 'bytes=4-15',14 unmodified lines580 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()587 588 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 lines601 assert value == 'attachment'602 assert options['filename'] == 'index.txt'603 rv.close()604 605+ def test_attachment_with_utf8_filename(self):606+ app = flask.Flask(__name__)607+608+ 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()617+618 def test_static_file(self):619 app = flask.Flask(__name__)620 # default cache timeout is 12 hours621 with app.test_request_context():323 unmodified linesmodified:tests/test_reqctx.py+25 added
10 unmodified lines11 12 import pytest13 14 import flask15+from flask.sessions import SessionInterface16 17 try:18 from greenlet import greenlet19 except ImportError:173 unmodified lines193 assert rv.data == b'Hello World!'194 195 result = greenlets[0].run()196 assert result == 42197+198+199+def test_session_error_pops_context():200+ class SessionError(Exception):201+ pass202+203+ class FailingSessionInterface(SessionInterface):204+ def open_session(self, app, request):205+ raise SessionError()206+207+ class CustomFlask(flask.Flask):208+ session_interface = FailingSessionInterface()209+210+ app = CustomFlask(__name__)211+212+ @app.route('/')213+ def index():214+ # shouldn't get here215+ assert False216+217+ response = app.test_client().get('/')218+ assert response.status_code == 500219+ assert not flask.request220+ assert not flask.current_appmodified:tests/test_testing.py+35 added
9 unmodified lines10 """11 import pytest12 13 import flask14+import werkzeug15 16 from flask._compat import text_type17 18 24 unmodified lines43 with app.test_client() as c:44 rv = c.get('/')45 assert rv.data == b'http://localhost/'46 47+def 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_addr54+55+ 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__59+60+def 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_addr67+68+ 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'74+75+ 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'80+81 def test_redirect_keep_session():82 app = flask.Flask(__name__)83 app.secret_key = 'testing'84 187 unmodified linesmodified:tests/test_views.py+42 added
158 unmodified lines159 app.add_url_rule('/', view_func=Index.as_view('index'))160 161 # But these tests should still pass. We just log a warning.162 common_test(app)163+164+def test_multiple_inheritance():165+ app = flask.Flask(__name__)166+167+ class GetView(flask.views.MethodView):168+ def get(self):169+ return 'GET'170+171+ class DeleteView(flask.views.MethodView):172+ def delete(self):173+ return 'DELETE'174+175+ class GetDeleteView(GetView, DeleteView):176+ pass177+178+ app.add_url_rule('/', view_func=GetDeleteView.as_view('index'))179+180+ 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']184+185+def test_remove_method_from_parent():186+ app = flask.Flask(__name__)187+188+ class GetView(flask.views.MethodView):189+ def get(self):190+ return 'GET'191+192+ class OtherView(flask.views.MethodView):193+ def post(self):194+ return 'POST'195+196+ class View(GetView, OtherView):197+ methods = ['GET']198+199+ app.add_url_rule('/', view_func=View.as_view('index'))200+201+ 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 lines10 _mailinglist11 .tox12 .cache/13 .idea/14+15+# Coverage reports16+htmlcov17+.coverage18+.coverage.*19+*,covermodified:.travis.yml+5 added-1 removed
6 unmodified lines7 - "pypy"8 - "3.3"9 - "3.4"10 - "3.5"11+ - "3.6"12 13 env:14 - REQUIREMENTS=lowest15 - REQUIREMENTS=lowest-simplejson16 unmodified lines32 - 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-simplejson40 36-41 install:42 - pip install tox43 44 script:15 unmodified linesmodified:AUTHORS+1 added
19 unmodified lines20 - Edmond Burnett21 - Florent Xicluna22 - Georg Brandl23 - Jeff Widman @jeffwidman24+- Joshua Bronson @jab25 - Justin Quick26 - Kenneth Reitz27 - Keyan Pishdadian28 - Marian Sigler10 unmodified linesmodified:CHANGES+67 added
1 unmodified line2 ===============3 4 Here you can see the full list of changes between each Flask release.5 6+Version 0.137+------------8+9+Major release, unreleased10+11+- 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`_)43+44+.. _#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/228253+54+Version 0.12.155+--------------56+57+Bugfix release, released on March 31st 201758+59+- 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.68+69 Version 0.1270 ------------71 72+Released on December 21st 2016, codename Punsch.73+74 - 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 to5 unmodified lines83 - 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``.89 90 Version 0.11.291 --------------92 572 unmodified linesmodified:CONTRIBUTING.rst+31 added-6 removed
26 unmodified lines27 - 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.30 31-- 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.33 34 35 Running the testsuite1 unmodified line37 38 You probably want to set up a `virtualenv39 <https://virtualenv.readthedocs.io/en/latest/index.html>`_.40 41-The minimal requirement for running the testsuite is ``py.test``. You can41+The minimal requirement for running the testsuite is ``pytest``. You can42 install it with::43 44 pip install pytest45 7 unmodified lines53 pip install --editable .54 55 Then you can run the testsuite with::56 57- py.test57+ pytest tests/58 59-With only py.test installed, a large part of the testsuite will get skipped59+With only pytest installed, a large part of the testsuite will get skipped60 though. Whether this is relevant depends on which part of Flask you're working61 on. Travis is set up to run the full testsuite when you submit your pull62 request anyways.63 14 unmodified lines78 pip install pytest-cov79 80 After this has been installed, you can output a report to the command line using this command::81 82- py.test --cov=flask tests/82+ pytest --cov=flask tests/83 84 Generate a HTML report can be done using this command::85 86- py.test --cov-report html --cov=flask tests/86+ pytest --cov-report html --cov=flask tests/87 88 Full docs on ``coverage.py`` are here: https://coverage.readthedocs.io89 90+Caution91+=======92+pushing93+-------94+This 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.95+96+97+cloning98+-------99+The zero-padded file modes files above can cause issues while cloning, too. If you have100+101+::102+103+ [fetch]104+ fsckobjects = true105+106+or107+108+::109+110+ [receive]111+ fsckObjects = true112+113+114+set 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 line2 3 all: clean-pyc test4 5 test:6- pip install -r test-requirements.txt -q7- FLASK_DEBUG= py.test tests examples6+ pip install -r test-requirements.txt7+ tox -e py-release8 9-tox-test:10- tox11-9 audit:10 python setup.py audit11 12 release:29 unmodified linesmodified:README+2 added-2 removed
31 unmodified lines32 ~ Where are the tests?33 34 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:37 38- $ py.test38+ $ pytest39 40 Details on contributing can be found in CONTRIBUTING.rst41 42 ~ Where can I get help?7 unmodified linesmodified:setup.cfg+5 added-2 removed
1 [aliases]2 release = egg_info -RDb ''3 4-[wheel]4+[bdist_wheel]5 universal = 16 7+[metadata]8+license_file = LICENSE9+10 [tool:pytest]8-norecursedirs = .* *.egg *.egg-info env* artwork docs examples11+norecursedirs = .* *.egg *.egg-info env* artwork docsmodified:setup.py+2 added-2 removed
39 unmodified lines40 41 * `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>`_45 46 """47 import re48 import ast9 unmodified lines58 59 setup(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 linesmodified:test-requirements.txt+1 added-1 removed
1-pytest1+toxmodified:tox.ini+9 added-3 removed
1 [tox]2-envlist = {py26,py27,pypy}-{lowest,release,devel}{,-simplejson}, {py33,py34,py35}-{release,devel}{,-simplejson}2+envlist = {py26,py27,pypy}-{lowest,release,devel}{,-simplejson}, {py33,py34,py35,py36}-{release,devel}{,-simplejson}3 4 5 6 [testenv]7+passenv = LANG8+usedevelop=true9 commands =8- py.test []9-10+ # 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 []15 deps=16 pytest17+ pytest-cov18 greenlet19 20 lowest: Werkzeug==0.721 lowest: Jinja2==2.412 unmodified lines