Merge branch 'master' into reload_templates_run_debug
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 1a67e28, 2c97ed9 · Browse files · 167 files·+7490 added−4642 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
167 files+7490 added−4642 removed
- tests:+2733 added−1247 removed
- other:+4757 added−3395 removed
Provenance
- Commit
9e39c50- Tree
ddddd31- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
1a67e28- Parent 2
2c97ed9
167 files changed+7490 added−4642 removed
modified:.github/ISSUE_TEMPLATE.rst+33 added-2 removed
1-The issue tracker is a tool to address bugs.2-Please use the #pocoo IRC channel on freenode or Stack Overflow for questions.1+**This issue tracker is a tool to address bugs in Flask itself.2+Please use the #pocoo IRC channel on freenode or Stack Overflow for general3+questions about using Jinja or issues not related to Jinja.**4+5+If you'd like to report a bug in Flask, fill out the template below. Provide6+any any extra information that may be useful / related to your problem.7+Ideally, create an [MCVE](http://stackoverflow.com/help/mcve), which helps us8+understand the problem and helps check that it is not caused by something in9+your code.10+11+---12+13+### Expected Behavior14+15+Tell us what should happen.16+17+```python18+Paste a minimal example that causes the problem.19+```20+21+### Actual Behavior22+23+Tell us what happens instead.24+25+```pytb26+Paste the full traceback if there was an exception.27+```28+29+### Environment30+31+* Python version:32+* Flask version:33+* Werkzeug version:added:.github/PULL_REQUEST_TEMPLATE.rst+16 added
1+Describe what this patch does to fix the issue.2+3+Link to any relevant issues or pull requests.4+5+<!--6+Commit checklist:7+8+* add tests that fail without the patch9+* ensure all tests pass with ``pytest``10+* add documentation to the relevant docstrings or pages11+* add ``versionadded`` or ``versionchanged`` directives to relevant docstrings12+* add a changelog entry if this patch changes code13+14+Tests, coverage, and docs will be run automatically when you submit the pull15+request, but running them yourself can save time.16+-->added:docs/_static/pycharm-runconfig.pngbinary
A binary file, added.
modified:docs/_templates/sidebarintro.html+4 added-4 removed
123345677 unmodified lines1516171819202119202122<h3>About Flask</h3><p> Flask is a micro webdevelopment framework for Python. You are currently Flask is a micro web development framework for Python. You are currently looking at the documentation of the development version.</p><h3>Other Formats</h3><p>7 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+3 added-1 removed
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 32 .. toctree::33 :maxdepth: 234 33- mod_wsgi35 wsgi-standalone36 uwsgi37+ mod_wsgi38 fastcgi39 cgimodified:docs/deploying/mod_wsgi.rst+6 added-6 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:: apache7 unmodified lines129 130 Require all granted131 132 133-For more information consult the `mod_wsgi wiki`_.133+For more information consult the `mod_wsgi documentation`_.134 135-.. _mod_wsgi: http://code.google.com/p/modwsgi/136-.. _installation instructions: http://code.google.com/p/modwsgi/wiki/QuickInstallationGuide135+.. _mod_wsgi: https://github.com/GrahamDumpleton/mod_wsgi136+.. _installation instructions: https://modwsgi.readthedocs.io/en/develop/installation.html137 .. _virtual python: https://pypi.python.org/pypi/virtualenv138-.. _mod_wsgi wiki: http://code.google.com/p/modwsgi/w/list138+.. _mod_wsgi documentation: https://modwsgi.readthedocs.io/en/develop/index.html139 140 Troubleshooting141 ---------------142 75 unmodified linesmodified:docs/deploying/uwsgi.rst+3 added-3 removed
27 unmodified lines28 Given a flask application in myapp.py, use the following command:29 30 .. sourcecode:: text31 32- $ uwsgi -s /tmp/uwsgi.sock --manage-script-name --mount /yourapplication=myapp:app32+ $ uwsgi -s /tmp/yourapplication.sock --manage-script-name --mount /yourapplication=myapp:app33 34 The ``--manage-script-name`` will move the handling of ``SCRIPT_NAME`` to uwsgi,35 since its smarter about that. It is used together with the ``--mount`` directive36 which will make requests to ``/yourapplication`` be directed to ``myapp:app``.28 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/deploying/wsgi-standalone.rst+16 added
25 unmodified lines26 .. _Gunicorn: http://gunicorn.org/27 .. _eventlet: http://eventlet.net/28 .. _greenlet: https://greenlet.readthedocs.io/en/latest/29 30+uWSGI31+--------32+33+`uWSGI`_ is a fast application server written in C. It is very configurable34+which makes it more complicated to setup than gunicorn.35+36+Running `uWSGI HTTP Router`_::37+38+ uwsgi --http 127.0.0.1:5000 --module myproject:app39+40+For a more optimized setup, see `configuring uWSGI and NGINX`_.41+42+.. _uWSGI: http://uwsgi-docs.readthedocs.io/en/latest/43+.. _uWSGI HTTP Router: http://uwsgi-docs.readthedocs.io/en/latest/HTTP.html#the-uwsgi-http-https-router44+.. _configuring uWSGI and NGINX: uwsgi.html#starting-your-app-with-uwsgi45+46 Gevent47 -------48 49 `Gevent`_ is a coroutine-based Python networking library that uses101 unmodified linesmodified: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/celery.rst+44 added-36 removed
1-Celery Based Background Tasks2-=============================1+Celery Background Tasks2+=======================3 4-Celery is a task queue for Python with batteries included. It used to5-have a Flask integration but it became unnecessary after some6-restructuring of the internals of Celery with Version 3. This guide fills7-in the blanks in how to properly use Celery with Flask but assumes that8-you generally already read the `First Steps with Celery9-<http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html>`_10-guide in the official Celery documentation.4+If your application has a long running task, such as processing some uploaded5+data or sending email, you don't want to wait for it to finish during a6+request. Instead, use a task queue to send the necessary data to another7+process that will run the task in the background while the request returns8+immediately.9 12-Installing Celery13------------------10+Celery is a powerful task queue that can be used for simple background tasks11+as well as complex multi-stage programs and schedules. This guide will show you12+how to configure Celery using Flask, but assumes you've already read the13+`First Steps with Celery <http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html>`_14+guide in the Celery documentation.15 15-Celery is on the Python Package Index (PyPI), so it can be installed with16-standard Python tools like :command:`pip` or :command:`easy_install`::16+Install17+-------18 19+Celery is a separate Python package. Install it from PyPI using pip::20+21 $ pip install celery22 20-Configuring Celery21-------------------23+Configure24+---------25 26 The first thing you need is a Celery instance, this is called the celery27 application. It serves the same purpose as the :class:`~flask.Flask`28 object in Flask, just for Celery. Since this instance is used as the9 unmodified lines38 39 from celery import Celery40 41 def make_celery(app):39- celery = Celery(app.import_name, backend=app.config['CELERY_BACKEND'],40- broker=app.config['CELERY_BROKER_URL'])42+ celery = Celery(43+ app.import_name,44+ backend=app.config['CELERY_RESULT_BACKEND'],45+ broker=app.config['CELERY_BROKER_URL']46+ )47 celery.conf.update(app.config)42- TaskBase = celery.Task43- class ContextTask(TaskBase):44- abstract = True48+49+ class ContextTask(celery.Task):50 def __call__(self, *args, **kwargs):51 with app.app_context():47- return TaskBase.__call__(self, *args, **kwargs)52+ return self.run(*args, **kwargs)53+54 celery.Task = ContextTask55 return celery56 57 The function creates a new Celery object, configures it with the broker58 from the application config, updates the rest of the Celery config from59 the Flask config and then creates a subclass of the task that wraps the60 task execution in an application context.61 56-Minimal Example62+An example task63 ---------------64 59-With what we have above this is the minimal example of using Celery with60-Flask::65+Let's write a task that adds two numbers together and returns the result. We66+configure Celery's broker and backend to use Redis, create a ``celery``67+application using the factor from above, and then use it to define the task. ::68 69 from flask import Flask70 71 flask_app = Flask(__name__)2 unmodified lines74 CELERY_RESULT_BACKEND='redis://localhost:6379'75 )76 celery = make_celery(flask_app)77 71-78 @celery.task()79 def add_together(a, b):80 return a + b81 76-This task can now be called in the background:82+This task can now be called in the background::83 78->>> result = add_together.delay(23, 42)79->>> result.wait()80-6584+ result = add_together.delay(23, 42)85+ result.wait() # 6586 82-Running the Celery Worker83--------------------------87+Run a worker88+------------89 85-Now if you jumped in and already executed the above code you will be86-disappointed to learn that your ``.wait()`` will never actually return.87-That's because you also need to run celery. You can do that by running88-celery as a worker::90+If you jumped in and already executed the above code you will be91+disappointed to learn that ``.wait()`` will never actually return.92+That's because you also need to run a Celery worker to receive and execute the93+task. ::94 95 $ celery -A your_application.celery worker96 97 The ``your_application`` string has to point to your application's package93-or module that creates the `celery` object.98+or module that creates the ``celery`` object.99+100+Now that the worker is running, ``wait`` will return the result once the task101+is finished.modified: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+13 added-15 removed
37 unmodified lines38 39 Basic Setup Script40 ------------------41 42-Because you have Flask running, you have setuptools available on your system anyways.43-Flask already depends upon setuptools. If you do not, fear not, there is a44-script to install it for you: `ez_setup.py`_. Just download and45-run with your Python interpreter.42+Because you have Flask installed, you have setuptools available on your system.43+Flask already depends upon setuptools.44 45 Standard disclaimer applies: :ref:`you better use a virtualenv46 <virtualenv>`.47 16 unmodified lines64 )65 66 Please keep in mind that you have to list subpackages explicitly. If you67 want setuptools to lookup the packages for you automatically, you can use70-the `find_packages` function::68+the ``find_packages`` function::69 70 from setuptools import setup, find_packages71 72 setup(73 ...74 packages=find_packages()75 )76 79-Most parameters to the `setup` function should be self explanatory,80-`include_package_data` and `zip_safe` might not be.81-`include_package_data` tells setuptools to look for a :file:`MANIFEST.in` file77+Most parameters to the ``setup`` function should be self explanatory,78+``include_package_data`` and ``zip_safe`` might not be.79+``include_package_data`` tells setuptools to look for a :file:`MANIFEST.in` file80 and install all the entries that match as package data. We will use this81 to distribute the static files and templates along with the Python module84-(see :ref:`distributing-resources`). The `zip_safe` flag can be used to82+(see :ref:`distributing-resources`). The ``zip_safe`` flag can be used to83 force or prevent zip Archive creation. In general you probably don't want84 your packages to be installed as zip files because some tools do not85 support them and they make debugging a lot harder.86 33 unmodified lines120 recursive-include yourapplication/static *121 122 Don't forget that even if you enlist them in your :file:`MANIFEST.in` file, they123 won't be installed for you unless you set the `include_package_data`126-parameter of the `setup` function to ``True``!124+parameter of the ``setup`` function to ``True``!125 126 127 Declaring Dependencies128 ----------------------129 132-Dependencies are declared in the `install_requires` parameter as a list.130+Dependencies are declared in the ``install_requires`` parameter as a list.131 Each item in that list is the name of a package that should be pulled from132 PyPI on installation. By default it will always use the most recent133 version, but you can also provide minimum and maximum version134 requirements. Here some examples::21 unmodified lines156 Installing / Developing157 -----------------------158 159 To install your application (ideally into a virtualenv) just run the162-:file:`setup.py` script with the `install` parameter. It will install your160+:file:`setup.py` script with the ``install`` parameter. It will install your161 application into the virtualenv's site-packages folder and also download162 and install all dependencies::163 164 $ python setup.py install165 166 If you are developing on the package and also want the requirements to be169-installed, you can use the `develop` command instead::167+installed, you can use the ``develop`` command instead::168 169 $ python setup.py develop170 171 This has the advantage of just installing a link to the site-packages172 folder instead of copying the data over. You can then continue to work on175-the code without having to run `install` again after each change.173+the code without having to run ``install`` again after each change.174 175 176 .. _pip: https://pypi.python.org/pypi/pip179-.. _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+10 added-10 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'])17 unmodified lines46 the file and redirects the user to the URL for the uploaded file::47 48 def allowed_file(filename):49 return '.' in filename and \50- filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS50+ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS51 52 @app.route('/', methods=['GET', 'POST'])53 def upload_file():54 if request.method == 'POST':2 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):4 unmodified lines70 return '''71 <!doctype html>72 <title>Upload new File</title>73 <h1>Upload new File</h1>74- <form action="" method=post enctype=multipart/form-data>75- <p><input type=file name=file>76- <input type=submit value=Upload>74+ <form method=post enctype=multipart/form-data>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?22 unmodified lines103 104 >>> secure_filename('../../../../home/username/.bashrc')105 'home_username_.bashrc'106 107-Now one last thing is missing: the serving of the uploaded files. In the 108-:func:`upload_file()` we redirect the user to 109-``url_for('uploaded_file', filename=filename)``, that is, ``/uploads/filename``. 107+Now one last thing is missing: the serving of the uploaded files. In the108+:func:`upload_file()` we redirect the user to109+``url_for('uploaded_file', filename=filename)``, that is, ``/uploads/filename``.110 So we write the :func:`uploaded_file` function to return the file of that name. As111 of Flask 0.5 we can use a function that does that for us::112 113 from flask import send_from_directory66 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/flashing.rst+1 added-1 removed
76 unmodified lines77 <h1>Login</h1>78 {% if error %}79 <p class=error><strong>Error:</strong> {{ error }}80 {% endif %}81- <form action="" method=post>81+ <form method=post>82 <dl>83 <dt>Username:84 <dd><input type=text name=username value="{{85 request.form.username }}">65 unmodified linesmodified:docs/patterns/lazyloading.rst+10 added-5 removed
88 unmodified lines89 90 You can further optimize this in terms of amount of keystrokes needed to91 write this by having a function that calls into92 :meth:`~flask.Flask.add_url_rule` by prefixing a string with the project93-name and a dot, and by wrapping `view_func` in a `LazyView` as needed::93+name and a dot, and by wrapping `view_func` in a `LazyView` as needed. ::94 95- def url(url_rule, import_name, **options):95+ def url(import_name, url_rules=[], **options):96 view = LazyView('yourapplication.' + import_name)97+ for url_rule in url_rules:97- app.add_url_rule(url_rule, view_func=view, **options)98+ app.add_url_rule(url_rule, view_func=view, **options)99 99- url('/', 'views.index')100- url('/user/<username>', 'views.user')100+ # add a single route to the index view101+ url('views.index', ['/'])102 103+ # add two routes to a single function endpoint104+ url_rules = ['/user/','/user/<username>']105+ url('views.user', url_rules)106+107 One thing to keep in mind is that before and after request handlers have108 to be in a file that is imported upfront to work properly on the first109 request. The same goes for any kind of remaining decorator.modified:docs/patterns/packages.rst+41 added-11 removed
6 unmodified lines7 module. That is quite simple. Imagine a small application looks like8 this::9 10 /yourapplication11- /yourapplication.py11+ yourapplication.py12 /static13- /style.css13+ style.css14 /templates15 layout.html16 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 folder4 unmodified lines32 You should then end up with something like that::33 34 /yourapplication35 /yourapplication32- /__init__.py36+ __init__.py37 /static34- /style.css38+ style.css39 /templates40 layout.html41 index.html42 login.html1 unmodified line44 45 But how do you run your application now? The naive ``python46 yourapplication/__init__.py`` will not work. Let's just say that Python47 does not want modules in packages to be the startup file. But that is not44-a big problem, just add a new file called :file:`runserver.py` next to the inner48+a big problem, just add a new file called :file:`setup.py` next to the inner49 :file:`yourapplication` folder with the following contents::50 47- from yourapplication import app48- app.run(debug=True)51+ from setuptools import setup52 53+ setup(54+ name='yourapplication',55+ packages=['yourapplication'],56+ include_package_data=True,57+ install_requires=[58+ 'flask',59+ ],60+ )61+62+In order to run the application you need to export an environment variable 63+that tells Flask where to find the application instance:: 64+65+ export FLASK_APP=yourapplication66+67+If you are outside of the project directory make sure to provide the exact 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+73+In order to install and run the application you need to issue the following 74+commands::75+76+ pip install -e . 77+ flask run78+79 What did we gain from this? Now we can restructure the application a bit80 into multiple modules. The only thing you have to remember is the81 following quick checklist:82 22 unmodified lines105 106 You should then end up with something like that::107 108 /yourapplication80- /runserver.py109+ setup.py110 /yourapplication82- /__init__.py83- /views.py111+ __init__.py112+ views.py113 /static85- /style.css114+ style.css115 /templates116 layout.html117 index.html118 login.html14 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+25 added-8 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 ``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)79 for idx, value in enumerate(row))80 81 db.row_factory = make_dicts82 82-Or even simpler::83+This will make the sqlite3 module return dicts for this database connection, which are much nicer to deal with. Even more simply, we could place this in ``get_db`` instead::84 85 db.row_factory = sqlite3.Row86 87+This would use Row objects rather than dicts to return the results of queries. These are ``namedtuple`` s, so we can access them either by index or by key. For example, assuming we have a ``sqlite3.Row`` called ``r`` for the rows ``id``, ``FirstName``, ``LastName``, and ``MiddleInitial``::88+89+ >>> # You can get values based on the row's name90+ >>> r['FirstName']91+ John92+ >>> # Or, you can get them based on index93+ >>> r[1]94+ John95+ # Row objects are also iterable:96+ >>> for value in r:97+ ... print(value)98+ 199+ John100+ Doe101+ M102+103 Additionally, it is a good idea to provide a query function that combines104 getting the cursor, executing and fetching the results::88- 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 95-This handy little function, in combination with a row factory, makes 96-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 Injections117-<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+2 added-2 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 80 unmodified lines107 108 .. sourcecode:: html+jinja109 110 {% from "_formhelpers.html" import render_field %}111- <form method=post action="/register">111+ <form method=post>112 <dl>113 {{ render_field(form.username) }}114 {{ render_field(form.email) }}115 {{ render_field(form.password) }}11 unmodified linesmodified:docs/tutorial/css.rst+2 added-2 removed
1 .. _tutorial-css:2 3-Step 7: Adding Style3+Step 8: Adding Style4 ====================5 6 Now that everything else works, it's time to add some style to the7 application. Just create a stylesheet called :file:`style.css` in the8-:file:`static` folder we created before:8+:file:`static` folder:9 10 .. sourcecode:: css11 12 body { font-family: sans-serif; background: #eee; }19 unmodified linesmodified:docs/tutorial/dbcon.rst+15 added-14 removed
1 .. _tutorial-dbcon:2 3-Step 3: Database Connections3+Step 4: Database Connections4 ----------------------------5 6-We have created a function for establishing a database connection with7-`connect_db`, but by itself, that's not particularly useful. Creating and8-closing database connections all the time is very inefficient, so we want9-to keep it around for longer. Because database connections encapsulate a10-transaction, we also need to make sure that only one request at the time11-uses the connection. How can we elegantly do that with Flask?6+Let's continue building our code in the ``flaskr.py`` file.7+(Scroll to the end of the page for more about project layout.)8 13-This is where the application context comes into play, so let's start14-there.9+You currently have a function for establishing a database connection with10+`connect_db`, but by itself, it is not particularly useful. Creating and11+closing database connections all the time is very inefficient, so you will12+need to keep it around for longer. Because database connections13+encapsulate a transaction, you will need to make sure that only one14+request at a time uses the connection. An elegant way to do this is by15+utilizing the *application context*.16 16-Flask provides us with two contexts: the application context and the17-request context. For the time being, all you have to know is that there17+Flask provides two contexts: the *application context* and the18+*request context*. For the time being, all you have to know is that there19 are special variables that use these. For instance, the20 :data:`~flask.request` variable is the request object associated with21 the current request, whereas :data:`~flask.g` is a general purpose21-variable associated with the current application context. We will go into22-the details of this a bit later.22+variable associated with the current application context. The tutorial23+will cover some more details of this later on.24 25 For the time being, all you have to know is that you can store information26 safely on the :data:`~flask.g` object.27 9 unmodified lines37 if not hasattr(g, 'sqlite_db'):38 g.sqlite_db = connect_db()39 return g.sqlite_db40 40-So now we know how to connect, but how do we properly disconnect? For41+Now you know how to connect, but how can you properly disconnect? For42 that, Flask provides us with the :meth:`~flask.Flask.teardown_appcontext`43 decorator. It's executed every time the application context tears down::44 45 @app.teardown_appcontext33 unmodified linesmodified:docs/tutorial/dbinit.rst+29 added-21 removed
1 .. _tutorial-dbinit:2 3-Step 4: Creating The Database3+Step 5: Creating The Database4 =============================5 6 As outlined earlier, Flaskr is a database powered application, and more7 precisely, it is an application powered by a relational database system. Such8 systems need a schema that tells them how to store that information.9 Before starting the server for the first time, it's important to create10 that schema.11 12-Such a schema can be created by piping the ``schema.sql`` file into the13-`sqlite3` command as follows::12+Such a schema could be created by piping the ``schema.sql`` file into the13+``sqlite3`` command as follows::14 15 sqlite3 /tmp/flaskr.db < schema.sql16 17-The downside of this is that it requires the ``sqlite3`` command to be18-installed, which is not necessarily the case on every system. This also19-requires that we provide the path to the database, which can introduce20-errors. It's a good idea to add a function that initializes the database21-for you to the application.17+However, the downside of this is that it requires the ``sqlite3`` command18+to be installed, which is not necessarily the case on every system. This19+also requires that you provide the path to the database, which can introduce20+errors.21 23-To do this, we can create a function and hook it into the :command:`flask`24-command that initializes the database. Let me show you the code first. Just25-add this function below the `connect_db` function in :file:`flaskr.py`::22+Instead of the ``sqlite3`` command above, it's a good idea to add a function23+to our application that initializes the database for you. To do this, you24+can create a function and hook it into a :command:`flask` command that25+initializes the database.26 27+Take a look at the code segment below. A good place to add this function,28+and command, is just below the ``connect_db`` function in :file:`flaskr.py`::29+30 def init_db():31 db = get_db()32+33 with app.open_resource('schema.sql', mode='r') as f:34 db.cursor().executescript(f.read())35+36 db.commit()37 38+39 @app.cli.command('initdb')40 def initdb_command():41 """Initializes the database."""42+43 init_db()37- print 'Initialized the database.'44+ print('Initialized the database.')45 46 The ``app.cli.command()`` decorator registers a new command with the47 :command:`flask` script. When the command executes, Flask will automatically41-create an application context for us bound to the right application.42-Within the function, we can then access :attr:`flask.g` and other things as43-we would expect. When the script ends, the application context tears down48+create an application context which is bound to the right application.49+Within the function, you can then access :attr:`flask.g` and other things as50+you might expect. When the script ends, the application context tears down51 and the database connection is released.52 46-We want to keep an actual function around that initializes the database,53+You will want to keep an actual function around that initializes the database,54 though, so that we can easily create databases in unit tests later on. (For55 more information see :ref:`testing`.)56 57 The :func:`~flask.Flask.open_resource` method of the application object58 is a convenient helper function that will open a resource that the59 application provides. This function opens a file from the resource53-location (your ``flaskr`` folder) and allows you to read from it. We are54-using this here to execute a script on the database connection.60+location (the :file:`flaskr/flaskr` folder) and allows you to read from it.61+It is used in this example to execute a script on the database connection.62 56-The connection object provided by SQLite can give us a cursor object.57-On that cursor, there is a method to execute a complete script. Finally, we63+The connection object provided by SQLite can give you a cursor object.64+On that cursor, there is a method to execute a complete script. Finally, you65 only have to commit the changes. SQLite3 and other transactional66 databases will not commit unless you explicitly tell it to.67 68+Now, in a terminal, from the application root directory :file:`flaskr/` it is61-Now, it is possible to create a database with the :command:`flask` script::69+possible to create a database with the :command:`flask` script::70 71 flask initdb72 Initialized the database.73 7 unmodified linesmodified:docs/tutorial/folders.rst+20 added-12 removed
1 unmodified line2 3 Step 0: Creating The Folders4 ============================5 6-Before we get started, let's create the folders needed for this7-application::6+It is recommended to install your Flask application within a virtualenv. Please7+read the :ref:`installation` section to set up your environment.8 9+Now that you have installed Flask, you will need to create the folders required10+for this tutorial. Your directory structure will look like this::11+12 /flaskr13+ /flaskr10- /static11- /templates14+ /static15+ /templates16 13-The ``flaskr`` folder is not a Python package, but just something where we14-drop our files. Later on, we will put our database schema as well as main15-module into this folder. It is done in the following way. The files inside16-the :file:`static` folder are available to users of the application via HTTP.17-This is the place where CSS and Javascript files go. Inside the18-:file:`templates` folder, Flask will look for `Jinja2`_ templates. The19-templates you create later on in the tutorial will go in this directory.17+The application will be installed and run as Python package. This is the18+recommended way to install and run Flask applications. You will see exactly19+how to run ``flaskr`` later on in this tutorial.20 21-Continue with :ref:`tutorial-schema`.21+For now go ahead and create the applications directory structure. In the next22+few steps you will be creating the database schema as well as the main module.23 24+As a quick side note, the files inside of the :file:`static` folder are25+available to users of the application via HTTP. This is the place where CSS and26+JavaScript files go. Inside the :file:`templates` folder, Flask will look for27+`Jinja2`_ templates. You will see examples of this later on.28+29+For now you should continue with :ref:`tutorial-schema`.30+31 .. _Jinja2: http://jinja.pocoo.org/modified:docs/tutorial/index.rst+10 added-9 removed
1 unmodified line2 3 Tutorial4 ========5 6-You want to develop an application with Python and Flask? Here you have7-the chance to learn by example. In this tutorial, we will create a simple8-microblogging application. It only supports one user that can create9-text-only entries and there are no feeds or comments, but it still10-features everything you need to get started. We will use Flask and SQLite11-as a database (which comes out of the box with Python) so there is nothing12-else you need.6+Learn by example to develop an application with Python and Flask.7 8+In this tutorial, we will create a simple blogging application. It only9+supports one user, only allows text entries, and has no feeds or comments.10+11+While very simple, this example still features everything you need to get12+started. In addition to Flask, we will use SQLite for the database, which is13+built-in to Python, so there is nothing else you need.14+15 If you want the full source code in advance or for comparison, check out16 the `example source`_.17 17-.. _example source:18- https://github.com/pallets/flask/tree/master/examples/flaskr/18+.. _example source: https://github.com/pallets/flask/tree/master/examples/flaskr/19 20 .. toctree::21 :maxdepth: 222 23 introduction24 folders25 schema26 setup27+ packaging28 dbcon29 dbinit30 views31 templates2 unmodified linesmodified:docs/tutorial/introduction.rst+7 added-6 removed
1 unmodified line2 3 Introducing Flaskr4 ==================5 6-We will call our blogging application Flaskr, but feel free to choose your own7-less Web-2.0-ish name ;) Essentially, we want it to do the following things:6+This tutorial will demonstrate a blogging application named Flaskr, but feel7+free to choose your own less Web-2.0-ish name ;) Essentially, it will do the8+following things:9 10 1. Let the user sign in and out with credentials specified in the11 configuration. Only one user is supported.12 2. When the user is logged in, they can add new entries to the page1 unmodified line14 is not sanitized because we trust the user here.15 3. The index page shows all entries so far in reverse chronological order16 (newest on top) and the user can add new ones from there if logged in.17 17-We will be using SQLite3 directly for this application because it's good18-enough for an application of this size. For larger applications, however,18+SQLite3 will be used directly for this application because it's good enough19+for an application of this size. For larger applications, however,20 it makes a lot of sense to use `SQLAlchemy`_, as it handles database21 connections in a more intelligent way, allowing you to target different22 relational databases at once and more. You might also want to consider23 one of the popular NoSQL databases if your data is more suited for those.24 24-Here a screenshot of the final application:25+Here is a screenshot of the final application:26 27 .. image:: ../_static/flaskr.png28 :align: center29 :class: screenshot30 :alt: screenshot of the final application31 32 Continue with :ref:`tutorial-folders`.33 33-.. _SQLAlchemy: http://www.sqlalchemy.org/34+.. _SQLAlchemy: https://www.sqlalchemy.org/added:docs/tutorial/packaging.rst+106 added
1+.. _tutorial-packaging:2+3+Step 3: Installing flaskr as a Package4+======================================5+6+Flask is now shipped with built-in support for `Click`_. Click provides7+Flask with enhanced and extensible command line utilities. Later in this8+tutorial you will see exactly how to extend the ``flask`` command line9+interface (CLI).10+11+A useful pattern to manage a Flask application is to install your app12+following the `Python Packaging Guide`_. Presently this involves13+creating two new files; :file:`setup.py` and :file:`MANIFEST.in` in the14+projects root directory. You also need to add an :file:`__init__.py`15+file to make the :file:`flaskr/flaskr` directory a package. After these16+changes, your code structure should be::17+18+ /flaskr19+ /flaskr20+ __init__.py21+ /static22+ /templates23+ flaskr.py24+ schema.sql25+ setup.py26+ MANIFEST.in27+28+Create the ``setup.py`` file for ``flaskr`` with the following content::29+30+ from setuptools import setup31+32+ setup(33+ name='flaskr',34+ packages=['flaskr'],35+ include_package_data=True,36+ install_requires=[37+ 'flask',38+ ],39+ )40+41+When using setuptools, it is also necessary to specify any special files42+that should be included in your package (in the :file:`MANIFEST.in`).43+In this case, the static and templates directories need to be included,44+as well as the schema.45+46+Create the :file:`MANIFEST.in` and add the following lines::47+48+ graft flaskr/templates49+ graft flaskr/static50+ include flaskr/schema.sql51+52+Next, to simplify locating the application, create the file,53+:file:`flaskr/__init__.py` containing only the following import statement::54+55+ from .flaskr import app56+57+This import statement brings the application instance into the top-level58+of the application package. When it is time to run the application, the59+Flask development server needs the location of the app instance. This60+import statement simplifies the location process. Without the above61+import statement, the export statement a few steps below would need to be62+``export FLASK_APP=flaskr.flaskr``.63+64+At this point you should be able to install the application. As usual, it65+is recommended to install your Flask application within a `virtualenv`_.66+With that said, from the ``flaskr/`` directory, go ahead and install the67+application with::68+69+ pip install --editable .70+71+The above installation command assumes that it is run within the projects72+root directory, ``flaskr/``. The ``editable`` flag allows editing73+source code without having to reinstall the Flask app each time you make74+changes. The flaskr app is now installed in your virtualenv (see output75+of ``pip freeze``).76+77+With that out of the way, you should be able to start up the application.78+Do this on Mac or Linux with the following commands in ``flaskr/``::79+80+ export FLASK_APP=flaskr81+ export FLASK_DEBUG=true82+ flask run83+84+(In case you are on Windows you need to use ``set`` instead of ``export``).85+The :envvar:`FLASK_DEBUG` flag enables or disables the interactive debugger.86+*Never leave debug mode activated in a production system*, because it will87+allow users to execute code on the server!88+89+You will see a message telling you that server has started along with90+the address at which you can access it in a browser.91+92+When you head over to the server in your browser, you will get a 404 error93+because we don't have any views yet. That will be addressed a little later,94+but first, you should get the database working.95+96+.. admonition:: Externally Visible Server97+98+ Want your server to be publicly available? Check out the99+ :ref:`externally visible server <public-server>` section for more100+ information.101+102+Continue with :ref:`tutorial-dbcon`.103+104+.. _Click: http://click.pocoo.org105+.. _Python Packaging Guide: https://packaging.python.org106+.. _virtualenv: https://virtualenv.pypa.iomodified:docs/tutorial/schema.rst+5 added-5 removed
1 unmodified line2 3 Step 1: Database Schema4 =======================5 6-First, we want to create the database schema. Only a single table is needed7-for this application and we only want to support SQLite, so creating the8-database schema is quite easy. Just put the following contents into a file9-named `schema.sql` in the just created `flaskr` folder:6+In this step, you will create the database schema. Only a single table is7+needed for this application and it will only support SQLite. All you need to do8+is put the following contents into a file named :file:`schema.sql` in the9+:file:`flaskr/flaskr` folder:10 11 .. sourcecode:: sql12 13 drop table if exists entries;2 unmodified lines16 title text not null,17 'text' text not null18 );19 20-This schema consists of a single table called ``entries``. Each row in20+This schema consists of a single table called ``entries``. Each row in21 this table has an ``id``, a ``title``, and a ``text``. The ``id`` is an22 automatically incrementing integer and a primary key, the other two are23 strings that must not be null.24 1 unmodified linemodified:docs/tutorial/setup.rst+41 added-58 removed
1 unmodified line2 3 Step 2: Application Setup Code4 ==============================5 6-Now that we have the schema in place, we can create the application module.7-Let's call it ``flaskr.py``. We will place this file inside the ``flaskr``8-folder. We will begin by adding the imports we need and by adding the config9-section. For small applications, it is possible to drop the configuration10-directly into the module, and this is what we will be doing here. However,11-a cleaner solution would be to create a separate ``.ini`` or ``.py`` file,12-load that, and import the values from there.6+Next, we will create the application module, :file:`flaskr.py`. Just like the7+:file:`schema.sql` file you created in the previous step, this file should be8+placed inside of the :file:`flaskr/flaskr` folder.9 14-First, we add the imports in :file:`flaskr.py`::10+For this tutorial, all the Python code we use will be put into this file11+(except for one line in ``__init__.py``, and any testing or optional files you12+decide to create).13 16- # all the imports14+The first several lines of code in the application module are the needed import15+statements. After that there will be a few lines of configuration code.16+17+For small applications like ``flaskr``, it is possible to drop the configuration18+directly into the module. However, a cleaner solution is to create a separate19+``.py`` file, load that, and import the values from there.20+21+Here are the import statements (in :file:`flaskr.py`)::22+23 import os24 import sqlite319- from flask import Flask, request, session, g, redirect, url_for, abort, \20- render_template, flash25 22-Next, we can create our actual application and initialize it with the23-config from the same file in :file:`flaskr.py`::26+ from flask import (Flask, request, session, g, redirect, url_for, abort,27+ render_template, flash)28 25- # create our little application :)26- app = Flask(__name__)27- app.config.from_object(__name__)29+The next couple lines will create the actual application instance and30+initialize it with the config from the same file in :file:`flaskr.py`::31 32+ app = Flask(__name__) # create the application instance :)33+ app.config.from_object(__name__) # load config from this file , flaskr.py34+35 # Load default config and override config from an environment variable36 app.config.update(dict(37 DATABASE=os.path.join(app.root_path, 'flaskr.db'),38 SECRET_KEY='development key',1 unmodified line40 PASSWORD='default'41 ))42 app.config.from_envvar('FLASKR_SETTINGS', silent=True)43 38-The :class:`~flask.Config` object works similarly to a dictionary so we39-can update it with new values.44+In the above code, the :class:`~flask.Config` object works similarly to a45+dictionary, so it can be updated with new values.46 47 .. admonition:: Database Path48 49 Operating systems know the concept of a current working directory for10 unmodified lines60 :ref:`instance-folders` instead.61 62 Usually, it is a good idea to load a separate, environment-specific63 configuration file. Flask allows you to import multiple configurations and it58-will use the setting defined in the last import. This enables robust59-configuration setups. :meth:`~flask.Config.from_envvar` can help achieve this.64+will use the setting defined in the last import. This enables robust65+configuration setups. :meth:`~flask.Config.from_envvar` can help achieve66+this. ::67 61-.. code-block:: python62-68 app.config.from_envvar('FLASKR_SETTINGS', silent=True)69 65-Simply define the environment variable :envvar:`FLASKR_SETTINGS` that points to66-a config file to be loaded. The silent switch just tells Flask to not complain67-if no such environment key is set.70+If you want to do this (not required for this tutorial) simply define the71+environment variable :envvar:`FLASKR_SETTINGS` that points to a config file72+to be loaded. The silent switch just tells Flask to not complain if no such73+environment key is set.74 75 In addition to that, you can use the :meth:`~flask.Config.from_object`76 method on the config object and provide it with an import name of a77 module. Flask will then initialize the variable from that module. Note1 unmodified line79 80 The ``SECRET_KEY`` is needed to keep the client-side sessions secure.81 Choose that key wisely and as hard to guess and complex as possible.82 77-We will also add a method that allows for easy connections to the78-specified database. This can be used to open a connection on request and79-also from the interactive Python shell or a script. This will come in80-handy later. We create a simple database connection through SQLite and81-then tell it to use the :class:`sqlite3.Row` object to represent rows.82-This allows us to treat the rows as if they were dictionaries instead of83-tuples.83+Lastly, add a method that allows for easy connections to the specified84+database. ::85 85-::86-86 def connect_db():87 """Connects to the specific database."""88+89 rv = sqlite3.connect(app.config['DATABASE'])90 rv.row_factory = sqlite3.Row91 return rv92 93-With that out of the way, you should be able to start up the application94-without problems. Do this with the following commands::93+This can be used to open a connection on request and also from the94+interactive Python shell or a script. This will come in handy later.95+You can create a simple database connection through SQLite and then tell96+it to use the :class:`sqlite3.Row` object to represent rows. This allows97+the rows to be treated as if they were dictionaries instead of tuples.98 96- export FLASK_APP=flaskr97- export FLASK_DEBUG=198- flask run99+In the next section you will see how to run the application.100 100-(In case you are on Windows you need to use `set` instead of `export`).101-The :envvar:`FLASK_DEBUG` flag enables or disables the interactive debugger.102-*Never leave debug mode activated in a production system*, because it will103-allow users to execute code on the server!104-105-You will see a message telling you that server has started along with106-the address at which you can access it.107-108-When you head over to the server in your browser, you will get a 404 error109-because we don't have any views yet. We will focus on that a little later,110-but first, we should get the database working.111-112-.. admonition:: Externally Visible Server113-114- Want your server to be publicly available? Check out the115- :ref:`externally visible server <public-server>` section for more116- information.117-118-Continue with :ref:`tutorial-dbcon`.101+Continue with :ref:`tutorial-packaging`.modified:docs/tutorial/templates.rst+12 added-10 removed
1 .. _tutorial-templates:2 3-Step 6: The Templates3+Step 7: The Templates4 =====================5 6-Now we should start working on the templates. If we were to request the URLs7-now, we would only get an exception that Flask cannot find the templates. The8-templates are using `Jinja2`_ syntax and have autoescaping enabled by6+Now it is time to start working on the templates. As you may have7+noticed, if you make requests with the app running, you will get8+an exception that Flask cannot find the templates. The templates9+are using `Jinja2`_ syntax and have autoescaping enabled by10 default. This means that unless you mark a value in the code with11 :class:`~flask.Markup` or with the ``|safe`` filter in the template,12 Jinja2 will ensure that special characters such as ``<`` or ``>`` are13 escaped with their XML equivalents.14 15 We are also using template inheritance which makes it possible to reuse16 the layout of the website in all pages.17 17-Put the following templates into the :file:`templates` folder:18+Create the follwing three HTML files and place them in the19+:file:`templates` folder:20 21 .. _Jinja2: http://jinja.pocoo.org/docs/templates22 23 layout.html34 unmodified lines58 -----------------59 60 This template extends the :file:`layout.html` template from above to display the61 messages. Note that the ``for`` loop iterates over the messages we passed60-in with the :func:`~flask.render_template` function. We also tell the61-form to submit to your `add_entry` function and use ``POST`` as HTTP62-method:62+in with the :func:`~flask.render_template` function. Notice that the form is63+configured to submit to the `add_entry` view function and use ``POST`` as64+HTTP method:65 66 .. sourcecode:: html+jinja67 68 {% extends "layout.html" %}10 unmodified lines79 </form>80 {% endif %}81 <ul class=entries>82 {% for entry in entries %}81- <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}83+ <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}</li>84 {% else %}83- <li><em>Unbelievable. No entries here so far</em>85+ <li><em>Unbelievable. No entries here so far</em></li>86 {% endfor %}87 </ul>88 {% endblock %}89 24 unmodified linesmodified:docs/tutorial/testing.rst+86 added
6 unmodified lines7 expected, it's probably not a bad idea to add automated tests to simplify8 modifications in the future. The application above is used as a basic9 example of how to perform unit testing in the :ref:`testing` section of the10 documentation. Go there to see how easy it is to test Flask applications.11+12+Adding tests to flaskr13+----------------------14+15+Assuming you have seen the :ref:`testing` section and have either written16+your own tests for ``flaskr`` or have followed along with the examples17+provided, you might be wondering about ways to organize the project.18+19+One possible and recommended project structure is::20+21+ flaskr/22+ flaskr/23+ __init__.py24+ static/25+ templates/26+ tests/27+ test_flaskr.py28+ setup.py29+ MANIFEST.in30+31+For now go ahead a create the :file:`tests/` directory as well as the 32+:file:`test_flaskr.py` file.33+34+Running the tests35+-----------------36+37+At this point you can run the tests. Here ``pytest`` will be used. 38+39+.. note:: Make sure that ``pytest`` is installed in the same virtualenv 40+ as flaskr. Otherwise ``pytest`` test will not be able to import the 41+ required components to test the application::42+43+ pip install -e .44+ pip install pytest 45+46+Run and watch the tests pass, within the top-level :file:`flaskr/` 47+directory as::48+49+ pytest50+51+Testing + setuptools52+--------------------53+54+One way to handle testing is to integrate it with ``setuptools``. Here55+that requires adding a couple of lines to the :file:`setup.py` file and56+creating a new file :file:`setup.cfg`. One benefit of running the tests 57+this way is that you do not have to install ``pytest``. Go ahead and 58+update the :file:`setup.py` file to contain::59+60+ from setuptools import setup61+62+ setup(63+ name='flaskr',64+ packages=['flaskr'],65+ include_package_data=True,66+ install_requires=[67+ 'flask',68+ ],69+ setup_requires=[70+ 'pytest-runner',71+ ],72+ tests_require=[73+ 'pytest',74+ ],75+ )76+77+Now create :file:`setup.cfg` in the project root (alongside78+:file:`setup.py`)::79+80+ [aliases]81+ test=pytest82+83+Now you can run::84+85+ python setup.py test86+87+This calls on the alias created in :file:`setup.cfg` which in turn runs88+``pytest`` via ``pytest-runner``, as the :file:`setup.py` script has89+been called. (Recall the `setup_requires` argument in :file:`setup.py`)90+Following the standard rules of test-discovery your tests will be91+found, run, and hopefully pass.92+93+This is one possible way to run and manage testing. Here ``pytest`` is94+used, but there are other options such as ``nose``. Integrating testing95+with ``setuptools`` is convenient because it is not necessary to actually96+download ``pytest`` or any other testing framework one might use.modified:docs/tutorial/views.rst+20 added-19 removed
1 .. _tutorial-views:2 3-Step 5: The View Functions3+Step 6: The View Functions4 ==========================5 6-Now that the database connections are working, we can start writing the7-view functions. We will need four of them:6+Now that the database connections are working, you can start writing the7+view functions. You will need four of them; Show Entries, Add New Entry,8+Login and Logout. Add the following code snipets to :file:`flaskr.py`.9 10 Show Entries11 ------------12 17 unmodified lines30 -------------31 32 This view lets the user add new entries if they are logged in. This only33 responds to ``POST`` requests; the actual form is shown on the33-`show_entries` page. If everything worked out well, we will34+`show_entries` page. If everything worked out well, it will35 :func:`~flask.flash` an information message to the next request and36 redirect back to the `show_entries` page::37 38 @app.route('/add', methods=['POST'])6 unmodified lines45 db.commit()46 flash('New entry was successfully posted')47 return redirect(url_for('show_entries'))48 48-Note that we check that the user is logged in here (the `logged_in` key is49-present in the session and ``True``).49+Note that this view checks that the user is logged in (that is, if the50+`logged_in` key is present in the session and ``True``).51 52 .. admonition:: Security Note53 54 Be sure to use question marks when building SQL statements, as done in the26 unmodified lines81 return redirect(url_for('show_entries'))82 return render_template('login.html', error=error)83 84 The `logout` function, on the other hand, removes that key from the session84-again. We use a neat trick here: if you use the :meth:`~dict.pop` method85+again. There is a neat trick here: if you use the :meth:`~dict.pop` method86 of the dict and pass a second parameter to it (the default), the method87 will delete the key from the dictionary if present or do nothing when that87-key is not in there. This is helpful because now we don't have to check88-if the user was logged in.88+key is not in there. This is helpful because now it is not necessary to89+check if the user was logged in.90 91 ::92 93 @app.route('/logout')3 unmodified lines97 return redirect(url_for('show_entries'))98 99 .. admonition:: Security Note100 100- Passwords should never be stored in plain text in a production 101- system. This tutorial uses plain text passwords for simplicity. If you 102- plan to release a project based off this tutorial out into the world, 103- passwords should be both `hashed and salted`_ before being stored in a 104- database or file. 101+ Passwords should never be stored in plain text in a production102+ system. This tutorial uses plain text passwords for simplicity. If you103+ plan to release a project based off this tutorial out into the world,104+ passwords should be both `hashed and salted`_ before being stored in a105+ database or file.106 106- Fortunately, there are Flask extensions for the purpose of 107- hashing passwords and verifying passwords against hashes, so adding 108- this functionality is fairly straight forward. There are also 107+ Fortunately, there are Flask extensions for the purpose of108+ hashing passwords and verifying passwords against hashes, so adding109+ this functionality is fairly straight forward. There are also110 many general python libraries that can be used for hashing.111 111- You can find a list of recommended Flask extensions 112+ You can find a list of recommended Flask extensions113 `here <http://flask.pocoo.org/extensions/>`_114 115 116 Continue with :ref:`tutorial-templates`.117 117-.. _hashed and salted: https://blog.codinghorror.com/youre-probably-storing-passwords-incorrectly/118+.. _hashed and salted: https://blog.codinghorror.com/youre-probably-storing-passwords-incorrectly/deleted:docs/_themesnot shown
Its text is not shown, deleted.
modified:docs/api.rst+7 added-78 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 you9 unmodified lines84 Response Objects85 ----------------86 87 .. autoclass:: flask.Response144- :members: set_cookie, data, mimetype88+ :members: set_cookie, data, mimetype, is_json, get_json89 90 .. attribute:: headers91 92 A :class:`~werkzeug.datastructures.Headers` object representing the response headers.77 unmodified lines170 171 .. autoclass:: SessionMixin172 :members:173 230-.. autodata:: session_json_serializer231-232- This object provides dumping and loading methods similar to simplejson233- but it also tags certain builtin Python objects that commonly appear in234- sessions. Currently the following extended values are supported in235- the JSON it dumps:236-237- - :class:`~markupsafe.Markup` objects238- - :class:`~uuid.UUID` objects239- - :class:`~datetime.datetime` objects240- - :class:`tuple`\s241-174 .. admonition:: Notice175 176 The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer177 starting with Flask 0.8. Either catch this down yourself or use69 unmodified lines247 .. autofunction:: has_app_context248 249 .. autofunction:: url_for250 319-.. function:: abort(code)251+.. autofunction:: abort252 321- Raises an :exc:`~werkzeug.exceptions.HTTPException` for the given322- status code. For example to abort request handling with a page not323- found exception, you would call ``abort(404)``.324-325- :param code: the HTTP error code.326-253 .. autofunction:: redirect254 255 .. autofunction:: make_response256 84 unmodified lines341 342 .. autoclass:: JSONDecoder343 :members:344 345+.. automodule:: flask.json.tag346+347 Template Rendering348 ------------------349 350 .. currentmodule:: flask287 unmodified lines638 639 640 .. _blinker: https://pypi.python.org/pypi/blinker641 642+.. _class-based-views:643 644 Class-Based Views645 -----------------646 180 unmodified linesmodified:docs/appcontext.rst+30 added-24 removed
3 unmodified lines4 =======================5 6 .. versionadded:: 0.97 8-One of the design ideas behind Flask is that there are two different9-“states” in which code is executed. The application setup state in which10-the application implicitly is on the module level. It starts when the11-:class:`Flask` object is instantiated, and it implicitly ends when the12-first request comes in. While the application is in this state a few13-assumptions are true:8+One of the design ideas behind Flask is that there are at least two9+different “states” in which code is executed:10 15-- the programmer can modify the application object safely.16-- no request handling happened so far17-- you have to have a reference to the application object in order to18- modify it, there is no magic proxy that can give you a reference to19- the application object you're currently creating or modifying.11+1. The application setup state, in which the application implicitly is12+on the module level.13 21-In contrast, during request handling, a couple of other rules exist:14+ This state starts when the :class:`Flask` object is instantiated, and15+ it implicitly ends when the first request comes in. While the16+ application is in this state, a few assumptions are true:17 23-- while a request is active, the context local objects24- (:data:`flask.request` and others) point to the current request.25-- any code can get hold of these objects at any time.18+ - the programmer can modify the application object safely.19+ - no request handling happened so far20+ - you have to have a reference to the application object in order to21+ modify it, there is no magic proxy that can give you a reference to22+ the application object you're currently creating or modifying.23 27-There is a third state which is sitting in between a little bit.28-Sometimes you are dealing with an application in a way that is similar to29-how you interact with applications during request handling; just that there30-is no request active. Consider, for instance, that you're sitting in an31-interactive Python shell and interacting with the application, or a32-command line application.24+2. In contrast, in the request handling state, a couple of other rules25+exist:26 27+ - while a request is active, the context local objects28+ (:data:`flask.request` and others) point to the current request.29+ - any code can get hold of these objects at any time.30+31+3. There is also a third state somewhere in between 'module-level' and32+'request-handling':33+34+ Sometimes you are dealing with an application in a way that is similar to35+ how you interact with applications during request handling, but without36+ there being an active request. Consider, for instance, that you're37+ sitting in an interactive Python shell and interacting with the38+ application, or a command line application.39+40 The application context is what powers the :data:`~flask.current_app`41 context local.42 43 Purpose of the Application Context35 unmodified lines79 The application context is also used by the :func:`~flask.url_for`80 function in case a ``SERVER_NAME`` was configured. This allows you to81 generate URLs even in the absence of a request.82 77-If no request context has been pushed and an application context has 78-not been explicitly set, a ``RuntimeError`` will be raised.79-::83+If no request context has been pushed and an application context has84+not been explicitly set, a ``RuntimeError`` will be raised. ::85+86 RuntimeError: Working outside of application context.87 88 Locality of the Context89 -----------------------55 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+64 added-11 removed
30 unmodified lines31 Python module that contains a Flask application.32 33 In that imported file the name of the app needs to be called ``app`` or34 optionally be specified after a colon. For instance35-`mymodule:application` would tell it to use the `application` object in35+``mymodule:application`` would tell it to use the `application` object in36 the :file:`mymodule.py` file.37 38 Given a :file:`hello.py` file with the application in it named ``app``39 this is how it can be run.15 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 mode of the application automatically by exporting ``FLASK_DEBUG``. If64-set to ``1`` debug is enabled or ``0`` disables it.76+set to ``1`` debug is enabled or ``0`` disables it::77 66-Or with a filename::67-78 export FLASK_DEBUG=179 80 Running a Shell81 ---------------68 unmodified lines150 import os151 from yourapplication import create_app152 app = create_app(os.environ['YOURAPPLICATION_CONFIG'])153 144-Once this has happened you can make the flask command automatically pick145-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 67 unmodified lines227 228 CLI Plugins229 -----------230 221-Flask extensions can always patch the `Flask.cli` instance with more231+Flask extensions can always patch the :attr:`Flask.cli` instance with more232 commands if they want. However there is a second way to add CLI plugins223-to Flask which is through `setuptools`. If you make a Python package that224-should export a Flask command line plugin you can ship a `setup.py` file233+to Flask which is through ``setuptools``. If you make a Python package that234+should export a Flask command line plugin you can ship a :file:`setup.py` file235 that declares an entrypoint that points to a click command:236 227-Example `setup.py`::237+Example :file:`setup.py`::238 239 from setuptools import setup240 241 setup(4 unmodified lines246 my-command=mypackage.commands:cli247 ''',248 )249 240-Inside `mypackage/commands.py` you can then export a Click object::250+Inside :file:`mypackage/commands.py` you can then export a Click object::251 252 import click253 254 @click.command()2 unmodified lines257 258 Once that package is installed in the same virtualenv as Flask itself you259 can run ``flask my-command`` to invoke your command. This is useful to260 provide extra functionality that Flask itself cannot ship.261+262+PyCharm Integration263+-------------------264+265+The new Flask CLI features aren’t yet fully integrated into the PyCharm IDE,266+so we have to do a few tweaks to get them working smoothly.267+268+In your PyCharm application, with your project open, click on *Run*269+from the menu bar and go to *Edit Configurations*. You’ll be greeted by a270+screen similar to this:271+272+.. image:: _static/pycharm-runconfig.png273+ :align: center274+ :class: screenshot275+ :alt: screenshot of pycharm's run configuration settings276+277+There’s quite a few options to change, but don’t worry— once we’ve done it278+for one command, we can easily copy the entire configuration and make a279+single tweak to give us access to other flask cli commands, including280+any custom ones you may implement yourself.281+282+For the *Script* input (**A**), we want to navigate to the virtual environment283+we’re using for our project and within that folder we want to pick the ``flask``284+file which will reside in the ``bin`` folder, or in the ``Scripts`` folder if285+you're on Windows.286+287+The *Script Parameter* field (**B**) is set to the cli command you wish to288+execute, in this example we use ``run`` which will run our development server.289+290+We need to add an environment variable (**C**) to identify our application.291+Click on the browse button and add an entry with ``FLASK_APP`` on the292+left and the name of the python file, or package on the right293+(``app.py`` for example).294+295+Next we need to set the working directory (**D**) to be the same folder where296+our application file or package resides.297+298+Finally, untick the *PYTHONPATH* options (**E**) and give the configuration a299+good descriptive name, such as “Run Flask Server” and click *Apply*.300+301+Now that we have on run configuration which implements ``flask run`` from within302+PyCharm, we can simply copy that configuration and alter the script argument303+to run a different cli command, e.g. ``flask shell``.modified:docs/conf.py+51 added-47 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-import sys, os14+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.19-sys.path.append(os.path.abspath('_themes'))20-sys.path.append(os.path.abspath('.'))25+sys.path.append(os.path.dirname(__file__))26 27 # -- General configuration -----------------------------------------------------28 29 # If your documentation needs a minimal Sphinx version, state it here.6 unmodified lines36 'sphinx.ext.intersphinx',37 'flaskdocext'38 ]39 40+try:41+ __import__('sphinxcontrib.log_cabinet')42+except ImportError:43+ print('sphinxcontrib-log-cabinet is not installed.')44+ print('Changelog directives will not be re-organized.')45+else:46+ extensions.append('sphinxcontrib.log_cabinet')47+48 # Add any paths that contain templates here, relative to this directory.49 templates_path = ['_templates']50 51 # The suffix of source filenames.6 unmodified lines58 master_doc = 'index'59 60 # General information about the project.61 project = u'Flask'49-copyright = u'2015, Armin Ronacher'62+copyright = u'2010 - {0}, Armin Ronacher'.format(BUILD_DATE.year)63 64 # The version info for the project you're documenting, acts as replacement for65 # |version| and |release|, also used in various other places throughout the66 # built documents.54-import pkg_resources67 try:68 release = pkg_resources.get_distribution('Flask').version69 except pkg_resources.DistributionNotFound:70 print('Flask must be installed to build the documentation.')71 print('Install from source using `pip install -e .` in a virtualenv.')72 sys.exit(1)61-del pkg_resources73 74 if 'dev' in release:64- release = release.split('dev')[0] + 'dev'75+ release = ''.join(release.partition('dev')[:2])76+77 version = '.'.join(release.split('.')[:2])78 79 # The language for content autogenerated by Sphinx. Refer to documentation80 # for a list of supported languages.30 unmodified lines111 # -- Options for HTML output ---------------------------------------------------112 113 # The theme to use for HTML and HTML Help pages. Major themes that come with114 # Sphinx are currently 'default' and 'sphinxdoc'.103-html_theme = 'flask'115+# html_theme = 'default'116 117 # Theme options are theme-specific and customize the look and feel of a theme118 # further. For a list of options available for each theme, see the119 # documentation.108-html_theme_options = {109- 'touch_icon': 'touch-icon.png'110-}120+# html_theme_options = {}121 122 # Add any paths that contain custom themes here, relative to this directory.113-html_theme_path = ['_themes']123+# html_theme_path = ['_themes']124 125 # The name for this set of Sphinx documents. If None, it defaults to126 # "<project> v<release> documentation".127 #html_title = None7 unmodified lines135 136 # The name of an image file (within the static path) to use as favicon of the137 # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32138 # pixels large.129-html_favicon = "flask-favicon.ico"139+html_favicon = '_static/flask-favicon.ico'140 141 # Add any paths that contain custom static files (such as style sheets) here,142 # relative to this directory. They are copied after the builtin static files,143 # so a file named "default.css" will overwrite the builtin "default.css".8 unmodified lines152 #html_use_smartypants = True153 154 # Custom sidebar templates, maps document names to template names.155 html_sidebars = {146- 'index': ['sidebarintro.html', 'sourcelink.html', 'searchbox.html'],147- '**': ['sidebarlogo.html', 'localtoc.html', 'relations.html',148- 'sourcelink.html', 'searchbox.html']156+ 'index': [157+ 'sidebarintro.html',158+ 'sourcelink.html',159+ 'searchbox.html'160+ ],161+ '**': [162+ 'sidebarlogo.html',163+ 'localtoc.html',164+ 'relations.html',165+ 'sourcelink.html',166+ 'searchbox.html'167+ ]168 }169 170 # Additional templates that should be rendered to pages, maps page names to171 # template names.33 unmodified lines205 206 # Grouping the document tree into LaTeX files. List of tuples207 # (source start file, target name, title, author, documentclass [howto/manual]).208 latex_documents = [190- ('latexindex', 'Flask.tex', u'Flask Documentation',191- u'Armin Ronacher', 'manual'),209+ ('latexindex', 'Flask.tex', u'Flask Documentation', u'Armin Ronacher', 'manual'),210 ]211 212 # Documents to append as an appendix to all manuals.213 #latex_appendices = []1 unmodified line215 # If false, no module index is generated.216 latex_use_modindex = False217 218 latex_elements = {201- 'fontpkg': r'\usepackage{mathpazo}',202- 'papersize': 'a4paper',203- 'pointsize': '12pt',204- 'preamble': r'\usepackage{flaskstyle}'219+ 'fontpkg': r'\usepackage{mathpazo}',220+ 'papersize': 'a4paper',221+ 'pointsize': '12pt',222+ 'preamble': r'\usepackage{flaskstyle}'223 }224 latex_use_parts = True225 226 latex_additional_files = ['flaskstyle.sty', 'logo.pdf']13 unmodified lines240 241 # The scheme of the identifier. Typical schemes are ISBN or URL.242 #epub_scheme = ''243 226-# The unique identifier of the text. This can be a ISBN number244+# The unique identifier of the text. This can be an ISBN number245 # or the project homepage.246 #epub_identifier = ''247 248 # A unique identification for the text.13 unmodified lines262 # The depth of the table of contents in toc.ncx.263 #epub_tocdepth = 3264 265 intersphinx_mapping = {248- 'https://docs.python.org/dev': None,249- 'http://werkzeug.pocoo.org/docs/': None,250- 'http://click.pocoo.org/': None,251- 'http://jinja.pocoo.org/docs/': None,252- 'http://www.sqlalchemy.org/docs/': None,253- 'https://wtforms.readthedocs.io/en/latest/': None,254- 'https://pythonhosted.org/blinker/': None266+ 'python': ('https://docs.python.org/3/', None),267+ 'werkzeug': ('http://werkzeug.pocoo.org/docs/', None),268+ 'click': ('http://click.pocoo.org/', None),269+ 'jinja': ('http://jinja.pocoo.org/docs/', None),270+ 'sqlalchemy': ('https://docs.sqlalchemy.org/en/latest/', None),271+ 'wtforms': ('https://wtforms.readthedocs.io/en/latest/', None),272+ 'blinker': ('https://pythonhosted.org/blinker/', None)273 }274 257-pygments_style = 'flask_theme_support.FlaskyStyle'275+html_theme_options = {276+ 'touch_icon': 'touch-icon.png'277+}278 259-# fall back if theme is not there260-try:261- __import__('flask_theme_support')262-except ImportError as e:263- print('-' * 74)264- print('Warning: Flask themes unavailable. Building with default theme')265- print('If you want the Flask themes, run this command and build again:')266- print()267- print(' git submodule update --init')268- print('-' * 74)269-270- pygments_style = 'tango'271- html_theme = 'default'272- html_theme_options = {}273-274-279 # unwrap decorators280 def unwrap_decorators():281 import sphinx.util.inspect as inspect282 import functools15 unmodified linesmodified:docs/config.rst+297 added-165 removed
1 unmodified line2 3 Configuration Handling4 ======================5 6-.. versionadded:: 0.37-6 Applications need some kind of configuration. There are different settings7 you might want to change depending on the application environment like8 toggling the debug mode, setting the secret key, and other such9 environment-specific things.31 unmodified lines41 DEBUG=True,42 SECRET_KEY='...'43 )44 45+.. admonition:: Debug Mode with the ``flask`` Script46+47+ If you use the :command:`flask` script to start a local development48+ server, to enable the debug mode, you need to export the ``FLASK_DEBUG``49+ environment variable before running the server::50+51+ $ export FLASK_DEBUG=152+ $ flask run53+54+ (On Windows you need to use ``set`` instead of ``export``).55+56+ ``app.debug`` and ``app.config['DEBUG']`` are not compatible with57+ the :command:`flask` script. They only worked when using ``Flask.run()``58+ method.59+60 Builtin Configuration Values61 ----------------------------62 63 The following configuration values are used internally by Flask:64 52-.. tabularcolumns:: |p{6.5cm}|p{8.5cm}|65+.. py:data:: DEBUG66 54-================================= =========================================55-``DEBUG`` enable/disable debug mode56-``TESTING`` enable/disable testing mode57-``PROPAGATE_EXCEPTIONS`` explicitly enable or disable the58- propagation of exceptions. If not set or59- explicitly set to ``None`` this is60- implicitly true if either ``TESTING`` or61- ``DEBUG`` is true.62-``PRESERVE_CONTEXT_ON_EXCEPTION`` By default if the application is in63- debug mode the request context is not64- popped on exceptions to enable debuggers65- to introspect the data. This can be66- disabled by this key. You can also use67- this setting to force-enable it for non68- debug execution which might be useful to69- debug production applications (but also70- very risky).71-``SECRET_KEY`` the secret key72-``SESSION_COOKIE_NAME`` the name of the session cookie73-``SESSION_COOKIE_DOMAIN`` the domain for the session cookie. If74- this is not set, the cookie will be75- valid for all subdomains of76- ``SERVER_NAME``.77-``SESSION_COOKIE_PATH`` the path for the session cookie. If78- this is not set the cookie will be valid79- for all of ``APPLICATION_ROOT`` or if80- that is not set for ``'/'``.81-``SESSION_COOKIE_HTTPONLY`` controls if the cookie should be set82- with the httponly flag. Defaults to83- ``True``.84-``SESSION_COOKIE_SECURE`` controls if the cookie should be set85- with the secure flag. Defaults to86- ``False``.87-``PERMANENT_SESSION_LIFETIME`` the lifetime of a permanent session as88- :class:`datetime.timedelta` object.89- Starting with Flask 0.8 this can also be90- an integer representing seconds.91-``SESSION_REFRESH_EACH_REQUEST`` this flag controls how permanent92- sessions are refreshed. If set to ``True``93- (which is the default) then the cookie94- is refreshed each request which95- automatically bumps the lifetime. If96- set to ``False`` a `set-cookie` header is97- only sent if the session is modified.98- Non permanent sessions are not affected99- by this.100-``USE_X_SENDFILE`` enable/disable x-sendfile101-``LOGGER_NAME`` the name of the logger102-``LOGGER_HANDLER_POLICY`` the policy of the default logging103- handler. The default is ``'always'``104- which means that the default logging105- handler is always active. ``'debug'``106- will only activate logging in debug107- mode, ``'production'`` will only log in108- production and ``'never'`` disables it109- entirely.110-``SERVER_NAME`` the name and port number of the server.111- Required for subdomain support (e.g.:112- ``'myapp.dev:5000'``) Note that113- localhost does not support subdomains so114- setting this to “localhost” does not115- help. Setting a ``SERVER_NAME`` also116- by default enables URL generation117- without a request context but with an118- 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``.126-``MAX_CONTENT_LENGTH`` If set to a value in bytes, Flask will127- reject incoming requests with a128- content length greater than this by129- returning a 413 status code.130-``SEND_FILE_MAX_AGE_DEFAULT`` Default cache control max age to use with131- :meth:`~flask.Flask.send_static_file` (the132- default static file handler) and133- :func:`~flask.send_file`, as134- :class:`datetime.timedelta` or as seconds.135- Override this value on a per-file136- basis using the137- :meth:`~flask.Flask.get_send_file_max_age`138- hook on :class:`~flask.Flask` or139- :class:`~flask.Blueprint`,140- respectively. Defaults to 43200 (12 hours).141-``TRAP_HTTP_EXCEPTIONS`` If this is set to ``True`` Flask will142- not execute the error handlers of HTTP143- exceptions but instead treat the144- exception like any other and bubble it145- through the exception stack. This is146- helpful for hairy debugging situations147- where you have to find out where an HTTP148- exception is coming from.149-``TRAP_BAD_REQUEST_ERRORS`` Werkzeug's internal data structures that150- deal with request specific data will151- raise special key errors that are also152- bad request exceptions. Likewise many153- operations can implicitly fail with a154- BadRequest exception for consistency.155- Since it's nice for debugging to know156- why exactly it failed this flag can be157- used to debug those situations. If this158- config is set to ``True`` you will get159- a regular traceback instead.160-``PREFERRED_URL_SCHEME`` The URL scheme that should be used for161- URL generation if no URL scheme is162- available. This defaults to ``http``.163-``JSON_AS_ASCII`` By default Flask serialize object to164- ascii-encoded JSON. If this is set to165- ``False`` Flask will not encode to ASCII166- and output strings as-is and return167- unicode strings. ``jsonify`` will168- automatically encode it in ``utf-8``169- then for transport for instance.170-``JSON_SORT_KEYS`` By default Flask will serialize JSON171- objects in a way that the keys are172- ordered. This is done in order to173- ensure that independent of the hash seed174- of the dictionary the return value will175- be consistent to not trash external HTTP176- caches. You can override the default177- behavior by changing this variable.178- This is not recommended but might give179- you a performance improvement on the180- cost of cachability.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)186-``JSONIFY_MIMETYPE`` MIME type used for jsonify responses.187-``TEMPLATES_AUTO_RELOAD`` Whether to check for modifications of188- the template source and reload it189- automatically. By default the value is190- ``None`` which means that Flask checks191- original file only in debug mode.192-``EXPLAIN_TEMPLATE_LOADING`` If this is enabled then every attempt to193- load a template will write an info194- message to the logger explaining the195- attempts to locate the template. This196- can be useful to figure out why197- templates cannot be found or wrong198- templates appear to be loaded.199-================================= =========================================67+ Enable debug mode. When using the development server with ``flask run`` or68+ ``app.run``, an interactive debugger will be shown for unhanlded69+ exceptions, and the server will be reloaded when code changes.70 201-.. admonition:: More on ``SERVER_NAME``71+ **Do not enable debug mode in production.**72 203- The ``SERVER_NAME`` key is used for the subdomain support. Because204- Flask cannot guess the subdomain part without the knowledge of the205- actual server name, this is required if you want to work with206- subdomains. This is also used for the session cookie.73+ Default: ``False``74 208- Please keep in mind that not only Flask has the problem of not knowing209- what subdomains are, your web browser does as well. Most modern web210- browsers will not allow cross-subdomain cookies to be set on a211- server name without dots in it. So if your server name is212- ``'localhost'`` you will not be able to set a cookie for213- ``'localhost'`` and every subdomain of it. Please choose a different214- server name in that case, like ``'myapplication.local'`` and add215- this name + the subdomains you want to use into your host config216- or setup a local `bind`_.75+.. py:data:: TESTING76 218-.. _bind: https://www.isc.org/downloads/bind/77+ Enable testing mode. Exceptions are propagated rather than handled by the78+ the app's error handlers. Extensions may also change their behavior to79+ facilitate easier testing. You should enable this in your own tests.80 81+ Default: ``False``82+83+.. py:data:: PROPAGATE_EXCEPTIONS84+85+ Exceptions are re-raised rather than being handled by the app's error86+ handlers. If not set, this is implicitly true if ``TESTING`` or ``DEBUG``87+ is enabled.88+89+ Default: ``None``90+91+.. py:data:: PRESERVE_CONTEXT_ON_EXCEPTION92+93+ Don't pop the request context when an exception occurs. If not set, this94+ is true if ``DEBUG`` is true. This allows debuggers to introspect the95+ request data on errors, and should normally not need to be set directly.96+97+ Default: ``None``98+99+.. py:data:: TRAP_HTTP_EXCEPTIONS100+101+ If there is no handler for an ``HTTPException``-type exception, re-raise it102+ to be handled by the interactive debugger instead of returning it as a103+ simple error response.104+105+ Default: ``False``106+107+.. py:data:: TRAP_BAD_REQUEST_ERRORS``108+109+ Trying to access a key that doesn't exist from request dicts like ``args``110+ and ``form`` will return a 400 Bad Request error page. Enable this to treat111+ the error as an unhandled exception instead so that you get the interactive112+ debugger. This is a more specific version of ``TRAP_HTTP_EXCEPTIONS``. If113+ unset, it is enabled in debug mode.114+115+ Default: ``None``116+117+.. py:data:: SECRET_KEY118+119+ A secret key that will be used for securely signing the session cookie120+ and can be used for any other security related needs by extensions or your121+ application. It should be a long random string of bytes, although unicode122+ is accepted too. For example, copy the output of this to your config::123+124+ python -c 'import os; print(os.urandom(32))'125+126+ **Do not reveal the secret key when posting questions or committing code.**127+128+ Default: ``None``129+130+.. py:data:: SESSION_COOKIE_NAME131+132+ The name of the session cookie. Can be changed in case you already have a133+ cookie with the same name.134+135+ Default: ``'session'``136+137+.. py:data:: SESSION_COOKIE_DOMAIN138+139+ The domain match rule that the session cookie will be valid for. If not140+ set, the cookie will be valid for all subdomains of ``SERVER_NAME``. If141+ ``False``, the cookie's domain will not be set.142+143+ Default: ``None``144+145+.. py:data:: SESSION_COOKIE_PATH146+147+ The path that the session cookie will be valid for. If not set, the cookie148+ will be valid underneath ``APPLICATION_ROOT`` or ``/`` if that is not set.149+150+ Default: ``None``151+152+.. py:data:: SESSION_COOKIE_HTTPONLY153+154+ Browsers will not allow JavaScript access to cookies marked as "HTTP only"155+ for security.156+157+ Default: ``True``158+159+.. py:data:: SESSION_COOKIE_SECURE160+161+ Browsers will only send cookies with requests over HTTPS if the cookie is162+ marked "secure". The application must be served over HTTPS for this to make163+ sense.164+165+ Default: ``False``166+167+.. py:data:: PERMANENT_SESSION_LIFETIME168+169+ If ``session.permanent`` is true, the cookie's max age will be set to this170+ number of seconds. Can either be a :class:`datetime.timedelta` or an171+ ``int``.172+173+ Default: ``timedelta(days=31)`` (``2678400`` seconds)174+175+.. py:data:: SESSION_REFRESH_EACH_REQUEST176+177+ Control whether the cookie is sent with every response when178+ ``session.permanent`` is true. Sending the cookie every time (the default)179+ can more reliably keep the session from expiring, but uses more bandwidth.180+ Non-permanent sessions are not affected.181+182+ Default: ``True``183+184+.. py:data:: USE_X_SENDFILE185+186+ When serving files, set the ``X-Sendfile`` header instead of serving the187+ data with Flask. Some web servers, such as Apache, recognize this and serve188+ the data more efficiently. This only makes sense when using such a server.189+190+ Default: ``False``191+192+.. py:data:: SEND_FILE_MAX_AGE_DEFAULT193+194+ When serving files, set the cache control max age to this number of195+ seconds. Can either be a :class:`datetime.timedelta` or an ``int``.196+ Override this value on a per-file basis using197+ :meth:`~flask.Flask.get_send_file_max_age` on the application or blueprint.198+199+ Default: ``timedelta(hours=12)`` (``43200`` seconds)200+201+.. py:data:: LOGGER_NAME202+203+ The name of the logger that the Flask application sets up. If not set,204+ it will take the import name passed to ``Flask.__init__``.205+206+ Default: ``None``207+208+.. py:data:: LOGGER_HANDLER_POLICY209+210+ When to activate the application's logger handler. ``'always'`` always211+ enables it, ``'debug'`` only activates it in debug mode, ``'production'``212+ only activates it when not in debug mode, and ``'never'`` never enables it.213+214+ Default: ``'always'``215+216+.. py:data:: SERVER_NAME217+218+ Inform the application what host and port it is bound to. Required for219+ subdomain route matching support.220+221+ If set, will be used for the session cookie domain if222+ ``SESSION_COOKIE_DOMAIN`` is not set. Modern web browsers will not allow223+ setting cookies for domains without a dot. To use a domain locally,224+ add any names that should route to the app to your ``hosts`` file. ::225+226+ 127.0.0.1 localhost.dev227+228+ If set, ``url_for`` can generate external URLs with only an application229+ context instead of a request context.230+231+ Default: ``None``232+233+.. py:data:: APPLICATION_ROOT234+235+ Inform the application what path it is mounted under by the application /236+ web server.237+238+ Will be used for the session cookie path if ``SESSION_COOKIE_PATH`` is not239+ set.240+241+ Default: ``'/'``242+243+.. py:data:: PREFERRED_URL_SCHEME244+245+ Use this scheme for generating external URLs when not in a request context.246+247+ Default: ``'http'``248+249+.. py:data:: MAX_CONTENT_LENGTH250+251+ Don't read more than this many bytes from the incoming request data. If not252+ set and the request does not specify a ``CONTENT_LENGTH``, no data will be253+ read for security.254+255+ Default: ``None``256+257+.. py:data:: JSON_AS_ASCII258+259+ Serialize objects to ASCII-encoded JSON. If this is disabled, the JSON260+ will be returned as a Unicode string, or encoded as ``UTF-8`` by261+ ``jsonify``. This has security implications when rendering the JSON in262+ to JavaScript in templates, and should typically remain enabled.263+264+ Default: ``True``265+266+.. py:data:: JSON_SORT_KEYS267+268+ Sort the keys of JSON objects alphabetically. This is useful for caching269+ because it ensures the data is serialized the same way no matter what270+ Python's hash seed is. While not recommended, you can disable this for a271+ possible performance improvement at the cost of caching.272+273+ Default: ``True``274+275+.. py:data:: JSONIFY_PRETTYPRINT_REGULAR276+277+ ``jsonify`` responses will be output with newlines, spaces, and indentation278+ for easier reading by humans. Always enabled in debug mode.279+280+ Default: ``False``281+282+.. py:data:: JSONIFY_MIMETYPE283+284+ The mimetype of ``jsonify`` responses.285+286+ Default: ``'application/json'``287+288+.. py:data:: TEMPLATES_AUTO_RELOAD289+290+ Reload templates when they are changed. If not set, it will be enabled in291+ debug mode.292+293+ Default: ``None``294+295+.. py:data:: EXPLAIN_TEMPLATE_LOADING296+297+ Log debugging information tracing how a template file was loaded. This can298+ be useful to figure out why a template was not loaded or the wrong file299+ appears to be loaded.300+301+ Default: ``False``302+303 .. versionadded:: 0.4304 ``LOGGER_NAME``305 306 .. versionadded:: 0.537 unmodified lines344 app.config.from_envvar('YOURAPPLICATION_SETTINGS')345 346 This first loads the configuration from the347 `yourapplication.default_settings` module and then overrides the values265-with the contents of the file the :envvar:``YOURAPPLICATION_SETTINGS``348+with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS`349 environment variable points to. This environment variable can be set on350 Linux or OS X with the export command in the shell before starting the351 server::352 21 unmodified lines374 methods on the config object as well to load from individual files. For a375 complete reference, read the :class:`~flask.Config` object's376 documentation.377 378+Configuring from Environment Variables379+--------------------------------------380 381+In addition to pointing to configuration files using environment variables, you382+may find it useful (or necessary) to control your configuration values directly383+from the environment.384+385+Environment variables can be set on Linux or OS X with the export command in386+the shell before starting the server::387+388+ $ export SECRET_KEY='?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'389+ $ export DEBUG=False390+ $ python run-app.py391+ * Running on http://127.0.0.1:5000/392+ * Restarting with reloader...393+394+On Windows systems use the `set` builtin instead::395+396+ >set SECRET_KEY='?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'397+ >set DEBUG=False398+399+While this approach is straightforward to use, it is important to remember that400+environment variables are strings -- they are not automatically deserialized401+into Python types.402+403+Here is an example of a configuration file that uses environment variables::404+405+ # Example configuration406+ import os407+408+ ENVIRONMENT_DEBUG = os.environ.get("DEBUG", default=False)409+ if ENVIRONMENT_DEBUG.lower() in ("f", "false"):410+ ENVIRONMENT_DEBUG = False411+412+ DEBUG = ENVIRONMENT_DEBUG413+ SECRET_KEY = os.environ.get("SECRET_KEY", default=None)414+ if not SECRET_KEY:415+ raise ValueError("No secret key set for Flask application")416+417+418+Notice that any value besides an empty string will be interpreted as a boolean419+``True`` value in Python, which requires care if an environment explicitly sets420+values intended to be ``False``.421+422+Make sure to load the configuration very early on, so that extensions have the423+ability to access the configuration when starting up. There are other methods424+on the config object as well to load from individual files. For a complete425+reference, read the :class:`~flask.Config` class documentation.426+427 Configuration Best Practices428 ----------------------------429 430 The downside with the approach mentioned earlier is that it makes testing162 unmodified lines593 594 # or via open_instance_resource:595 with app.open_instance_resource('application.cfg') as f:596 config = f.read()597+modified:docs/contents.rst.inc+1 added
57 unmodified lines58 python359 upgrading60 changelog61 license62+ contributingadded:docs/contributing.rst+1 added
1+.. include:: ../CONTRIBUTING.rstmodified:docs/errorhandling.rst+54 added-30 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 local8 unmodified lines50 51 from raven.contrib.flask import Sentry52 sentry = Sentry(app, dsn='YOUR_DSN_HERE')53 54-Of if you are using factories you can also init it later::54+Or if you are using factories you can also init it later::55 56 from raven.contrib.flask import Sentry57 sentry = Sentry(dsn='YOUR_DSN_HERE')58 16 unmodified lines75 76 You might want to show custom error pages to the user when an error occurs.77 This can be done by registering error handlers.78 79-Error handlers are normal :ref:`views` but instead of being registered for80-routes they are registered for exceptions that are rised while trying to81-do something else.79+An error handler is a normal view function that return a response, but instead80+of being registered for a route, it is registered for an exception or HTTP81+status code that would is raised while trying to handle a request.82 83 Registering84 ```````````85 86-Register error handlers using :meth:`~flask.Flask.errorhandler` or87-:meth:`~flask.Flask.register_error_handler`::86+Register handlers by decorating a function with87+:meth:`~flask.Flask.errorhandler`. Or use88+:meth:`~flask.Flask.register_error_handler` to register the function later.89+Remember to set the error code when returning the response. ::90 91 @app.errorhandler(werkzeug.exceptions.BadRequest)92 def handle_bad_request(e):91- return 'bad request!'92- 93- app.register_error_handler(400, lambda e: 'bad request!')93+ return 'bad request!', 40094 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 that95+ # or, without the decorator96+ app.register_error_handler(400, handle_bad_request)97+98 :exc:`werkzeug.exceptions.HTTPException` subclasses like98-:exc:`~werkzeug.exceptions.BadRequest` from the example and their HTTP codes99-are interchangeable when handed to the registration methods or decorator100-(``BadRequest.code == 400``).99+:exc:`~werkzeug.exceptions.BadRequest` and their HTTP codes are interchangeable100+when registering handlers. (``BadRequest.code == 400``)101 102-You are however not limited to :exc:`~werkzeug.exceptions.HTTPException`103-or HTTP status codes but can register a handler for every exception class you104-like.102+Non-standard HTTP codes cannot be registered by code because they are not known103+by Werkzeug. Instead, define a subclass of104+:class:`~werkzeug.exceptions.HTTPException` with the appropriate code and105+register and raise that exception class. ::106 106-.. versionchanged:: 0.11107+ class InsufficientStorage(werkzeug.exceptions.HTTPException):108+ code = 507109+ description = 'Not enough storage space.'110 108- Errorhandlers are now prioritized by specificity of the exception classes109- they are registered for instead of the order they are registered in.111+ app.register_error_handler(InsuffcientStorage, handle_507)112 113+ raise InsufficientStorage()114+115+Handlers can be registered for any exception class, not just116+:exc:`~werkzeug.exceptions.HTTPException` subclasses or HTTP status117+codes. Handlers can be registered for a specific class, or for all subclasses118+of a parent class.119+120 Handling121 ````````122 114-Once an exception instance is raised, its class hierarchy is traversed,115-and searched for in the exception classes for which handlers are registered.116-The most specific handler is selected.123+When an exception is caught by Flask while handling a request, it is first124+looked up by code. If no handler is registered for the code, it is looked up125+by its class hierarchy; the most specific handler is chosen. If no handler is126+registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a127+generic message about their code, while other exceptions are converted to a128+generic 500 Internal Server Error.129 118-E.g. if an instance of :exc:`ConnectionRefusedError` is raised, and a handler130+For example, if an instance of :exc:`ConnectionRefusedError` is raised, and a handler131 is registered for :exc:`ConnectionError` and :exc:`ConnectionRefusedError`,120-the more specific :exc:`ConnectionRefusedError` handler is called on the121-exception instance, and its response is shown to the user.132+the more specific :exc:`ConnectionRefusedError` handler is called with the133+exception instance to generate the response.134 135+Handlers registered on the blueprint take precedence over those registered136+globally on the application, assuming a blueprint is handling the request that137+raises the exception. However, the blueprint cannot handle 404 routing errors138+because the 404 occurs at the routing level before the blueprint can be139+determined.140+141+.. versionchanged:: 0.11142+143+ Handlers are prioritized by specificity of the exception classes they are144+ registered for instead of the order they are registered in.145+146 Error Mails147 -----------148 149 If the application runs in production mode (which it will do on your88 unmodified lines238 A formatter can be instantiated with a format string. Note that239 tracebacks are appended to the log entry automatically. You don't have to240 do that in the log formatter format string.241 219-Here some example setups:242+Here are some example setups:243 244 Email245 `````246 51 unmodified lines298 +------------------+----------------------------------------------------+299 | ``%(lineno)d`` | Source line number where the logging call was |300 | | issued (if available). |301 +------------------+----------------------------------------------------+279-| ``%(asctime)s`` | Human-readable time when the LogRecord` was |280-| | created. By default this is of the form |302+| ``%(asctime)s`` | Human-readable time when the |303+| | :class:`~logging.LogRecord` was created. |304+| | By default this is of the form |305 | | ``"2003-07-08 16:49:45,896"`` (the numbers after |306 | | the comma are millisecond portion of the time). |307 | | This can be changed by subclassing the formatter |308 | | and overriding the |109 unmodified linesmodified:docs/extensiondev.rst+16 added-24 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 aid5 unmodified lines41 that people can easily install the development version into their42 virtualenv without having to download the library by hand.43 44 Flask extensions must be licensed under a BSD, MIT or more liberal license51-to be able to be enlisted in the Flask Extension Registry. Keep in mind45+in order to be listed in the Flask Extension Registry. Keep in mind46 that the Flask Extension Registry is a moderated place and libraries will47 be reviewed upfront if they behave as required.48 49 "Hello Flaskext!"97 unmodified lines147 What to use depends on what you have in mind. For the SQLite 3 extension148 we will use the class-based approach because it will provide users with an149 object that handles opening and closing database connections.150 157-What's important about classes is that they encourage to be shared around158-on module level. In that case, the object itself must not under any151+When designing your classes, it's important to make them easily reusable152+at the module level. This means the object itself must not under any153 circumstances store any application specific state and must be shareable160-between different application.154+between different applications.155 156 The Extension Code157 ------------------158 168 unmodified lines327 development. If you want to learn more, it's a very good idea to check328 out existing extensions on the `Flask Extension Registry`_. If you feel329 lost there is still the `mailinglist`_ and the `IRC channel`_ to get some330 ideas for nice looking APIs. Especially if you do something nobody before337-you did, it might be a very good idea to get some more input. This not338-only to get an idea about what people might want to have from an339-extension, but also to avoid having multiple developers working on pretty340-much the same side by side.331+you did, it might be a very good idea to get some more input. This not only332+generates useful feedback on what people might want from an extension, but333+also avoids having multiple developers working in isolation on pretty much the334+same problem.335 336 Remember: good API design is hard, so introduce your project on the337 mailinglist, and let other developers give you a helping hand with338 designing the API.24 unmodified lines363 test suite also has to be part of the distribution.364 3. APIs of approved extensions will be checked for the following365 characteristics:366 373- - an approved extension has to support multiple applications374- running in the same Python process.375- - it must be possible to use the factory pattern for creating376- applications.367+ - an approved extension has to support multiple applications368+ running in the same Python process.369+ - it must be possible to use the factory pattern for creating370+ applications.371 372 4. The license must be BSD/MIT/WTFPL licensed.373 5. The naming scheme for official extensions is *Flask-ExtensionName* or374 *ExtensionName-Flask*.5 unmodified lines380 8. The setup.py description (and thus the PyPI description) has to381 link to the documentation, website (if there is one) and there382 must be a link to automatically install the development version383 (``PackageName==dev``).390-9. The ``zip_safe`` flag in the setup script must be set to ``False``,391- even if the extension would be safe for zipping.392-10. An extension currently has to support Python 2.6 as well as393- Python 2.7384+9. The ``zip_safe`` flag in the setup script must be set to ``False``,385+ even if the extension would be safe for zipping.386+10. An extension currently has to support Python 2.7, Python 3.3 and higher.387 388 396-.. _ext-import-transition:389 390 Extension Import Transition391 ---------------------------392 11 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/deleted:docs/flaskext.py-86 removed
1-# flasky extensions. flasky pygments style based on tango style2-from pygments.style import Style3-from pygments.token import Keyword, Name, Comment, String, Error, \4- Number, Operator, Generic, Whitespace, Punctuation, Other, Literal5-6-7-class FlaskyStyle(Style):8- background_color = "#f8f8f8"9- default_style = ""10-11- styles = {12- # No corresponding class for the following:13- #Text: "", # class: ''14- Whitespace: "underline #f8f8f8", # class: 'w'15- Error: "#a40000 border:#ef2929", # class: 'err'16- Other: "#000000", # class 'x'17-18- Comment: "italic #8f5902", # class: 'c'19- Comment.Preproc: "noitalic", # class: 'cp'20-21- Keyword: "bold #004461", # class: 'k'22- Keyword.Constant: "bold #004461", # class: 'kc'23- Keyword.Declaration: "bold #004461", # class: 'kd'24- Keyword.Namespace: "bold #004461", # class: 'kn'25- Keyword.Pseudo: "bold #004461", # class: 'kp'26- Keyword.Reserved: "bold #004461", # class: 'kr'27- Keyword.Type: "bold #004461", # class: 'kt'28-29- Operator: "#582800", # class: 'o'30- Operator.Word: "bold #004461", # class: 'ow' - like keywords31-32- Punctuation: "bold #000000", # class: 'p'33-34- # because special names such as Name.Class, Name.Function, etc.35- # are not recognized as such later in the parsing, we choose them36- # to look the same as ordinary variables.37- Name: "#000000", # class: 'n'38- Name.Attribute: "#c4a000", # class: 'na' - to be revised39- Name.Builtin: "#004461", # class: 'nb'40- Name.Builtin.Pseudo: "#3465a4", # class: 'bp'41- Name.Class: "#000000", # class: 'nc' - to be revised42- Name.Constant: "#000000", # class: 'no' - to be revised43- Name.Decorator: "#888", # class: 'nd' - to be revised44- Name.Entity: "#ce5c00", # class: 'ni'45- Name.Exception: "bold #cc0000", # class: 'ne'46- Name.Function: "#000000", # class: 'nf'47- Name.Property: "#000000", # class: 'py'48- Name.Label: "#f57900", # class: 'nl'49- Name.Namespace: "#000000", # class: 'nn' - to be revised50- Name.Other: "#000000", # class: 'nx'51- Name.Tag: "bold #004461", # class: 'nt' - like a keyword52- Name.Variable: "#000000", # class: 'nv' - to be revised53- Name.Variable.Class: "#000000", # class: 'vc' - to be revised54- Name.Variable.Global: "#000000", # class: 'vg' - to be revised55- Name.Variable.Instance: "#000000", # class: 'vi' - to be revised56-57- Number: "#990000", # class: 'm'58-59- Literal: "#000000", # class: 'l'60- Literal.Date: "#000000", # class: 'ld'61-62- String: "#4e9a06", # class: 's'63- String.Backtick: "#4e9a06", # class: 'sb'64- String.Char: "#4e9a06", # class: 'sc'65- String.Doc: "italic #8f5902", # class: 'sd' - like a comment66- String.Double: "#4e9a06", # class: 's2'67- String.Escape: "#4e9a06", # class: 'se'68- String.Heredoc: "#4e9a06", # class: 'sh'69- String.Interpol: "#4e9a06", # class: 'si'70- String.Other: "#4e9a06", # class: 'sx'71- String.Regex: "#4e9a06", # class: 'sr'72- String.Single: "#4e9a06", # class: 's1'73- String.Symbol: "#4e9a06", # class: 'ss'74-75- Generic: "#000000", # class: 'g'76- Generic.Deleted: "#a40000", # class: 'gd'77- Generic.Emph: "italic #000000", # class: 'ge'78- Generic.Error: "#ef2929", # class: 'gr'79- Generic.Heading: "bold #000080", # class: 'gh'80- Generic.Inserted: "#00A000", # class: 'gi'81- Generic.Output: "#888", # class: 'go'82- Generic.Prompt: "#745334", # class: 'gp'83- Generic.Strong: "bold #000000", # class: 'gs'84- Generic.Subheading: "bold #800080", # class: 'gu'85- Generic.Traceback: "bold #a40000", # class: 'gt'86- }modified:docs/installation.rst+115 added-116 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 one of the following two44-commands 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 easy_install virtualenv45+.. _Blinker: https://pythonhosted.org/blinker/46+.. _SimpleJSON: https://simplejson.readthedocs.io/47 48-or even better::48+Virtual environments49+--------------------50 50- $ sudo pip install virtualenv51+Use a virtual environment to manage the dependencies for your project, both in52+development and in production.53 52-One of these will probably install virtualenv on your system. Maybe it's even53-in your package manager. If you use Ubuntu, try::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 55- $ sudo apt-get install python-virtualenv59+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 57-If you are on Windows and don't have the :command:`easy_install` command, you must58-install it first. Check the :ref:`windows-easy-install` section for more59-information about how to do that. Once you have it installed, run the same60-commands as above, but without the :command:`sudo` prefix.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 62-Once you have virtualenv installed, just fire up a shell and create63-your own environment. I usually create a project folder and a :file:`venv`64-folder within::67+If you're using Python 2, see :ref:`install-install-virtualenv` first.68 66- $ mkdir myproject67- $ cd myproject68- $ virtualenv venv69- New python executable in venv/bin/python70- Installing setuptools, pip............done.69+.. _install-create-env:70 72-Now, whenever you want to work on a project, you only have to activate the73-corresponding environment. On OS X and Linux, do the following::71+Create an environment72+~~~~~~~~~~~~~~~~~~~~~73 75- $ . venv/bin/activate74+Create a project folder and a :file:`venv` folder within:75 77-If you are a Windows user, the following command is for you::76+.. code-block:: sh77 79- $ venv\scripts\activate78+ mkdir myproject79+ cd myproject80+ python3 -m venv venv81 81-Either way, you should now be using your virtualenv (notice how the prompt of82-your shell has changed to show the active environment).82+On Windows:83 84-And if you want to go back to the real world, use the following command::84+.. code-block:: bat85 86- $ deactivate86+ py -3 -m venv venv87 88-After doing this, the prompt of your shell should be as familiar as before.88+If you needed to install virtualenv because you are on an older version of89+Python, use the following command instead:90 90-Now, let's move on. Enter the following command to get Flask activated in your91-virtualenv::91+.. code-block:: sh92 93- $ pip install Flask93+ virtualenv venv94 95-A few seconds later and you are good to go.95+On Windows:96 97+.. code-block:: bat98 98-System-Wide Installation99-------------------------99+ \Python27\Scripts\virtualenv.exe venv100 101-This is possible as well, though I do not recommend it. Just run102-:command:`pip` with root privileges::101+Activate the environment102+~~~~~~~~~~~~~~~~~~~~~~~~103 104- $ sudo pip install Flask104+Before you work on your project, activate the corresponding environment:105 106-(On Windows systems, run it in a command-prompt window with administrator107-privileges, and leave out :command:`sudo`.)106+.. code-block:: sh107 108+ . venv/bin/activate109 110-Living on the Edge111-------------------110+On Windows:111 113-If you want to work with the latest version of Flask, there are two ways: you114-can either let :command:`pip` pull in the development version, or you can tell115-it to operate on a git checkout. Either way, virtualenv is recommended.112+.. code-block:: bat113 117-Get the git checkout in a new virtualenv and run in development mode::114+ venv\Scripts\activate115 119- $ git clone http://github.com/pallets/flask.git120- Initialized empty Git repository in ~/dev/flask/.git/121- $ cd flask122- $ virtualenv venv123- New python executable in venv/bin/python124- Installing setuptools, pip............done.125- $ . venv/bin/activate126- $ python setup.py develop127- ...128- Finished processing dependencies for Flask116+Your shell prompt will change to show the name of the activated environment.117 130-This will pull in the dependencies and activate the git head as the current131-version inside the virtualenv. Then all you have to do is run ``git pull132-origin`` to update to the latest version.118+Install Flask119+-------------120 121+Within the activated environment, use the following command to install Flask:122 135-.. _windows-easy-install:123+.. code-block:: sh124 137-`pip` and `setuptools` on Windows138----------------------------------125+ pip install Flask126 140-Sometimes getting the standard "Python packaging tools" like *pip*, *setuptools*141-and *virtualenv* can be a little trickier, but nothing very hard. The two crucial142-packages you will need are setuptools and pip - these will let you install143-anything else (like virtualenv). Fortunately there are two "bootstrap scripts"144-you can run to install either.127+Living on the edge128+~~~~~~~~~~~~~~~~~~129 146-If you don't currently have either, then `get-pip.py` will install both for you147-(you won't need to run ez_setup.py).130+If you want to work with the latest Flask code before it's released, install or131+update the code from the master branch:132 149-`get-pip.py`_133+.. code-block:: sh134 151-To install the latest setuptools, you can use its bootstrap file:135+ pip install -U https://github.com/pallets/flask/archive/master.tar.gz136 153-`ez_setup.py`_137+.. _install-install-virtualenv:138 155-Either should be double-clickable once you download them. If you already have pip,156-you can upgrade them by running::139+Install virtualenv140+------------------141 158- > pip install --upgrade pip setuptools142+If you are using Python 2, the venv module is not available. Instead,143+install `virtualenv`_.144 160-Most often, once you pull up a command prompt you want to be able to type :command:`pip`161-and :command:`python` which will run those things, but this might not automatically happen162-on Windows, because it doesn't know where those executables are (give either a try!).145+On Linux, virtualenv is provided by your package manager:146 164-To fix this, you should be able to navigate to your Python install directory165-(e.g :file:`C:\Python27`), then go to :file:`Tools`, then :file:`Scripts`, then find the166-:file:`win_add2path.py` file and run that. Open a **new** Command Prompt and167-check that you can now just type :command:`python` to bring up the interpreter.147+.. code-block:: sh148 169-Finally, to install `virtualenv`_, you can simply run::149+ # Debian, Ubuntu150+ sudo apt-get install python-virtualenv151 171- > pip install virtualenv152+ # CentOS, Fedora153+ sudo yum install python-virtualenv154 173-Then you can be off on your way following the installation instructions above.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.py176-.. _ez_setup.py: https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.pymodified:docs/quickstart.rst+149 added-194 removed
24 unmodified lines25 1. First we imported the :class:`~flask.Flask` class. An instance of this26 class will be our WSGI application.27 2. Next we create an instance of this class. The first argument is the name of28 the application's module or package. If you are using a single module (as29- in this example), you should use `__name__` because depending on if it's29+ in this example), you should use ``__name__`` because depending on if it's30 started as application or imported as module the name will be different31 (``'__main__'`` versus the actual import name). This is needed so that32 Flask knows where to look for templates, static files, and so on. For more33 information have a look at the :class:`~flask.Flask` documentation.7 unmodified lines41 your application :file:`flask.py` because this would conflict with Flask42 itself.43 44 To run the application you can either use the :command:`flask` command or45-python's :option:`-m` switch with Flask. Before you can do that you need45+python's ``-m`` switch with Flask. Before you can do that you need46 to tell your terminal the application to work with by exporting the47-`FLASK_APP` environment variable::47+``FLASK_APP`` environment variable::48 49 $ export FLASK_APP=hello.py50 $ flask run51 * Running on http://127.0.0.1:5000/52 53-If you are on Windows you need to use `set` instead of `export`.53+If you are on Windows, the environment variable syntax depends on command line54+interpreter. On Command Prompt::55 55-Alternatively you can use `python -m flask`::56+ C:\path\to\app>set FLASK_APP=hello.py57 58+And on PowerShell::59+60+ PS C:\path\to\app> $env:FLASK_APP = "hello.py"61+62+Alternatively you can use :command:`python -m flask`::63+64 $ export FLASK_APP=hello.py65 $ python -m flask run66 * Running on http://127.0.0.1:5000/67 24 unmodified lines92 93 What to do if the Server does not Start94 ---------------------------------------95 89-In case the ``python -m flask`` fails or :command:`flask` does not exist,96+In case the :command:`python -m flask` fails or :command:`flask` does not exist,97 there are multiple reasons this might be the case. First of all you need98 to look at the error message.99 100 Old Version of Flask101 ````````````````````102 103 Versions of Flask older than 0.11 use to have different ways to start the104 application. In short, the :command:`flask` command did not exist, and98-neither did ``python -m flask``. In that case you have two options:105+neither did :command:`python -m flask`. In that case you have two options:106 either upgrade to newer Flask versions or have a look at the :ref:`server`107 docs to see the alternative method for running a server.108 109 Invalid Import Name110 ```````````````````111 105-The :option:`-a` argument to :command:`flask` is the name of the module to106-import. In case that module is incorrectly named you will get an import107-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.112+The ``FLASK_APP`` environment variable is the name of the module to import at113+:command:`flask run`. In case that module is incorrectly named you will get an114+import error upon start (or if debug is enabled when you navigate to the115+application). It will tell you what it tried to import and why it failed.116 117 The most common reason is a typo or because you did not actually create an118 ``app`` object.119 9 unmodified lines129 That is not very nice and Flask can do better. If you enable debug130 support the server will reload itself on code changes, and it will also131 provide you with a helpful debugger if things go wrong.132 126-To enable debug mode you can export the `FLASK_DEBUG` environment variable133+To enable debug mode you can export the ``FLASK_DEBUG`` environment variable134 before running the server::135 136 $ export FLASK_DEBUG=1137 $ flask run138 132-(On Windows you need to use `set` instead of `export`).139+(On Windows you need to use ``set`` instead of ``export``).140 141 This does the following things:142 143 1. it activates the debugger15 unmodified lines159 :align: center160 :class: screenshot161 :alt: screenshot of debugger in action162 163+More information on using the debugger can be found in the `Werkzeug 164+documentation`_.165+166+.. _Werkzeug documentation: http://werkzeug.pocoo.org/docs/debug/#using-the-debugger167+168 Have another debugger in mind? See :ref:`working-with-debuggers`.169 170 171 Routing172 -------173 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.174+Modern web applications use meaningful URLs to help users. Users are more175+likely to like a page and come back if the page uses a meaningful URL they can176+remember and use to directly visit a page.177 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::178+Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::179 180 @app.route('/')181 def index():182 return 'Index Page'1 unmodified line184 @app.route('/hello')185 def hello():186 return 'Hello, World'187 179-But there is more to it! You can make certain parts of the URL dynamic and180-attach multiple rules to a function.188+You can do more! You can make parts of the URL dynamic and attach multiple189+rules to a function.190 191 Variable Rules192 ``````````````193 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::194+You can add variable sections to a URL by marking sections with195+``<variable_name>``. Your function then receives the ``<variable_name>``196+as a keyword argument. Optionally, you can use a converter to specify the type197+of the argument like ``<converter:variable_name>``. ::198 199 @app.route('/user/<username>')200 def show_user_profile(username):201 # show the user profile for that user3 unmodified lines205 def show_post(post_id):206 # show the post with the given id, the id is an integer207 return 'Post %d' % post_id208 200-The following converters exist:209+ @app.route('/path/<path:subpath>')210+ def show_subpath(subpath):211+ # show the subpath after /path/212+ return 'Subpath %s' % subpath213 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-=========== ===============================================214+Converter types:215 211-.. admonition:: Unique URLs / Redirection Behavior216+========== ==========================================217+``string`` (default) accepts any text without a slash218+``int`` accepts positive integers219+``float`` accepts positive floating point values220+``path`` like ``string`` but also accepts slashes221+``uuid`` accepts UUID strings222+========== ==========================================223 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.224+Unique URLs / Redirection Behavior225+``````````````````````````````````226 217- Take these two rules::227+Take these two rules::228 219- @app.route('/projects/')220- def projects():221- return 'The project page'229+ @app.route('/projects/')230+ def projects():231+ return 'The project page'232 223- @app.route('/about')224- def about():225- return 'The about page'233+ @app.route('/about')234+ def about():235+ return 'The about page'236 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.237+Though they look similar, they differ in their use of the trailing slash in238+the URL. In the first case, the canonical URL for the ``projects`` endpoint239+uses a trailing slash. It's similar to a folder in a file system; if you240+access the URL without a trailing slash, Flask redirects you to the241+canonical URL with the trailing slash.242 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.243+In the second case, however, the URL definition lacks a trailing slash,244+like the pathname of a file on UNIX-like systems. Accessing the URL with a245+trailing slash produces a 404 “Not Found” error.246 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.247+This behavior allows relative URLs to continue working even if the trailing248+slash is omitted, consistent with how Apache and other servers work. Also,249+the URLs will stay unique, which helps search engines avoid indexing the250+same page twice.251 242-252 .. _url-building:253 254 URL Building255 ````````````256 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:257+To build a URL to a specific function, use the :func:`~flask.url_for` function.258+It accepts the name of the function as its first argument and any number of259+keyword arguments, each corresponding to a variable part of the URL rule.260+Unknown variable parts are appended to the URL as query parameters.261 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-262 Why would you want to build URLs using the URL reversing function263 :func:`~flask.url_for` instead of hard-coding them into your templates?284-There are three good reasons for this:264 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.265+1. Reversing is often more descriptive than hard-coding the URLs.266+2. You can change your URLs in one go instead of needing to remember to267+ manually change hard-coded URLs.268+3. URL building handles escaping of special characters and Unicode data269+ transparently.270+4. If your application is placed outside the URL root, for example, in271+ ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly272+ handles that for you.273 274+For example, here we use the :meth:`~flask.Flask.test_request_context` method275+to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`276+tells Flask to behave as though it's handling a request even while we use a277+Python shell. See :ref:`context-locals`. ::278 279+ from flask import Flask, url_for280+281+ app = Flask(__name__)282+283+ @app.route('/')284+ def index():285+ return 'index'286+287+ @app.route('/login')288+ def login():289+ return 'login'290+291+ @app.route('/user/<username>')292+ def profile(username):293+ return '{}'s profile'.format(username)294+295+ with app.test_request_context():296+ print(url_for('index'))297+ print(url_for('login'))298+ print(url_for('login', next='/'))299+ print(url_for('profile', username='John Doe'))300+301+ /302+ /login303+ /login?next=/304+ /user/John%20Doe305+306 HTTP Methods307 ````````````308 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::309+Web applications use different HTTP methods when accessing URLs. You should310+familiarize yourself with the HTTP methods as you work with Flask. By default,311+a route only answers to ``GET`` requests. You can use the ``methods`` argument312+of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.313+::314 304- from flask import request305-315 @app.route('/login', methods=['GET', 'POST'])316 def login():317 if request.method == 'POST':318 do_the_login()319 else:320 show_the_login_form()321 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.322+If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method323+and handles ``HEAD`` requests according to the the `HTTP RFC`_. Likewise,324+``OPTIONS`` is automatically implemented for you.325 320-You have no idea what an HTTP method is? Worry not, here is a quick321-introduction to HTTP methods and why they matter:326+.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt327 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-328 Static Files329 ------------330 331 Dynamic web applications also need static files. That's usually where69 unmodified lines401 know how that works, head over to the :ref:`template-inheritance` pattern402 documentation. Basically template inheritance makes it possible to keep403 certain elements on each page (like header, navigation and footer).404 449-Automatic escaping is enabled, so if `name` contains HTML it will be escaped405+Automatic escaping is enabled, so if ``name`` contains HTML it will be escaped406 automatically. If you can trust a variable and you know that it will be407 safe HTML (for example because it came from a module that converts wiki408 markup to HTML) you can mark it as safe by using the409 :class:`~jinja2.Markup` class or by using the ``|safe`` filter in the410 template. Head over to the Jinja 2 documentation for more examples.411 456-Here is a basic introduction to how the :class:`~jinja2.Markup` class works:412+Here is a basic introduction to how the :class:`~jinja2.Markup` class works::413 458->>> from flask import Markup459->>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'460-Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')461->>> Markup.escape('<blink>hacker</blink>')462-Markup(u'<blink>hacker</blink>')463->>> Markup('<em>Marked up</em> » HTML').striptags()464-u'Marked up \xbb HTML'414+ >>> from flask import Markup415+ >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'416+ Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')417+ >>> Markup.escape('<blink>hacker</blink>')418+ Markup(u'<blink>hacker</blink>')419+ >>> Markup('<em>Marked up</em> » HTML').striptags()420+ u'Marked up \xbb HTML'421 422 .. versionchanged:: 0.5423 424 Autoescaping is no longer enabled for all templates. The following68 unmodified lines493 The Request Object494 ``````````````````495 496 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 of497+it here in detail (see :class:`~flask.Request`). Here is a broad overview of498 some of the most common operations. First of all you have to import it from543-the `flask` module::499+the ``flask`` module::500 501 from flask import request502 503 The current request method is available by using the548-:attr:`~flask.request.method` attribute. To access form data (data504+:attr:`~flask.Request.method` attribute. To access form data (data505 transmitted in a ``POST`` or ``PUT`` request) you can use the550-:attr:`~flask.request.form` attribute. Here is a full example of the two506+:attr:`~flask.Request.form` attribute. Here is a full example of the two507 attributes mentioned above::508 509 @app.route('/login', methods=['POST', 'GET'])510 def login():7 unmodified lines518 # the code below is executed if the request method519 # was GET or the credentials were invalid520 return render_template('login.html', error=error)521 566-What happens if the key does not exist in the `form` attribute? In that522+What happens if the key does not exist in the ``form`` attribute? In that523 case a special :exc:`KeyError` is raised. You can catch it like a524 standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request525 error page is shown instead. So for many situations you don't have to526 deal with that problem.527 528 To access parameters submitted in the URL (``?key=value``) you can use the573-:attr:`~flask.request.args` attribute::529+:attr:`~flask.Request.args` attribute::530 531 searchword = request.args.get('key', '')532 533 We recommend accessing URL parameters with `get` or by catching the534 :exc:`KeyError` because users might change the URL and presenting them a 400535 bad request page in that case is not user friendly.536 537 For a full list of methods and attributes of the request object, head over582-to the :class:`~flask.request` documentation.538+to the :class:`~flask.Request` documentation.539 540 541 File Uploads542 ````````````137 unmodified lines680 default parameters.681 3. If a tuple is returned the items in the tuple can provide extra682 information. Such tuples have to be in the form ``(response, status,683 headers)`` or ``(response, headers)`` where at least one item has728- to be in the tuple. The `status` value will override the status code729- and `headers` can be a list or dictionary of additional header values.684+ to be in the tuple. The ``status`` value will override the status code685+ and ``headers`` can be a list or dictionary of additional header values.686 4. If none of that works, Flask will assume the return value is a687 valid WSGI application and convert that into a response object.688 689 If you want to get hold of the resulting response object inside the view690 you can use the :func:`~flask.make_response` function.691 736-Imagine you have a view like this:692+Imagine you have a view like this::693 738-.. sourcecode:: python739-694 @app.errorhandler(404)695 def not_found(error):696 return render_template('error.html'), 404697 698 You just need to wrap the return expression with699 :func:`~flask.make_response` and get the response object to modify it, then746-return it:700+return it::701 748-.. sourcecode:: python749-702 @app.errorhandler(404)703 def not_found(error):704 resp = make_response(render_template('error.html'), 404)705 resp.headers['X-Something'] = 'A value'29 unmodified lines735 if request.method == 'POST':736 session['username'] = request.form['username']737 return redirect(url_for('index'))738 return '''787- <form action="" method="post">739+ <form method="post">740 <p><input type=text name=username>741 <p><input type=submit value=Login>742 </form>743 '''14 unmodified lines758 759 The problem with random is that it's hard to judge what is truly random. And760 a secret key should be as random as possible. Your operating system761 has ways to generate pretty random stuff based on a cryptographic810- random generator which can be used to get such a key:762+ random generator which can be used to get such a key::763 812- >>> import os813- >>> os.urandom(24)814- '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'764+ >>> import os765+ >>> os.urandom(24)766+ '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'767 816- Just take that thing and copy/paste it into your code and you're done.768+ Just take that thing and copy/paste it into your code and you're done.769 770 A note on cookie-based sessions: Flask will take the values you put into the771 session object and serialize them into a cookie. If you are finding some772 values do not persist across requests, cookies are indeed enabled, and you are773 not getting a clear error message, check the size of the cookie in your page774 responses compared to the size supported by web browsers.775 776+Besides the default client-side based sessions, if you want to handle777+sessions on the server-side instead, there are several778+Flask extensions that support this.779 780 Message Flashing781 ----------------782 67 unmodified linesmodified:docs/reqcontext.rst+8 added-7 removed
117 unmodified lines118 unhandled exception down the road or if a before-request handler was119 not executed yet or at all (for example in test environments sometimes120 you might want to not execute before-request callbacks).121 122-Now what happens on errors? In production mode if an exception is not123-caught, the 500 internal server handler is called. In development mode124-however the exception is not further processed and bubbles up to the WSGI122+Now what happens on errors? If you are not in debug mode and an exception is not 123+caught, the 500 internal server handler is called. In debug mode 124+however the exception is not further processed and bubbles up to the WSGI 125 server. That way things like the interactive debugger can provide helpful126 debug information.127 128 An important change in 0.7 is that the internal server error is now no84 unmodified lines213 214 Starting with Flask 0.7 you have finer control over that behavior by215 setting the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable. By216 default it's linked to the setting of ``DEBUG``. If the application is in217-debug mode the context is preserved, in production mode it's not.217+debug mode the context is preserved. If debug mode is set to off, the context218+is not preserved.219 219-Do not force activate ``PRESERVE_CONTEXT_ON_EXCEPTION`` in production mode220-as it will cause your application to leak memory on exceptions. However220+Do not force activate ``PRESERVE_CONTEXT_ON_EXCEPTION`` if debug mode is set to off221+as it will cause your application to leak memory on exceptions. However,222 it can be useful during development to get the same error preserving222-behavior as in development mode when attempting to debug an error that223+behavior as debug mode when attempting to debug an error that224 only occurs under production settings.modified:docs/security.rst+119 added-4 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 be14 unmodified lines37 either double or single quotes when using Jinja expressions in them:38 39 .. sourcecode:: html+jinja40 41- <a href="{{ href }}">the text</a>41+ <input value="{{ value }}">42 43 Why is this necessary? Because if you would not be doing that, an44 attacker could easily inject custom JavaScript handlers. For example an45 attacker could inject this piece of HTML+JavaScript:46 47 .. sourcecode:: html48 49- onmouseover=alert(document.cookie)49+ onmouseover=alert(document.cookie)50 51-When the user would then move with the mouse over the link, the cookie51+When the user would then move with the mouse over the input, the cookie52 would be presented to the user in an alert window. But instead of showing53 the cookie to the user, a good attacker might also execute any other54 JavaScript code. In combination with CSS injections the attacker might55 even make the element fill out the entire page so that the user would56 just have to have the mouse anywhere on the page to trigger the attack.57 58+There is one class of XSS issues that Jinja's escaping does not protect59+against. The ``a`` tag's ``href`` attribute can contain a `javascript:` URI,60+which the browser will execute when clicked if not secured properly.61+62+.. sourcecode:: html63+64+ <a href="{{ value }}">click here</a>65+ <a href="javascript:alert('unsafe');">click here</a>66+67+To prevent this, you'll need to set the :ref:`security-csp` response header.68+69 Cross-Site Request Forgery (CSRF)70 ---------------------------------71 72 Another big problem is CSRF. This is a very complex topic and I won't41 unmodified lines114 vulnerabilities115 <https://github.com/pallets/flask/issues/248#issuecomment-59934857>`_, so116 this behavior was changed and :func:`~flask.jsonify` now supports serializing117 arrays.118+119+Security Headers120+----------------121+122+Browsers recognize various response headers in order to control security. We123+recommend reviewing each of the headers below for use in your application.124+The `Flask-Talisman`_ extension can be used to manage HTTPS and the security125+headers for you.126+127+.. _Flask-Talisman: https://github.com/GoogleCloudPlatform/flask-talisman128+129+HTTP Strict Transport Security (HSTS)130+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~131+132+Tells the browser to convert all HTTP requests to HTTPS, preventing133+man-in-the-middle (MITM) attacks. ::134+135+ response.haders['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'136+137+- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security138+139+.. _security-csp:140+141+Content Security Policy (CSP)142+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~143+144+Tell the browser where it can load various types of resource from. This header145+should be used whenever possible, but requires some work to define the correct146+policy for your site. A very strict policy would be::147+148+ response.headers['Content-Security-Policy'] = "default-src 'self'"149+150+- https://csp.withgoogle.com/docs/index.html151+- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy152+153+X-Content-Type-Options154+~~~~~~~~~~~~~~~~~~~~~~155+156+Forces the browser to honor the response content type instead of trying to157+detect it, which can be abused to generate a cross-site scripting (XSS)158+attack. ::159+160+ response.headers['X-Content-Type-Options'] = 'nosniff'161+162+- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options163+164+X-Frame-Options165+~~~~~~~~~~~~~~~166+167+Prevents external sites from embedding your site in an ``iframe``. This168+prevents a class of attacks where clicks in the outer frame can be translated169+invisibly to clicks on your page's elements. This is also known as170+"clickjacking". ::171+172+ response.headers['X-Frame-Options'] = 'SAMEORIGIN'173+174+- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options175+176+X-XSS-Protection177+~~~~~~~~~~~~~~~~178+179+The browser will try to prevent reflected XSS attacks by not loading the page180+if the request contains something that looks like JavaScript and the response181+contains the same data. ::182+183+ response.headers['X-XSS-Protection'] = '1; mode=block'184+185+- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection186+187+Set-Cookie options188+~~~~~~~~~~~~~~~~~~189+190+These options can be added to a ``Set-Cookie`` header to improve their191+security. Flask has configuration options to set these on the session cookie.192+They can be set on other cookies too.193+194+- ``Secure`` limits cookies to HTTPS traffic only.195+- ``HttpOnly`` protects the contents of cookies from being read with196+ JavaScript.197+- ``SameSite`` ensures that cookies can only be requested from the same198+ domain that created them. It is not supported by Flask yet.199+200+::201+202+ app.config.update(203+ SESSION_COOKIE_SECURE=True,204+ SESSION_COOKIE_HTTPONLY=True,205+ )206+207+ response.set_cookie('username', 'flask', secure=True, httponly=True)208+209+- https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Secure_and_HttpOnly_cookies210+211+HTTP Public Key Pinning (HPKP)212+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~213+214+This tells the browser to authenticate with the server using only the specific215+certificate key to prevent MITM attacks.216+217+.. warning::218+ Be careful when enabling this, as it is very difficult to undo if you set up219+ or upgrade your key incorrectly.220+221+- https://developer.mozilla.org/en-US/docs/Web/HTTP/Public_Key_Pinningmodified:docs/signals.rst+2 added-2 removed
25 unmodified lines26 executed in undefined order and do not modify any data.27 28 The big advantage of signals over handlers is that you can safely29 subscribe to them for just a split second. These temporary30-subscriptions are helpful for unittesting for example. Say you want to30+subscriptions are helpful for unit testing for example. Say you want to31 know what templates were rendered as part of a request: signals allow you32 to do exactly that.33 34 Subscribing to Signals9 unmodified lines44 signal. When you subscribe to a signal, be sure to also provide a sender45 unless you really want to listen for signals from all applications. This is46 especially true if you are developing an extension.47 48-For example, here is a helper context manager that can be used in a unittest48+For example, here is a helper context manager that can be used in a unit test49 to determine which templates were rendered and what variables were passed50 to the template::51 52 from flask import template_rendered138 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/templating.rst+2 added
1+.. _templates:2+3 Templates4 =========5 6 Flask leverages Jinja2 as template engine. You are obviously free to use221 unmodified linesmodified:docs/testing.rst+146 added-93 removed
3 unmodified lines4 ==========================5 6 **Something that is untested is broken.**7 8-The origin of this quote is unknown and while it is not entirely correct, it is also9-not far from the truth. Untested applications make it hard to8+The origin of this quote is unknown and while it is not entirely correct, it9+is also not far from the truth. Untested applications make it hard to10 improve existing code and developers of untested applications tend to11 become pretty paranoid. If an application has automated tests, you can12 safely make changes and instantly know if anything breaks.13 14 Flask provides a way to test your application by exposing the Werkzeug15 test :class:`~werkzeug.test.Client` and handling the context locals for you.16-You can then use that with your favourite testing solution. In this documentation17-we will use the :mod:`unittest` package that comes pre-installed with Python.16+You can then use that with your favourite testing solution.17 18+In this documentation we will use the `pytest`_ package as the base19+framework for our tests. You can install it with ``pip``, like so::20+21+ pip install pytest22+23+.. _pytest:24+ https://pytest.org25+26 The Application27 ---------------28 29 First, we need an application to test; we will use the application from30 the :ref:`tutorial`. If you don't have that application yet, get the24-sources from `the examples`_.31+source code from `the examples`_.32 33 .. _the examples:34 https://github.com/pallets/flask/tree/master/examples/flaskr/35 36 The Testing Skeleton37 --------------------38 32-In order to test the application, we add a second module33-(:file:`flaskr_tests.py`) and create a unittest skeleton there::39+We begin by adding a tests directory under the application root. Then40+create a Python file to store our tests (:file:`test_flaskr.py`). When we41+format the filename like ``test_*.py``, it will be auto-discoverable by42+pytest.43 44+Next, we create a `pytest fixture`_ called45+:func:`client` that configures46+the application for testing and initializes a new database.::47+48 import os36- import flaskr37- import unittest49 import tempfile50 40- class FlaskrTestCase(unittest.TestCase):51+ import pytest52 42- def setUp(self):43- self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()44- flaskr.app.config['TESTING'] = True45- self.app = flaskr.app.test_client()46- with flaskr.app.app_context():47- flaskr.init_db()53+ from flaskr import flaskr54 49- def tearDown(self):50- os.close(self.db_fd)51- os.unlink(flaskr.app.config['DATABASE'])55 53- if __name__ == '__main__':54- unittest.main()56+ @pytest.fixture57+ def client():58+ db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()59+ flaskr.app.config['TESTING'] = True60+ client = flaskr.app.test_client()61 56-The code in the :meth:`~unittest.TestCase.setUp` method creates a new test57-client and initializes a new database. This function is called before58-each individual test function is run. To delete the database after the59-test, we close the file and remove it from the filesystem in the60-:meth:`~unittest.TestCase.tearDown` method. Additionally during setup the61-``TESTING`` config flag is activated. What it does is disable the error62-catching during request handling so that you get better error reports when63-performing test requests against the application.62+ with flaskr.app.app_context():63+ flaskr.init_db()64 65-This test client will give us a simple interface to the application. We can66-trigger test requests to the application, and the client will also keep track67-of cookies for us.65+ yield client66 67+ os.close(db_fd)68+ os.unlink(flaskr.app.config['DATABASE'])69+70+This client fixture will be called by each individual test. It gives us a71+simple interface to the application, where we can trigger test requests to the72+application. The client will also keep track of cookies for us.73+74+During setup, the ``TESTING`` config flag is activated. What75+this does is disable error catching during request handling, so that76+you get better error reports when performing test requests against the77+application.78+69-Because SQLite3 is filesystem-based we can easily use the tempfile module79+Because SQLite3 is filesystem-based, we can easily use the :mod:`tempfile` module80 to create a temporary database and initialize it. The81 :func:`~tempfile.mkstemp` function does two things for us: it returns a82 low-level file handle and a random file name, the latter we use as83 database name. We just have to keep the `db_fd` around so that we can use84 the :func:`os.close` function to close the file.85 86+To delete the database after the test, the fixture closes the file and removes87+it from the filesystem.88+89 If we now run the test suite, we should see the following output::90 78- $ python flaskr_tests.py91+ $ pytest92 80- ----------------------------------------------------------------------81- Ran 0 tests in 0.000s93+ ================ test session starts ================94+ rootdir: ./flask/examples/flaskr, inifile: setup.cfg95+ collected 0 items96 83- OK97+ =========== no tests ran in 0.07 seconds ============98 85-Even though it did not run any actual tests, we already know that our flaskr99+Even though it did not run any actual tests, we already know that our ``flaskr``100 application is syntactically valid, otherwise the import would have died101 with an exception.102 103+.. _pytest fixture:104+ https://docs.pytest.org/en/latest/fixture.html105+106 The First Test107 --------------108 109 Now it's time to start testing the functionality of the application.110 Let's check that the application shows "No entries here so far" if we94-access the root of the application (``/``). To do this, we add a new95-test method to our class, like this::111+access the root of the application (``/``). To do this, we add a new112+test function to :file:`test_flaskr.py`, like this::113 97- class FlaskrTestCase(unittest.TestCase):114+ def test_empty_db(client):115+ """Start with a blank database."""116 99- def setUp(self):100- self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()101- self.app = flaskr.app.test_client()102- flaskr.init_db()117+ rv = client.get('/')118+ assert b'No entries here so far' in rv.data119 104- def tearDown(self):105- os.close(self.db_fd)106- os.unlink(flaskr.app.config['DATABASE'])107-108- def test_empty_db(self):109- rv = self.app.get('/')110- assert b'No entries here so far' in rv.data111-120 Notice that our test functions begin with the word `test`; this allows113-:mod:`unittest` to automatically identify the method as a test to run.121+`pytest`_ to automatically identify the function as a test to run.122 115-By using `self.app.get` we can send an HTTP ``GET`` request to the application with123+By using ``client.get`` we can send an HTTP ``GET`` request to the application with124 the given path. The return value will be a :class:`~flask.Flask.response_class` object.125 We can now use the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect126 the return value (as string) from the application. In this case, we ensure that127 ``'No entries here so far'`` is part of the output.128 129 Run it again and you should see one passing test::130 123- $ python flaskr_tests.py124- .125- ----------------------------------------------------------------------126- Ran 1 test in 0.034s131+ $ pytest -v132 128- OK133+ ================ test session starts ================134+ rootdir: ./flask/examples/flaskr, inifile: setup.cfg135+ collected 1 items136 137+ tests/test_flaskr.py::test_empty_db PASSED138+139+ ============= 1 passed in 0.10 seconds ==============140+141 Logging In and Out142 ------------------143 144 The majority of the functionality of our application is only available for1 unmodified line146 of the application. To do this, we fire some requests to the login and logout147 pages with the required form data (username and password). And because the148 login and logout pages redirect, we tell the client to `follow_redirects`.149 139-Add the following two methods to your `FlaskrTestCase` class::150+Add the following two functions to your :file:`test_flaskr.py` file::151 141- def login(self, username, password):142- return self.app.post('/login', data=dict(143- username=username,144- password=password145- ), follow_redirects=True)152+ def login(client, username, password):153+ return client.post('/login', data=dict(154+ username=username,155+ password=password156+ ), follow_redirects=True)157 147- def logout(self):148- return self.app.get('/logout', follow_redirects=True)158 159+ def logout(client):160+ return client.get('/logout', follow_redirects=True)161+162 Now we can easily test that logging in and out works and that it fails with151-invalid credentials. Add this new test to the class::163+invalid credentials. Add this new test function::164 153- def test_login_logout(self):154- rv = self.login('admin', 'default')155- assert 'You were logged in' in rv.data156- rv = self.logout()157- assert 'You were logged out' in rv.data158- rv = self.login('adminx', 'default')159- assert 'Invalid username' in rv.data160- rv = self.login('admin', 'defaultx')161- assert 'Invalid password' in rv.data165+ def test_login_logout(client):166+ """Make sure login and logout works."""167 168+ rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])169+ assert b'You were logged in' in rv.data170+171+ rv = logout(client)172+ assert b'You were logged out' in rv.data173+174+ rv = login(client, flaskr.app.config['USERNAME'] + 'x', flaskr.app.config['PASSWORD'])175+ assert b'Invalid username' in rv.data176+177+ rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'] + 'x')178+ assert b'Invalid password' in rv.data179+180 Test Adding Messages181 --------------------182 166-We should also test that adding messages works. Add a new test method183+We should also test that adding messages works. Add a new test function184 like this::185 169- def test_messages(self):170- self.login('admin', 'default')171- rv = self.app.post('/add', data=dict(186+ def test_messages(client):187+ """Test that messages work."""188+189+ login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])190+ rv = client.post('/add', data=dict(191 title='<Hello>',192 text='<strong>HTML</strong> allowed here'193 ), follow_redirects=True)175- assert 'No entries here so far' not in rv.data176- assert '<Hello>' in rv.data177- assert '<strong>HTML</strong> allowed here' in rv.data194+ assert b'No entries here so far' not in rv.data195+ assert b'<Hello>' in rv.data196+ assert b'<strong>HTML</strong> allowed here' in rv.data197 198 Here we check that HTML is allowed in the text but not in the title,199 which is the intended behavior.200 201 Running that should now give us three passing tests::202 184- $ python flaskr_tests.py185- ...186- ----------------------------------------------------------------------187- Ran 3 tests in 0.332s203+ $ pytest -v204 189- OK205+ ================ test session starts ================206+ rootdir: ./flask/examples/flaskr, inifile: setup.cfg207+ collected 3 items208 209+ tests/test_flaskr.py::test_empty_db PASSED210+ tests/test_flaskr.py::test_login_logout PASSED211+ tests/test_flaskr.py::test_messages PASSED212+213+ ============= 3 passed in 0.23 seconds ==============214+215 For more complex tests with headers and status codes, check out the216 `MiniTwit Example`_ from the sources which contains a larger test217 suite.218 195-219 .. _MiniTwit Example:220 https://github.com/pallets/flask/tree/master/examples/minitwit/221 199-222 Other Testing Tricks223 --------------------224 225 Besides using the test client as shown above, there is also the3 unmodified lines229 :class:`~flask.g` and :class:`~flask.session` objects like in view230 functions. Here is a full example that demonstrates this approach::231 232 import flask211- 233+234 app = flask.Flask(__name__)235 236 with app.test_request_context('/?name=Peter'):237 assert flask.request.path == '/'136 unmodified lines374 375 Note that in this case you have to use the ``sess`` object instead of the376 :data:`flask.session` proxy. The object however itself will provide the377 same interface.378+379+380+Testing JSON APIs381+-----------------382+383+.. versionadded:: 1.0384+385+Flask has great support for JSON, and is a popular choice for building JSON386+APIs. Making requests with JSON data and examining JSON data in responses is387+very convenient::388+389+ from flask import request, jsonify390+391+ @app.route('/api/auth')392+ def auth():393+ json_data = request.get_json()394+ email = json_data['email']395+ password = json_data['password']396+ return jsonify(token=generate_token(email, password))397+398+ with app.test_client() as c:399+ rv = c.post('/api/auth', json={400+ 'username': 'flask', 'password': 'secret'401+ })402+ json_data = rv.get_json()403+ assert verify_token(email, json_data['token'])404+405+Passing the ``json`` argument in the test client methods sets the request data406+to the JSON-serialized object and sets the content type to407+``application/json``. You can get the JSON data from the request or response408+with ``get_json``.modified:docs/upgrading.rst+52 added-14 removed
12 unmodified lines13 This section of the documentation enumerates all the changes in Flask from14 release to release and how you can change your code to have a painless15 updating experience.16 17-If you want to use the :command:`easy_install` command to upgrade your Flask18-installation, make sure to pass it the :option:`-U` parameter::17+Use the :command:`pip` command to upgrade your existing Flask installation by18+providing the ``--upgrade`` parameter::19 20- $ easy_install -U Flask20+ $ pip install --upgrade Flask21 22-.. _upgrading-to-10:22+.. _upgrading-to-012:23 24+Version 0.1225+------------26+27+Changes to send_file28+````````````````````29+30+The ``filename`` is no longer automatically inferred from file-like objects.31+This means that the following code will no longer automatically have32+``X-Sendfile`` support, etag generation or MIME-type guessing::33+34+ response = send_file(open('/path/to/file.txt'))35+36+Any of the following is functionally equivalent::37+38+ fname = '/path/to/file.txt'39+40+ # Just pass the filepath directly41+ response = send_file(fname)42+43+ # Set the MIME-type and ETag explicitly44+ response = send_file(open(fname), mimetype='text/plain')45+ response.set_etag(...)46+47+ # Set `attachment_filename` for MIME-type guessing48+ # 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 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`` has57+been restricted. If Flask can't guess one or the user didn't provide one, the58+function fails if no filename information was provided.59+60+.. _upgrading-to-011:61+62 Version 0.1163 ------------64 65 0.11 is an odd release in the Flask release cycle because it was supposed1 unmodified line67 to the release we decided to push out a 0.11 release first with some68 changes removed to make the transition easier. If you have been tracking69 the master branch which was 1.0 you might see some unexpected changes.70 33-In case you did track the master branch you will notice that `flask --app`71+In case you did track the master branch you will notice that :command:`flask --app`72 is removed now. You need to use the environment variable to specify an73 application.74 75 Debugging29 unmodified lines105 106 The :func:`~flask.templating.render_template_string` function has changed to107 autoescape template variables by default. This better matches the behavior108 of :func:`~flask.templating.render_template`.71- 109+110 Extension imports111 `````````````````112 113 Extension imports of the form ``flask.ext.foo`` are deprecated, you should use28 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 108-.. _Flask-OldSessions: http://pythonhosted.org/Flask-OldSessions/146+.. _Flask-OldSessions: https://pythonhosted.org/Flask-OldSessions/147 148 Version 0.9149 -----------150 19 unmodified lines170 Version 0.8171 -----------172 173 Flask introduced a new session interface system. We also noticed that136-there was a naming collision between `flask.session` the module that174+there was a naming collision between ``flask.session`` the module that175 implements sessions and :data:`flask.session` which is the global session176 object. With that introduction we moved the implementation details for177 the session system into a new module called :mod:`flask.sessions`. If you178 used the previously undocumented session support we urge you to upgrade.18 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 163-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.30 unmodified lines236 Please note that deprecation warnings are disabled by default starting237 with Python 2.7. In order to see the deprecation warnings that might be238 emitted you have to enabled them with the :mod:`warnings` module.239 202-If you are working with windows and you lack the `patch` command line240+If you are working with windows and you lack the ``patch`` command line241 utility you can get it as part of various Unix runtime environments for242 windows including cygwin, msysgit or ming32. Also source control systems243 like svn, hg or git have builtin support for applying unified diffs as244 generated by the tool. Check the manual of your version control system108 unmodified lines353 that name but it might fail as this information could change at354 runtime.355 - Blueprints have an inverse behavior for :meth:`url_for`. Previously356 ``.foo`` told :meth:`url_for` that it should look for the endpoint319- `foo` on the application. Now it means “relative to current module”.357+ ``foo`` on the application. Now it means “relative to current module”.358 The script will inverse all calls to :meth:`url_for` automatically for359 you. It will do this in a very eager way so you might end up with360 some unnecessary leading dots in your code if you're not using361 modules.9 unmodified lines371 This means that you need to add another subfolder with the blueprint's372 name into that folder if you want :file:`blueprintname/template.html` as373 the template name.374 337-If you continue to use the `Module` object which is deprecated, Flask will375+If you continue to use the ``Module`` object which is deprecated, Flask will376 restore the previous behavior as good as possible. However we strongly377 recommend upgrading to the new blueprints as they provide a lot of useful378 improvement such as the ability to attach a blueprint multiple times,379 blueprint specific error handlers and a lot more.11 unmodified lines391 change the order.392 393 Another change that breaks backwards compatibility is that context394 processors will no longer override values passed directly to the template357-rendering function. If for example `request` is as variable passed395+rendering function. If for example ``request`` is as variable passed396 directly to the template, the default context processor will not override397 it with the current request object. This makes it easier to extend398 context processors later to inject additional variables without breaking399 existing template not expecting them.17 unmodified lines417 functionality might come back in future releases if there is demand418 for this feature. Removing support for this makes the Flask internal419 code easier to understand and fixes a couple of small issues that make420 debugging harder than necessary.383-- The `create_jinja_loader` function is gone. If you want to customize421+- The ``create_jinja_loader`` function is gone. If you want to customize422 the Jinja loader now, use the423 :meth:`~flask.Flask.create_jinja_environment` method instead.424 425 Version 0.447 unmodified linesadded:examples/flaskr/flaskr/blueprints/__init__.py
added:examples/flaskr/flaskr/blueprints/flaskr.py+85 added
1+# -*- coding: utf-8 -*-2+"""3+ Flaskr4+ ~~~~~~5+6+ A microblog example application written as Flask tutorial with7+ Flask and sqlite3.8+9+ :copyright: (c) 2015 by Armin Ronacher.10+ :license: BSD, see LICENSE for more details.11+"""12+13+from sqlite3 import dbapi2 as sqlite314+from flask import Blueprint, request, session, g, redirect, url_for, abort, \15+ render_template, flash, current_app16+17+18+# create our blueprint :)19+bp = Blueprint('flaskr', __name__)20+21+22+def connect_db():23+ """Connects to the specific database."""24+ rv = sqlite3.connect(current_app.config['DATABASE'])25+ rv.row_factory = sqlite3.Row26+ return rv27+28+29+def init_db():30+ """Initializes the database."""31+ db = get_db()32+ with current_app.open_resource('schema.sql', mode='r') as f:33+ db.cursor().executescript(f.read())34+ db.commit()35+36+37+def get_db():38+ """Opens a new database connection if there is none yet for the39+ current application context.40+ """41+ if not hasattr(g, 'sqlite_db'):42+ g.sqlite_db = connect_db()43+ return g.sqlite_db44+45+46+@bp.route('/')47+def show_entries():48+ db = get_db()49+ cur = db.execute('select title, text from entries order by id desc')50+ entries = cur.fetchall()51+ return render_template('show_entries.html', entries=entries)52+53+54+@bp.route('/add', methods=['POST'])55+def add_entry():56+ if not session.get('logged_in'):57+ abort(401)58+ db = get_db()59+ db.execute('insert into entries (title, text) values (?, ?)',60+ [request.form['title'], request.form['text']])61+ db.commit()62+ flash('New entry was successfully posted')63+ return redirect(url_for('flaskr.show_entries'))64+65+66+@bp.route('/login', methods=['GET', 'POST'])67+def login():68+ error = None69+ if request.method == 'POST':70+ if request.form['username'] != current_app.config['USERNAME']:71+ error = 'Invalid username'72+ elif request.form['password'] != current_app.config['PASSWORD']:73+ error = 'Invalid password'74+ else:75+ session['logged_in'] = True76+ flash('You were logged in')77+ return redirect(url_for('flaskr.show_entries'))78+ return render_template('login.html', error=error)79+80+81+@bp.route('/logout')82+def logout():83+ session.pop('logged_in', None)84+ flash('You were logged out')85+ return redirect(url_for('flaskr.show_entries'))added:examples/flaskr/flaskr/static/style.css+18 added
1+body { font-family: sans-serif; background: #eee; }2+a, h1, h2 { color: #377BA8; }3+h1, h2 { font-family: 'Georgia', serif; margin: 0; }4+h1 { border-bottom: 2px solid #eee; }5+h2 { font-size: 1.2em; }6+7+.page { margin: 2em auto; width: 35em; border: 5px solid #ccc;8+ padding: 0.8em; background: white; }9+.entries { list-style: none; margin: 0; padding: 0; }10+.entries li { margin: 0.8em 1.2em; }11+.entries li h2 { margin-left: -1em; }12+.add-entry { font-size: 0.9em; border-bottom: 1px solid #ccc; }13+.add-entry dl { font-weight: bold; }14+.metanav { text-align: right; font-size: 0.8em; padding: 0.3em;15+ margin-bottom: 1em; background: #fafafa; }16+.flash { background: #CEE5F5; padding: 0.5em;17+ border: 1px solid #AACBE2; }18+.error { background: #F0D6D6; padding: 0.5em; }added:examples/flaskr/flaskr/templates/layout.html+17 added
1+<!doctype html>2+<title>Flaskr</title>3+<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">4+<div class="page">5+ <h1>Flaskr</h1>6+ <div class="metanav">7+ {% if not session.logged_in %}8+ <a href="{{ url_for('flaskr.login') }}">log in</a>9+ {% else %}10+ <a href="{{ url_for('flaskr.logout') }}">log out</a>11+ {% endif %}12+ </div>13+ {% for message in get_flashed_messages() %}14+ <div class="flash">{{ message }}</div>15+ {% endfor %}16+ {% block body %}{% endblock %}17+</div>added:examples/flaskr/flaskr/templates/login.html+14 added
1+{% extends "layout.html" %}2+{% block body %}3+ <h2>Login</h2>4+ {% if error %}<p class="error"><strong>Error:</strong> {{ error }}{% endif %}5+ <form action="{{ url_for('flaskr.login') }}" method="post">6+ <dl>7+ <dt>Username:8+ <dd><input type="text" name="username">9+ <dt>Password:10+ <dd><input type="password" name="password">11+ <dd><input type="submit" value="Login">12+ </dl>13+ </form>14+{% endblock %}added:examples/flaskr/flaskr/templates/show_entries.html+21 added
1+{% extends "layout.html" %}2+{% block body %}3+ {% if session.logged_in %}4+ <form action="{{ url_for('flaskr.add_entry') }}" method="post" class="add-entry">5+ <dl>6+ <dt>Title:7+ <dd><input type="text" size="30" name="title">8+ <dt>Text:9+ <dd><textarea name="text" rows="5" cols="40"></textarea>10+ <dd><input type="submit" value="Share">11+ </dl>12+ </form>13+ {% endif %}14+ <ul class="entries">15+ {% for entry in entries %}16+ <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}</li>17+ {% else %}18+ <li><em>Unbelievable. No entries here so far</em></li>19+ {% endfor %}20+ </ul>21+{% endblock %}added:examples/flaskr/flaskr/__init__.py
added:examples/flaskr/flaskr/factory.py+64 added
1+# -*- coding: utf-8 -*-2+"""3+ Flaskr4+ ~~~~~~5+6+ A microblog example application written as Flask tutorial with7+ Flask and sqlite3.8+9+ :copyright: (c) 2015 by Armin Ronacher.10+ :license: BSD, see LICENSE for more details.11+"""12+13+import os14+from flask import Flask, g15+from werkzeug.utils import find_modules, import_string16+from flaskr.blueprints.flaskr import init_db17+18+19+def create_app(config=None):20+ app = Flask('flaskr')21+22+ app.config.update(dict(23+ DATABASE=os.path.join(app.root_path, 'flaskr.db'),24+ DEBUG=True,25+ SECRET_KEY='development key',26+ USERNAME='admin',27+ PASSWORD='default'28+ ))29+ app.config.update(config or {})30+ app.config.from_envvar('FLASKR_SETTINGS', silent=True)31+32+ register_blueprints(app)33+ register_cli(app)34+ register_teardowns(app)35+36+ return app37+38+39+def register_blueprints(app):40+ """Register all blueprint modules41+42+ Reference: Armin Ronacher, "Flask for Fun and for Profit" PyBay 2016.43+ """44+ for name in find_modules('flaskr.blueprints'):45+ mod = import_string(name)46+ if hasattr(mod, 'bp'):47+ app.register_blueprint(mod.bp)48+ return None49+50+51+def register_cli(app):52+ @app.cli.command('initdb')53+ def initdb_command():54+ """Creates the database tables."""55+ init_db()56+ print('Initialized the database.')57+58+59+def register_teardowns(app):60+ @app.teardown_appcontext61+ def close_db(error):62+ """Closes the database again at the end of the request."""63+ if hasattr(g, 'sqlite_db'):64+ g.sqlite_db.close()added:examples/flaskr/flaskr/schema.sql+6 added
1+drop table if exists entries;2+create table entries (3+ id integer primary key autoincrement,4+ title text not null,5+ 'text' text not null6+);deleted:examples/flaskr/static/style.css-18 removed
1-body { font-family: sans-serif; background: #eee; }2-a, h1, h2 { color: #377BA8; }3-h1, h2 { font-family: 'Georgia', serif; margin: 0; }4-h1 { border-bottom: 2px solid #eee; }5-h2 { font-size: 1.2em; }6-7-.page { margin: 2em auto; width: 35em; border: 5px solid #ccc;8- padding: 0.8em; background: white; }9-.entries { list-style: none; margin: 0; padding: 0; }10-.entries li { margin: 0.8em 1.2em; }11-.entries li h2 { margin-left: -1em; }12-.add-entry { font-size: 0.9em; border-bottom: 1px solid #ccc; }13-.add-entry dl { font-weight: bold; }14-.metanav { text-align: right; font-size: 0.8em; padding: 0.3em;15- margin-bottom: 1em; background: #fafafa; }16-.flash { background: #CEE5F5; padding: 0.5em;17- border: 1px solid #AACBE2; }18-.error { background: #F0D6D6; padding: 0.5em; }deleted:examples/flaskr/templates/layout.html-17 removed
1-<!doctype html>2-<title>Flaskr</title>3-<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">4-<div class="page">5- <h1>Flaskr</h1>6- <div class="metanav">7- {% if not session.logged_in %}8- <a href="{{ url_for('login') }}">log in</a>9- {% else %}10- <a href="{{ url_for('logout') }}">log out</a>11- {% endif %}12- </div>13- {% for message in get_flashed_messages() %}14- <div class="flash">{{ message }}</div>15- {% endfor %}16- {% block body %}{% endblock %}17-</div>deleted:examples/flaskr/templates/login.html-14 removed
1-{% extends "layout.html" %}2-{% block body %}3- <h2>Login</h2>4- {% if error %}<p class="error"><strong>Error:</strong> {{ error }}{% endif %}5- <form action="{{ url_for('login') }}" method="post">6- <dl>7- <dt>Username:8- <dd><input type="text" name="username">9- <dt>Password:10- <dd><input type="password" name="password">11- <dd><input type="submit" value="Login">12- </dl>13- </form>14-{% endblock %}deleted:examples/flaskr/templates/show_entries.html-21 removed
1-{% extends "layout.html" %}2-{% block body %}3- {% if session.logged_in %}4- <form action="{{ url_for('add_entry') }}" method="post" class="add-entry">5- <dl>6- <dt>Title:7- <dd><input type="text" size="30" name="title">8- <dt>Text:9- <dd><textarea name="text" rows="5" cols="40"></textarea>10- <dd><input type="submit" value="Share">11- </dl>12- </form>13- {% endif %}14- <ul class="entries">15- {% for entry in entries %}16- <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}17- {% else %}18- <li><em>Unbelievable. No entries here so far</em>19- {% endfor %}20- </ul>21-{% endblock %}added:examples/flaskr/tests/test_flaskr.py+91 added
1+# -*- coding: utf-8 -*-2+"""3+ Flaskr Tests4+ ~~~~~~~~~~~~5+6+ Tests the Flaskr application.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import os13+import tempfile14+import pytest15+from flaskr.factory import create_app16+from flaskr.blueprints.flaskr import init_db17+18+19+@pytest.fixture20+def app(request):21+22+ db_fd, temp_db_location = tempfile.mkstemp()23+ config = {24+ 'DATABASE': temp_db_location,25+ 'TESTING': True,26+ 'DB_FD': db_fd27+ }28+29+ app = create_app(config=config)30+31+ with app.app_context():32+ init_db()33+ yield app34+35+36+@pytest.fixture37+def client(request, app):38+39+ client = app.test_client()40+41+ def teardown():42+ os.close(app.config['DB_FD'])43+ os.unlink(app.config['DATABASE'])44+ request.addfinalizer(teardown)45+46+ return client47+48+49+def login(client, username, password):50+ return client.post('/login', data=dict(51+ username=username,52+ password=password53+ ), follow_redirects=True)54+55+56+def logout(client):57+ return client.get('/logout', follow_redirects=True)58+59+60+def test_empty_db(client):61+ """Start with a blank database."""62+ rv = client.get('/')63+ assert b'No entries here so far' in rv.data64+65+66+def test_login_logout(client, app):67+ """Make sure login and logout works"""68+ rv = login(client, app.config['USERNAME'],69+ app.config['PASSWORD'])70+ assert b'You were logged in' in rv.data71+ rv = logout(client)72+ assert b'You were logged out' in rv.data73+ rv = login(client,app.config['USERNAME'] + 'x',74+ app.config['PASSWORD'])75+ assert b'Invalid username' in rv.data76+ rv = login(client, app.config['USERNAME'],77+ app.config['PASSWORD'] + 'x')78+ assert b'Invalid password' in rv.data79+80+81+def test_messages(client, app):82+ """Test that messages work"""83+ login(client, app.config['USERNAME'],84+ app.config['PASSWORD'])85+ rv = client.post('/add', data=dict(86+ title='<Hello>',87+ text='<strong>HTML</strong> allowed here'88+ ), follow_redirects=True)89+ assert b'No entries here so far' not in rv.data90+ assert b'<Hello>' in rv.data91+ assert b'<strong>HTML</strong> allowed here' in rv.datamodified:examples/flaskr/.gitignore+1 added
1 flaskr.db2+.eggs/deleted:examples/flaskr/flaskr.py-110 removed
1-# -*- coding: utf-8 -*-2-"""3- Flaskr4- ~~~~~~5-6- A microblog example application written as Flask tutorial with7- Flask and sqlite3.8-9- :copyright: (c) 2015 by Armin Ronacher.10- :license: BSD, see LICENSE for more details.11-"""12-13-import os14-from sqlite3 import dbapi2 as sqlite315-from flask import Flask, request, session, g, redirect, url_for, abort, \16- render_template, flash17-18-19-# create our little application :)20-app = Flask(__name__)21-22-# Load default config and override config from an environment variable23-app.config.update(dict(24- DATABASE=os.path.join(app.root_path, 'flaskr.db'),25- DEBUG=True,26- SECRET_KEY='development key',27- USERNAME='admin',28- PASSWORD='default'29-))30-app.config.from_envvar('FLASKR_SETTINGS', silent=True)31-32-33-def connect_db():34- """Connects to the specific database."""35- rv = sqlite3.connect(app.config['DATABASE'])36- rv.row_factory = sqlite3.Row37- return rv38-39-40-def init_db():41- """Initializes the database."""42- db = get_db()43- with app.open_resource('schema.sql', mode='r') as f:44- db.cursor().executescript(f.read())45- db.commit()46-47-48-@app.cli.command('initdb')49-def initdb_command():50- """Creates the database tables."""51- init_db()52- print('Initialized the database.')53-54-55-def get_db():56- """Opens a new database connection if there is none yet for the57- current application context.58- """59- if not hasattr(g, 'sqlite_db'):60- g.sqlite_db = connect_db()61- return g.sqlite_db62-63-64-@app.teardown_appcontext65-def close_db(error):66- """Closes the database again at the end of the request."""67- if hasattr(g, 'sqlite_db'):68- g.sqlite_db.close()69-70-71-@app.route('/')72-def show_entries():73- db = get_db()74- cur = db.execute('select title, text from entries order by id desc')75- entries = cur.fetchall()76- return render_template('show_entries.html', entries=entries)77-78-79-@app.route('/add', methods=['POST'])80-def add_entry():81- if not session.get('logged_in'):82- abort(401)83- db = get_db()84- db.execute('insert into entries (title, text) values (?, ?)',85- [request.form['title'], request.form['text']])86- db.commit()87- flash('New entry was successfully posted')88- return redirect(url_for('show_entries'))89-90-91-@app.route('/login', methods=['GET', 'POST'])92-def login():93- error = None94- if request.method == 'POST':95- if request.form['username'] != app.config['USERNAME']:96- error = 'Invalid username'97- elif request.form['password'] != app.config['PASSWORD']:98- error = 'Invalid password'99- else:100- session['logged_in'] = True101- flash('You were logged in')102- return redirect(url_for('show_entries'))103- return render_template('login.html', error=error)104-105-106-@app.route('/logout')107-def logout():108- session.pop('logged_in', None)109- flash('You were logged out')110- return redirect(url_for('show_entries'))added:examples/flaskr/MANIFEST.in+3 added
1+graft flaskr/templates2+graft flaskr/static3+include flaskr/schema.sqlmodified:examples/flaskr/README+13 added-7 removed
7 unmodified lines8 A sqlite powered thumble blog application9 10 ~ How do I use it?11 12- 1. edit the configuration in the flaskr.py file or12+ 1. edit the configuration in the factory.py file or13 export an FLASKR_SETTINGS environment variable14- pointing to a configuration file.14+ pointing to a configuration file or pass in a15+ dictionary with config values using the create_app16+ function.17 16- 2. Instruct flask to use the right application18+ 2. install the app from the root of the project directory19 18- export FLASK_APP=flaskr20+ pip install --editable .21 20- 3. initialize the database with this command:22+ 3. Instruct flask to use the right application23 24+ export FLASK_APP=flaskr.factory:create_app()25+26+ 4. initialize the database with this command:27+28 flask initdb29 24- 4. now you can run flaskr:30+ 5. now you can run flaskr:31 32 flask run33 34 the application will greet you on35 http://localhost:5000/36 37 ~ Is it tested?38 33- You betcha. Run the `test_flaskr.py` file to see39+ You betcha. Run `python setup.py test` to see40 the tests pass.deleted:examples/flaskr/schema.sql-6 removed
1-drop table if exists entries;2-create table entries (3- id integer primary key autoincrement,4- title text not null,5- 'text' text not null6-);added:examples/flaskr/setup.cfg+2 added
1+[aliases]2+test=pytestadded:examples/flaskr/setup.py+27 added
1+# -*- coding: utf-8 -*-2+"""3+ Flaskr Tests4+ ~~~~~~~~~~~~5+6+ Tests the Flaskr application.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+from setuptools import setup, find_packages13+14+setup(15+ name='flaskr',16+ packages=find_packages(),17+ include_package_data=True,18+ install_requires=[19+ 'flask',20+ ],21+ setup_requires=[22+ 'pytest-runner',23+ ],24+ tests_require=[25+ 'pytest',26+ ],27+)deleted:examples/flaskr/test_flaskr.py-77 removed
1-# -*- coding: utf-8 -*-2-"""3- Flaskr Tests4- ~~~~~~~~~~~~5-6- Tests the Flaskr application.7-8- :copyright: (c) 2015 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-12-import pytest13-14-import os15-import flaskr16-import tempfile17-18-19-@pytest.fixture20-def client(request):21- db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()22- flaskr.app.config['TESTING'] = True23- client = flaskr.app.test_client()24- with flaskr.app.app_context():25- flaskr.init_db()26-27- def teardown():28- os.close(db_fd)29- os.unlink(flaskr.app.config['DATABASE'])30- request.addfinalizer(teardown)31-32- return client33-34-35-def login(client, username, password):36- return client.post('/login', data=dict(37- username=username,38- password=password39- ), follow_redirects=True)40-41-42-def logout(client):43- return client.get('/logout', follow_redirects=True)44-45-46-def test_empty_db(client):47- """Start with a blank database."""48- rv = client.get('/')49- assert b'No entries here so far' in rv.data50-51-52-def test_login_logout(client):53- """Make sure login and logout works"""54- rv = login(client, flaskr.app.config['USERNAME'],55- flaskr.app.config['PASSWORD'])56- assert b'You were logged in' in rv.data57- rv = logout(client)58- assert b'You were logged out' in rv.data59- rv = login(client, flaskr.app.config['USERNAME'] + 'x',60- flaskr.app.config['PASSWORD'])61- assert b'Invalid username' in rv.data62- rv = login(client, flaskr.app.config['USERNAME'],63- flaskr.app.config['PASSWORD'] + 'x')64- assert b'Invalid password' in rv.data65-66-67-def test_messages(client):68- """Test that messages work"""69- login(client, flaskr.app.config['USERNAME'],70- flaskr.app.config['PASSWORD'])71- rv = client.post('/add', data=dict(72- title='<Hello>',73- text='<strong>HTML</strong> allowed here'74- ), follow_redirects=True)75- assert b'No entries here so far' not in rv.data76- assert b'<Hello>' in rv.data77- assert b'<strong>HTML</strong> allowed here' in rv.dataadded:examples/minitwit/minitwit/static/style.css+178 added
1+body {2+ background: #CAECE9;3+ font-family: 'Trebuchet MS', sans-serif;4+ font-size: 14px;5+}6+7+a {8+ color: #26776F;9+}10+11+a:hover {12+ color: #333;13+}14+15+input[type="text"],16+input[type="password"] {17+ background: white;18+ border: 1px solid #BFE6E2;19+ padding: 2px;20+ font-family: 'Trebuchet MS', sans-serif;21+ font-size: 14px;22+ -moz-border-radius: 2px;23+ -webkit-border-radius: 2px;24+ color: #105751;25+}26+27+input[type="submit"] {28+ background: #105751;29+ border: 1px solid #073B36;30+ padding: 1px 3px;31+ font-family: 'Trebuchet MS', sans-serif;32+ font-size: 14px;33+ font-weight: bold;34+ -moz-border-radius: 2px;35+ -webkit-border-radius: 2px;36+ color: white;37+}38+39+div.page {40+ background: white;41+ border: 1px solid #6ECCC4;42+ width: 700px;43+ margin: 30px auto;44+}45+46+div.page h1 {47+ background: #6ECCC4;48+ margin: 0;49+ padding: 10px 14px;50+ color: white;51+ letter-spacing: 1px;52+ text-shadow: 0 0 3px #24776F;53+ font-weight: normal;54+}55+56+div.page div.navigation {57+ background: #DEE9E8;58+ padding: 4px 10px;59+ border-top: 1px solid #ccc;60+ border-bottom: 1px solid #eee;61+ color: #888;62+ font-size: 12px;63+ letter-spacing: 0.5px;64+}65+66+div.page div.navigation a {67+ color: #444;68+ font-weight: bold;69+}70+71+div.page h2 {72+ margin: 0 0 15px 0;73+ color: #105751;74+ text-shadow: 0 1px 2px #ccc;75+}76+77+div.page div.body {78+ padding: 10px;79+}80+81+div.page div.footer {82+ background: #eee;83+ color: #888;84+ padding: 5px 10px;85+ font-size: 12px;86+}87+88+div.page div.followstatus {89+ border: 1px solid #ccc;90+ background: #E3EBEA;91+ -moz-border-radius: 2px;92+ -webkit-border-radius: 2px;93+ padding: 3px;94+ font-size: 13px;95+}96+97+div.page ul.messages {98+ list-style: none;99+ margin: 0;100+ padding: 0;101+}102+103+div.page ul.messages li {104+ margin: 10px 0;105+ padding: 5px;106+ background: #F0FAF9;107+ border: 1px solid #DBF3F1;108+ -moz-border-radius: 5px;109+ -webkit-border-radius: 5px;110+ min-height: 48px;111+}112+113+div.page ul.messages p {114+ margin: 0;115+}116+117+div.page ul.messages li img {118+ float: left;119+ padding: 0 10px 0 0;120+}121+122+div.page ul.messages li small {123+ font-size: 0.9em;124+ color: #888;125+}126+127+div.page div.twitbox {128+ margin: 10px 0;129+ padding: 5px;130+ background: #F0FAF9;131+ border: 1px solid #94E2DA;132+ -moz-border-radius: 5px;133+ -webkit-border-radius: 5px;134+}135+136+div.page div.twitbox h3 {137+ margin: 0;138+ font-size: 1em;139+ color: #2C7E76;140+}141+142+div.page div.twitbox p {143+ margin: 0;144+}145+146+div.page div.twitbox input[type="text"] {147+ width: 585px;148+}149+150+div.page div.twitbox input[type="submit"] {151+ width: 70px;152+ margin-left: 5px;153+}154+155+ul.flashes {156+ list-style: none;157+ margin: 10px 10px 0 10px;158+ padding: 0;159+}160+161+ul.flashes li {162+ background: #B9F3ED;163+ border: 1px solid #81CEC6;164+ -moz-border-radius: 2px;165+ -webkit-border-radius: 2px;166+ padding: 4px;167+ font-size: 13px;168+}169+170+div.error {171+ margin: 10px 0;172+ background: #FAE4E4;173+ border: 1px solid #DD6F6F;174+ -moz-border-radius: 2px;175+ -webkit-border-radius: 2px;176+ padding: 4px;177+ font-size: 13px;178+}added:examples/minitwit/minitwit/templates/layout.html+32 added
1+<!doctype html>2+<title>{% block title %}Welcome{% endblock %} | MiniTwit</title>3+<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">4+<div class="page">5+ <h1>MiniTwit</h1>6+ <div class="navigation">7+ {% if g.user %}8+ <a href="{{ url_for('timeline') }}">my timeline</a> |9+ <a href="{{ url_for('public_timeline') }}">public timeline</a> |10+ <a href="{{ url_for('logout') }}">sign out [{{ g.user.username }}]</a>11+ {% else %}12+ <a href="{{ url_for('public_timeline') }}">public timeline</a> |13+ <a href="{{ url_for('register') }}">sign up</a> |14+ <a href="{{ url_for('login') }}">sign in</a>15+ {% endif %}16+ </div>17+ {% with flashes = get_flashed_messages() %}18+ {% if flashes %}19+ <ul class="flashes">20+ {% for message in flashes %}21+ <li>{{ message }}22+ {% endfor %}23+ </ul>24+ {% endif %}25+ {% endwith %}26+ <div class="body">27+ {% block body %}{% endblock %}28+ </div>29+ <div class="footer">30+ MiniTwit — A Flask Application31+ </div>32+</div>added:examples/minitwit/minitwit/templates/login.html+16 added
1+{% extends "layout.html" %}2+{% block title %}Sign In{% endblock %}3+{% block body %}4+ <h2>Sign In</h2>5+ {% if error %}<div class="error"><strong>Error:</strong> {{ error }}</div>{% endif %}6+ <form action="" method="post">7+ <dl>8+ <dt>Username:9+ <dd><input type="text" name="username" size="30" value="{{ request.form.username }}">10+ <dt>Password:11+ <dd><input type="password" name="password" size="30">12+ </dl>13+ <div class="actions"><input type="submit" value="Sign In"></div>14+ </form>15+{% endblock %}16+added:examples/minitwit/minitwit/templates/register.html+19 added
1+{% extends "layout.html" %}2+{% block title %}Sign Up{% endblock %}3+{% block body %}4+ <h2>Sign Up</h2>5+ {% if error %}<div class="error"><strong>Error:</strong> {{ error }}</div>{% endif %}6+ <form action="" method="post">7+ <dl>8+ <dt>Username:9+ <dd><input type="text" name="username" size="30" value="{{ request.form.username }}">10+ <dt>E-Mail:11+ <dd><input type="text" name="email" size="30" value="{{ request.form.email }}">12+ <dt>Password:13+ <dd><input type="password" name="password" size="30">14+ <dt>Password <small>(repeat)</small>:15+ <dd><input type="password" name="password2" size="30">16+ </dl>17+ <div class="actions"><input type="submit" value="Sign Up"></div>18+ </form>19+{% endblock %}added:examples/minitwit/minitwit/templates/timeline.html+49 added
1+{% extends "layout.html" %}2+{% block title %}3+ {% if request.endpoint == 'public_timeline' %}4+ Public Timeline5+ {% elif request.endpoint == 'user_timeline' %}6+ {{ profile_user.username }}'s Timeline7+ {% else %}8+ My Timeline9+ {% endif %}10+{% endblock %}11+{% block body %}12+ <h2>{{ self.title() }}</h2>13+ {% if g.user %}14+ {% if request.endpoint == 'user_timeline' %}15+ <div class="followstatus">16+ {% if g.user.user_id == profile_user.user_id %}17+ This is you!18+ {% elif followed %}19+ You are currently following this user.20+ <a class="unfollow" href="{{ url_for('unfollow_user', username=profile_user.username)21+ }}">Unfollow user</a>.22+ {% else %}23+ You are not yet following this user.24+ <a class="follow" href="{{ url_for('follow_user', username=profile_user.username)25+ }}">Follow user</a>.26+ {% endif %}27+ </div>28+ {% elif request.endpoint == 'timeline' %}29+ <div class="twitbox">30+ <h3>What's on your mind {{ g.user.username }}?</h3>31+ <form action="{{ url_for('add_message') }}" method="post">32+ <p><input type="text" name="text" size="60"><!--33+ --><input type="submit" value="Share">34+ </form>35+ </div>36+ {% endif %}37+ {% endif %}38+ <ul class="messages">39+ {% for message in messages %}40+ <li><img src="{{ message.email|gravatar(size=48) }}"><p>41+ <strong><a href="{{ url_for('user_timeline', username=message.username)42+ }}">{{ message.username }}</a></strong>43+ {{ message.text }}44+ <small>— {{ message.pub_date|datetimeformat }}</small>45+ {% else %}46+ <li><em>There's no message so far.</em>47+ {% endfor %}48+ </ul>49+{% endblock %}added:examples/minitwit/minitwit/__init__.py+1 added
1+from .minitwit import appadded:examples/minitwit/minitwit/minitwit.py+256 added
1+# -*- coding: utf-8 -*-2+"""3+ MiniTwit4+ ~~~~~~~~5+6+ A microblogging application written with Flask and sqlite3.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import time13+from sqlite3 import dbapi2 as sqlite314+from hashlib import md515+from datetime import datetime16+from flask import Flask, request, session, url_for, redirect, \17+ render_template, abort, g, flash, _app_ctx_stack18+from werkzeug import check_password_hash, generate_password_hash19+20+21+# configuration22+DATABASE = '/tmp/minitwit.db'23+PER_PAGE = 3024+DEBUG = True25+SECRET_KEY = 'development key'26+27+# create our little application :)28+app = Flask('minitwit')29+app.config.from_object(__name__)30+app.config.from_envvar('MINITWIT_SETTINGS', silent=True)31+32+33+def get_db():34+ """Opens a new database connection if there is none yet for the35+ current application context.36+ """37+ top = _app_ctx_stack.top38+ if not hasattr(top, 'sqlite_db'):39+ top.sqlite_db = sqlite3.connect(app.config['DATABASE'])40+ top.sqlite_db.row_factory = sqlite3.Row41+ return top.sqlite_db42+43+44+@app.teardown_appcontext45+def close_database(exception):46+ """Closes the database again at the end of the request."""47+ top = _app_ctx_stack.top48+ if hasattr(top, 'sqlite_db'):49+ top.sqlite_db.close()50+51+52+def init_db():53+ """Initializes the database."""54+ db = get_db()55+ with app.open_resource('schema.sql', mode='r') as f:56+ db.cursor().executescript(f.read())57+ db.commit()58+59+60+@app.cli.command('initdb')61+def initdb_command():62+ """Creates the database tables."""63+ init_db()64+ print('Initialized the database.')65+66+67+def query_db(query, args=(), one=False):68+ """Queries the database and returns a list of dictionaries."""69+ cur = get_db().execute(query, args)70+ rv = cur.fetchall()71+ return (rv[0] if rv else None) if one else rv72+73+74+def get_user_id(username):75+ """Convenience method to look up the id for a username."""76+ rv = query_db('select user_id from user where username = ?',77+ [username], one=True)78+ return rv[0] if rv else None79+80+81+def format_datetime(timestamp):82+ """Format a timestamp for display."""83+ return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d @ %H:%M')84+85+86+def gravatar_url(email, size=80):87+ """Return the gravatar image for the given email address."""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_request93+def before_request():94+ g.user = None95+ if 'user_id' in session:96+ g.user = query_db('select * from user where user_id = ?',97+ [session['user_id']], one=True)98+99+100+@app.route('/')101+def timeline():102+ """Shows a users timeline or if no user is logged in it will103+ redirect to the public timeline. This timeline shows the user's104+ messages as well as all the messages of followed users.105+ """106+ if not g.user:107+ return redirect(url_for('public_timeline'))108+ return render_template('timeline.html', messages=query_db('''109+ select message.*, user.* from message, user110+ where message.author_id = user.user_id and (111+ user.user_id = ? or112+ user.user_id in (select whom_id from follower113+ where who_id = ?))114+ order by message.pub_date desc limit ?''',115+ [session['user_id'], session['user_id'], PER_PAGE]))116+117+118+@app.route('/public')119+def public_timeline():120+ """Displays the latest messages of all users."""121+ return render_template('timeline.html', messages=query_db('''122+ select message.*, user.* from message, user123+ where message.author_id = user.user_id124+ order by message.pub_date desc limit ?''', [PER_PAGE]))125+126+127+@app.route('/<username>')128+def user_timeline(username):129+ """Display's a users tweets."""130+ profile_user = query_db('select * from user where username = ?',131+ [username], one=True)132+ if profile_user is None:133+ abort(404)134+ followed = False135+ if g.user:136+ followed = query_db('''select 1 from follower where137+ follower.who_id = ? and follower.whom_id = ?''',138+ [session['user_id'], profile_user['user_id']],139+ one=True) is not None140+ return render_template('timeline.html', messages=query_db('''141+ select message.*, user.* from message, user where142+ user.user_id = message.author_id and user.user_id = ?143+ order by message.pub_date desc limit ?''',144+ [profile_user['user_id'], PER_PAGE]), followed=followed,145+ profile_user=profile_user)146+147+148+@app.route('/<username>/follow')149+def follow_user(username):150+ """Adds the current user as follower of the given user."""151+ if not g.user:152+ abort(401)153+ whom_id = get_user_id(username)154+ if whom_id is None:155+ abort(404)156+ db = get_db()157+ db.execute('insert into follower (who_id, whom_id) values (?, ?)',158+ [session['user_id'], whom_id])159+ db.commit()160+ flash('You are now following "%s"' % username)161+ return redirect(url_for('user_timeline', username=username))162+163+164+@app.route('/<username>/unfollow')165+def unfollow_user(username):166+ """Removes the current user as follower of the given user."""167+ if not g.user:168+ abort(401)169+ whom_id = get_user_id(username)170+ if whom_id is None:171+ abort(404)172+ db = get_db()173+ db.execute('delete from follower where who_id=? and whom_id=?',174+ [session['user_id'], whom_id])175+ db.commit()176+ flash('You are no longer following "%s"' % username)177+ return redirect(url_for('user_timeline', username=username))178+179+180+@app.route('/add_message', methods=['POST'])181+def add_message():182+ """Registers a new message for the user."""183+ if 'user_id' not in session:184+ abort(401)185+ if request.form['text']:186+ db = get_db()187+ db.execute('''insert into message (author_id, text, pub_date)188+ values (?, ?, ?)''', (session['user_id'], request.form['text'],189+ int(time.time())))190+ db.commit()191+ flash('Your message was recorded')192+ return redirect(url_for('timeline'))193+194+195+@app.route('/login', methods=['GET', 'POST'])196+def login():197+ """Logs the user in."""198+ if g.user:199+ return redirect(url_for('timeline'))200+ error = None201+ if request.method == 'POST':202+ user = query_db('''select * from user where203+ username = ?''', [request.form['username']], one=True)204+ if user is None:205+ error = 'Invalid username'206+ elif not check_password_hash(user['pw_hash'],207+ request.form['password']):208+ error = 'Invalid password'209+ else:210+ flash('You were logged in')211+ session['user_id'] = user['user_id']212+ return redirect(url_for('timeline'))213+ return render_template('login.html', error=error)214+215+216+@app.route('/register', methods=['GET', 'POST'])217+def register():218+ """Registers the user."""219+ if g.user:220+ return redirect(url_for('timeline'))221+ error = None222+ if request.method == 'POST':223+ if not request.form['username']:224+ error = 'You have to enter a username'225+ elif not request.form['email'] or \226+ '@' not in request.form['email']:227+ error = 'You have to enter a valid email address'228+ elif not request.form['password']:229+ error = 'You have to enter a password'230+ elif request.form['password'] != request.form['password2']:231+ error = 'The two passwords do not match'232+ elif get_user_id(request.form['username']) is not None:233+ error = 'The username is already taken'234+ else:235+ db = get_db()236+ db.execute('''insert into user (237+ username, email, pw_hash) values (?, ?, ?)''',238+ [request.form['username'], request.form['email'],239+ generate_password_hash(request.form['password'])])240+ db.commit()241+ flash('You were successfully registered and can login now')242+ return redirect(url_for('login'))243+ return render_template('register.html', error=error)244+245+246+@app.route('/logout')247+def logout():248+ """Logs the user out."""249+ flash('You were logged out')250+ session.pop('user_id', None)251+ return redirect(url_for('public_timeline'))252+253+254+# add some filters to jinja255+app.jinja_env.filters['datetimeformat'] = format_datetime256+app.jinja_env.filters['gravatar'] = gravatar_urladded:examples/minitwit/minitwit/schema.sql+21 added
1+drop table if exists user;2+create table user (3+ user_id integer primary key autoincrement,4+ username text not null,5+ email text not null,6+ pw_hash text not null7+);8+9+drop table if exists follower;10+create table follower (11+ who_id integer,12+ whom_id integer13+);14+15+drop table if exists message;16+create table message (17+ message_id integer primary key autoincrement,18+ author_id integer not null,19+ text text not null,20+ pub_date integer21+);deleted:examples/minitwit/static/style.css-178 removed
1-body {2- background: #CAECE9;3- font-family: 'Trebuchet MS', sans-serif;4- font-size: 14px;5-}6-7-a {8- color: #26776F;9-}10-11-a:hover {12- color: #333;13-}14-15-input[type="text"],16-input[type="password"] {17- background: white;18- border: 1px solid #BFE6E2;19- padding: 2px;20- font-family: 'Trebuchet MS', sans-serif;21- font-size: 14px;22- -moz-border-radius: 2px;23- -webkit-border-radius: 2px;24- color: #105751;25-}26-27-input[type="submit"] {28- background: #105751;29- border: 1px solid #073B36;30- padding: 1px 3px;31- font-family: 'Trebuchet MS', sans-serif;32- font-size: 14px;33- font-weight: bold;34- -moz-border-radius: 2px;35- -webkit-border-radius: 2px;36- color: white;37-}38-39-div.page {40- background: white;41- border: 1px solid #6ECCC4;42- width: 700px;43- margin: 30px auto;44-}45-46-div.page h1 {47- background: #6ECCC4;48- margin: 0;49- padding: 10px 14px;50- color: white;51- letter-spacing: 1px;52- text-shadow: 0 0 3px #24776F;53- font-weight: normal;54-}55-56-div.page div.navigation {57- background: #DEE9E8;58- padding: 4px 10px;59- border-top: 1px solid #ccc;60- border-bottom: 1px solid #eee;61- color: #888;62- font-size: 12px;63- letter-spacing: 0.5px;64-}65-66-div.page div.navigation a {67- color: #444;68- font-weight: bold;69-}70-71-div.page h2 {72- margin: 0 0 15px 0;73- color: #105751;74- text-shadow: 0 1px 2px #ccc;75-}76-77-div.page div.body {78- padding: 10px;79-}80-81-div.page div.footer {82- background: #eee;83- color: #888;84- padding: 5px 10px;85- font-size: 12px;86-}87-88-div.page div.followstatus {89- border: 1px solid #ccc;90- background: #E3EBEA;91- -moz-border-radius: 2px;92- -webkit-border-radius: 2px;93- padding: 3px;94- font-size: 13px;95-}96-97-div.page ul.messages {98- list-style: none;99- margin: 0;100- padding: 0;101-}102-103-div.page ul.messages li {104- margin: 10px 0;105- padding: 5px;106- background: #F0FAF9;107- border: 1px solid #DBF3F1;108- -moz-border-radius: 5px;109- -webkit-border-radius: 5px;110- min-height: 48px;111-}112-113-div.page ul.messages p {114- margin: 0;115-}116-117-div.page ul.messages li img {118- float: left;119- padding: 0 10px 0 0;120-}121-122-div.page ul.messages li small {123- font-size: 0.9em;124- color: #888;125-}126-127-div.page div.twitbox {128- margin: 10px 0;129- padding: 5px;130- background: #F0FAF9;131- border: 1px solid #94E2DA;132- -moz-border-radius: 5px;133- -webkit-border-radius: 5px;134-}135-136-div.page div.twitbox h3 {137- margin: 0;138- font-size: 1em;139- color: #2C7E76;140-}141-142-div.page div.twitbox p {143- margin: 0;144-}145-146-div.page div.twitbox input[type="text"] {147- width: 585px;148-}149-150-div.page div.twitbox input[type="submit"] {151- width: 70px;152- margin-left: 5px;153-}154-155-ul.flashes {156- list-style: none;157- margin: 10px 10px 0 10px;158- padding: 0;159-}160-161-ul.flashes li {162- background: #B9F3ED;163- border: 1px solid #81CEC6;164- -moz-border-radius: 2px;165- -webkit-border-radius: 2px;166- padding: 4px;167- font-size: 13px;168-}169-170-div.error {171- margin: 10px 0;172- background: #FAE4E4;173- border: 1px solid #DD6F6F;174- -moz-border-radius: 2px;175- -webkit-border-radius: 2px;176- padding: 4px;177- font-size: 13px;178-}deleted:examples/minitwit/templates/layout.html-32 removed
1-<!doctype html>2-<title>{% block title %}Welcome{% endblock %} | MiniTwit</title>3-<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">4-<div class="page">5- <h1>MiniTwit</h1>6- <div class="navigation">7- {% if g.user %}8- <a href="{{ url_for('timeline') }}">my timeline</a> |9- <a href="{{ url_for('public_timeline') }}">public timeline</a> |10- <a href="{{ url_for('logout') }}">sign out [{{ g.user.username }}]</a>11- {% else %}12- <a href="{{ url_for('public_timeline') }}">public timeline</a> |13- <a href="{{ url_for('register') }}">sign up</a> |14- <a href="{{ url_for('login') }}">sign in</a>15- {% endif %}16- </div>17- {% with flashes = get_flashed_messages() %}18- {% if flashes %}19- <ul class="flashes">20- {% for message in flashes %}21- <li>{{ message }}22- {% endfor %}23- </ul>24- {% endif %}25- {% endwith %}26- <div class="body">27- {% block body %}{% endblock %}28- </div>29- <div class="footer">30- MiniTwit — A Flask Application31- </div>32-</div>deleted:examples/minitwit/templates/login.html-16 removed
1-{% extends "layout.html" %}2-{% block title %}Sign In{% endblock %}3-{% block body %}4- <h2>Sign In</h2>5- {% if error %}<div class="error"><strong>Error:</strong> {{ error }}</div>{% endif %}6- <form action="" method="post">7- <dl>8- <dt>Username:9- <dd><input type="text" name="username" size="30" value="{{ request.form.username }}">10- <dt>Password:11- <dd><input type="password" name="password" size="30">12- </dl>13- <div class="actions"><input type="submit" value="Sign In"></div>14- </form>15-{% endblock %}16-deleted:examples/minitwit/templates/register.html-19 removed
1-{% extends "layout.html" %}2-{% block title %}Sign Up{% endblock %}3-{% block body %}4- <h2>Sign Up</h2>5- {% if error %}<div class="error"><strong>Error:</strong> {{ error }}</div>{% endif %}6- <form action="" method="post">7- <dl>8- <dt>Username:9- <dd><input type="text" name="username" size="30" value="{{ request.form.username }}">10- <dt>E-Mail:11- <dd><input type="text" name="email" size="30" value="{{ request.form.email }}">12- <dt>Password:13- <dd><input type="password" name="password" size="30">14- <dt>Password <small>(repeat)</small>:15- <dd><input type="password" name="password2" size="30">16- </dl>17- <div class="actions"><input type="submit" value="Sign Up"></div>18- </form>19-{% endblock %}deleted:examples/minitwit/templates/timeline.html-49 removed
1-{% extends "layout.html" %}2-{% block title %}3- {% if request.endpoint == 'public_timeline' %}4- Public Timeline5- {% elif request.endpoint == 'user_timeline' %}6- {{ profile_user.username }}'s Timeline7- {% else %}8- My Timeline9- {% endif %}10-{% endblock %}11-{% block body %}12- <h2>{{ self.title() }}</h2>13- {% if g.user %}14- {% if request.endpoint == 'user_timeline' %}15- <div class="followstatus">16- {% if g.user.user_id == profile_user.user_id %}17- This is you!18- {% elif followed %}19- You are currently following this user.20- <a class="unfollow" href="{{ url_for('unfollow_user', username=profile_user.username)21- }}">Unfollow user</a>.22- {% else %}23- You are not yet following this user.24- <a class="follow" href="{{ url_for('follow_user', username=profile_user.username)25- }}">Follow user</a>.26- {% endif %}27- </div>28- {% elif request.endpoint == 'timeline' %}29- <div class="twitbox">30- <h3>What's on your mind {{ g.user.username }}?</h3>31- <form action="{{ url_for('add_message') }}" method="post">32- <p><input type="text" name="text" size="60"><!--33- --><input type="submit" value="Share">34- </form>35- </div>36- {% endif %}37- {% endif %}38- <ul class="messages">39- {% for message in messages %}40- <li><img src="{{ message.email|gravatar(size=48) }}"><p>41- <strong><a href="{{ url_for('user_timeline', username=message.username)42- }}">{{ message.username }}</a></strong>43- {{ message.text }}44- <small>— {{ message.pub_date|datetimeformat }}</small>45- {% else %}46- <li><em>There's no message so far.</em>47- {% endfor %}48- </ul>49-{% endblock %}added:examples/minitwit/tests/test_minitwit.py+149 added
1+# -*- coding: utf-8 -*-2+"""3+ MiniTwit Tests4+ ~~~~~~~~~~~~~~5+6+ Tests the MiniTwit application.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+import os12+import tempfile13+import pytest14+from minitwit import minitwit15+16+17+@pytest.fixture18+def client():19+ db_fd, minitwit.app.config['DATABASE'] = tempfile.mkstemp()20+ client = minitwit.app.test_client()21+ with minitwit.app.app_context():22+ minitwit.init_db()23+24+ yield client25+26+ os.close(db_fd)27+ os.unlink(minitwit.app.config['DATABASE'])28+29+30+def register(client, username, password, password2=None, email=None):31+ """Helper function to register a user"""32+ if password2 is None:33+ password2 = password34+ if email is None:35+ email = username + '@example.com'36+ return client.post('/register', data={37+ 'username': username,38+ 'password': password,39+ 'password2': password2,40+ 'email': email,41+ }, follow_redirects=True)42+43+44+def login(client, username, password):45+ """Helper function to login"""46+ return client.post('/login', data={47+ 'username': username,48+ 'password': password49+ }, follow_redirects=True)50+51+52+def register_and_login(client, username, password):53+ """Registers and logs in in one go"""54+ register(client, username, password)55+ return login(client, username, password)56+57+58+def logout(client):59+ """Helper function to logout"""60+ return client.get('/logout', follow_redirects=True)61+62+63+def add_message(client, text):64+ """Records a message"""65+ rv = client.post('/add_message', data={'text': text},66+ follow_redirects=True)67+ if text:68+ assert b'Your message was recorded' in rv.data69+ return rv70+71+72+def test_register(client):73+ """Make sure registering works"""74+ rv = register(client, 'user1', 'default')75+ assert b'You were successfully registered ' \76+ b'and can login now' in rv.data77+ rv = register(client, 'user1', 'default')78+ assert b'The username is already taken' in rv.data79+ rv = register(client, '', 'default')80+ assert b'You have to enter a username' in rv.data81+ rv = register(client, 'meh', '')82+ assert b'You have to enter a password' in rv.data83+ rv = register(client, 'meh', 'x', 'y')84+ assert b'The two passwords do not match' in rv.data85+ rv = register(client, 'meh', 'foo', email='broken')86+ assert b'You have to enter a valid email address' in rv.data87+88+89+def test_login_logout(client):90+ """Make sure logging in and logging out works"""91+ rv = register_and_login(client, 'user1', 'default')92+ assert b'You were logged in' in rv.data93+ rv = logout(client)94+ assert b'You were logged out' in rv.data95+ rv = login(client, 'user1', 'wrongpassword')96+ assert b'Invalid password' in rv.data97+ rv = login(client, 'user2', 'wrongpassword')98+ assert b'Invalid username' in rv.data99+100+101+def test_message_recording(client):102+ """Check if adding messages works"""103+ register_and_login(client, 'foo', 'default')104+ add_message(client, 'test message 1')105+ add_message(client, '<test message 2>')106+ rv = client.get('/')107+ assert b'test message 1' in rv.data108+ assert b'<test message 2>' in rv.data109+110+111+def test_timelines(client):112+ """Make sure that timelines work"""113+ register_and_login(client, 'foo', 'default')114+ add_message(client, 'the message by foo')115+ logout(client)116+ register_and_login(client, 'bar', 'default')117+ add_message(client, 'the message by bar')118+ rv = client.get('/public')119+ assert b'the message by foo' in rv.data120+ assert b'the message by bar' in rv.data121+122+ # bar's timeline should just show bar's message123+ rv = client.get('/')124+ assert b'the message by foo' not in rv.data125+ assert b'the message by bar' in rv.data126+127+ # now let's follow foo128+ rv = client.get('/foo/follow', follow_redirects=True)129+ assert b'You are now following "foo"' in rv.data130+131+ # we should now see foo's message132+ rv = client.get('/')133+ assert b'the message by foo' in rv.data134+ assert b'the message by bar' in rv.data135+136+ # but on the user's page we only want the user's message137+ rv = client.get('/bar')138+ assert b'the message by foo' not in rv.data139+ assert b'the message by bar' in rv.data140+ rv = client.get('/foo')141+ assert b'the message by foo' in rv.data142+ assert b'the message by bar' not in rv.data143+144+ # now unfollow and check if that worked145+ rv = client.get('/foo/unfollow', follow_redirects=True)146+ assert b'You are no longer following "foo"' in rv.data147+ rv = client.get('/')148+ assert b'the message by foo' not in rv.data149+ assert b'the message by bar' in rv.dataadded:examples/minitwit/.gitignore+2 added
1+minitwit.db2+.eggs/added:examples/minitwit/MANIFEST.in+3 added
1+graft minitwit/templates2+graft minitwit/static3+include minitwit/schema.sqldeleted:examples/minitwit/minitwit.py-256 removed
1-# -*- coding: utf-8 -*-2-"""3- MiniTwit4- ~~~~~~~~5-6- A microblogging application written with Flask and sqlite3.7-8- :copyright: (c) 2015 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-12-import time13-from sqlite3 import dbapi2 as sqlite314-from hashlib import md515-from datetime import datetime16-from flask import Flask, request, session, url_for, redirect, \17- render_template, abort, g, flash, _app_ctx_stack18-from werkzeug import check_password_hash, generate_password_hash19-20-21-# configuration22-DATABASE = '/tmp/minitwit.db'23-PER_PAGE = 3024-DEBUG = True25-SECRET_KEY = 'development key'26-27-# create our little application :)28-app = Flask(__name__)29-app.config.from_object(__name__)30-app.config.from_envvar('MINITWIT_SETTINGS', silent=True)31-32-33-def get_db():34- """Opens a new database connection if there is none yet for the35- current application context.36- """37- top = _app_ctx_stack.top38- if not hasattr(top, 'sqlite_db'):39- top.sqlite_db = sqlite3.connect(app.config['DATABASE'])40- top.sqlite_db.row_factory = sqlite3.Row41- return top.sqlite_db42-43-44-@app.teardown_appcontext45-def close_database(exception):46- """Closes the database again at the end of the request."""47- top = _app_ctx_stack.top48- if hasattr(top, 'sqlite_db'):49- top.sqlite_db.close()50-51-52-def init_db():53- """Initializes the database."""54- db = get_db()55- with app.open_resource('schema.sql', mode='r') as f:56- db.cursor().executescript(f.read())57- db.commit()58-59-60-@app.cli.command('initdb')61-def initdb_command():62- """Creates the database tables."""63- init_db()64- print('Initialized the database.')65-66-67-def query_db(query, args=(), one=False):68- """Queries the database and returns a list of dictionaries."""69- cur = get_db().execute(query, args)70- rv = cur.fetchall()71- return (rv[0] if rv else None) if one else rv72-73-74-def get_user_id(username):75- """Convenience method to look up the id for a username."""76- rv = query_db('select user_id from user where username = ?',77- [username], one=True)78- return rv[0] if rv else None79-80-81-def format_datetime(timestamp):82- """Format a timestamp for display."""83- return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d @ %H:%M')84-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' % \89- (md5(email.strip().lower().encode('utf-8')).hexdigest(), size)90-91-92-@app.before_request93-def before_request():94- g.user = None95- if 'user_id' in session:96- g.user = query_db('select * from user where user_id = ?',97- [session['user_id']], one=True)98-99-100-@app.route('/')101-def timeline():102- """Shows a users timeline or if no user is logged in it will103- redirect to the public timeline. This timeline shows the user's104- messages as well as all the messages of followed users.105- """106- if not g.user:107- return redirect(url_for('public_timeline'))108- return render_template('timeline.html', messages=query_db('''109- select message.*, user.* from message, user110- where message.author_id = user.user_id and (111- user.user_id = ? or112- user.user_id in (select whom_id from follower113- where who_id = ?))114- order by message.pub_date desc limit ?''',115- [session['user_id'], session['user_id'], PER_PAGE]))116-117-118-@app.route('/public')119-def public_timeline():120- """Displays the latest messages of all users."""121- return render_template('timeline.html', messages=query_db('''122- select message.*, user.* from message, user123- where message.author_id = user.user_id124- order by message.pub_date desc limit ?''', [PER_PAGE]))125-126-127-@app.route('/<username>')128-def user_timeline(username):129- """Display's a users tweets."""130- profile_user = query_db('select * from user where username = ?',131- [username], one=True)132- if profile_user is None:133- abort(404)134- followed = False135- if g.user:136- followed = query_db('''select 1 from follower where137- follower.who_id = ? and follower.whom_id = ?''',138- [session['user_id'], profile_user['user_id']],139- one=True) is not None140- return render_template('timeline.html', messages=query_db('''141- select message.*, user.* from message, user where142- user.user_id = message.author_id and user.user_id = ?143- order by message.pub_date desc limit ?''',144- [profile_user['user_id'], PER_PAGE]), followed=followed,145- profile_user=profile_user)146-147-148-@app.route('/<username>/follow')149-def follow_user(username):150- """Adds the current user as follower of the given user."""151- if not g.user:152- abort(401)153- whom_id = get_user_id(username)154- if whom_id is None:155- abort(404)156- db = get_db()157- db.execute('insert into follower (who_id, whom_id) values (?, ?)',158- [session['user_id'], whom_id])159- db.commit()160- flash('You are now following "%s"' % username)161- return redirect(url_for('user_timeline', username=username))162-163-164-@app.route('/<username>/unfollow')165-def unfollow_user(username):166- """Removes the current user as follower of the given user."""167- if not g.user:168- abort(401)169- whom_id = get_user_id(username)170- if whom_id is None:171- abort(404)172- db = get_db()173- db.execute('delete from follower where who_id=? and whom_id=?',174- [session['user_id'], whom_id])175- db.commit()176- flash('You are no longer following "%s"' % username)177- return redirect(url_for('user_timeline', username=username))178-179-180-@app.route('/add_message', methods=['POST'])181-def add_message():182- """Registers a new message for the user."""183- if 'user_id' not in session:184- abort(401)185- if request.form['text']:186- db = get_db()187- db.execute('''insert into message (author_id, text, pub_date)188- values (?, ?, ?)''', (session['user_id'], request.form['text'],189- int(time.time())))190- db.commit()191- flash('Your message was recorded')192- return redirect(url_for('timeline'))193-194-195-@app.route('/login', methods=['GET', 'POST'])196-def login():197- """Logs the user in."""198- if g.user:199- return redirect(url_for('timeline'))200- error = None201- if request.method == 'POST':202- user = query_db('''select * from user where203- username = ?''', [request.form['username']], one=True)204- if user is None:205- error = 'Invalid username'206- elif not check_password_hash(user['pw_hash'],207- request.form['password']):208- error = 'Invalid password'209- else:210- flash('You were logged in')211- session['user_id'] = user['user_id']212- return redirect(url_for('timeline'))213- return render_template('login.html', error=error)214-215-216-@app.route('/register', methods=['GET', 'POST'])217-def register():218- """Registers the user."""219- if g.user:220- return redirect(url_for('timeline'))221- error = None222- if request.method == 'POST':223- if not request.form['username']:224- error = 'You have to enter a username'225- elif not request.form['email'] or \226- '@' not in request.form['email']:227- error = 'You have to enter a valid email address'228- elif not request.form['password']:229- error = 'You have to enter a password'230- elif request.form['password'] != request.form['password2']:231- error = 'The two passwords do not match'232- elif get_user_id(request.form['username']) is not None:233- error = 'The username is already taken'234- else:235- db = get_db()236- db.execute('''insert into user (237- username, email, pw_hash) values (?, ?, ?)''',238- [request.form['username'], request.form['email'],239- generate_password_hash(request.form['password'])])240- db.commit()241- flash('You were successfully registered and can login now')242- return redirect(url_for('login'))243- return render_template('register.html', error=error)244-245-246-@app.route('/logout')247-def logout():248- """Logs the user out."""249- flash('You were logged out')250- session.pop('user_id', None)251- return redirect(url_for('public_timeline'))252-253-254-# add some filters to jinja255-app.jinja_env.filters['datetimeformat'] = format_datetime256-app.jinja_env.filters['gravatar'] = gravatar_urlmodified:examples/minitwit/README+8 added-4 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 on34 http://localhost:5000/35 36 ~ Is it tested?37 34- You betcha. Run the `test_minitwit.py` file to38+ You betcha. Run the `python setup.py test` file to39 see the tests pass.deleted:examples/minitwit/schema.sql-21 removed
1-drop table if exists user;2-create table user (3- user_id integer primary key autoincrement,4- username text not null,5- email text not null,6- pw_hash text not null7-);8-9-drop table if exists follower;10-create table follower (11- who_id integer,12- whom_id integer13-);14-15-drop table if exists message;16-create table message (17- message_id integer primary key autoincrement,18- author_id integer not null,19- text text not null,20- pub_date integer21-);added:examples/minitwit/setup.cfg+2 added
1+[aliases]2+test=pytestadded:examples/minitwit/setup.py+16 added
1+from setuptools import setup2+3+setup(4+ name='minitwit',5+ packages=['minitwit'],6+ include_package_data=True,7+ install_requires=[8+ 'flask',9+ ],10+ setup_requires=[11+ 'pytest-runner',12+ ],13+ tests_require=[14+ 'pytest',15+ ],16+)deleted:examples/minitwit/test_minitwit.py-151 removed
1-# -*- coding: utf-8 -*-2-"""3- MiniTwit Tests4- ~~~~~~~~~~~~~~5-6- Tests the MiniTwit application.7-8- :copyright: (c) 2015 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-import os12-import minitwit13-import tempfile14-import pytest15-16-17-@pytest.fixture18-def client(request):19- db_fd, minitwit.app.config['DATABASE'] = tempfile.mkstemp()20- client = minitwit.app.test_client()21- with minitwit.app.app_context():22- minitwit.init_db()23-24- def teardown():25- """Get rid of the database again after each test."""26- os.close(db_fd)27- os.unlink(minitwit.app.config['DATABASE'])28- request.addfinalizer(teardown)29- return client30-31-32-def register(client, username, password, password2=None, email=None):33- """Helper function to register a user"""34- if password2 is None:35- password2 = password36- if email is None:37- email = username + '@example.com'38- return client.post('/register', data={39- 'username': username,40- 'password': password,41- 'password2': password2,42- 'email': email,43- }, follow_redirects=True)44-45-46-def login(client, username, password):47- """Helper function to login"""48- return client.post('/login', data={49- 'username': username,50- 'password': password51- }, follow_redirects=True)52-53-54-def register_and_login(client, username, password):55- """Registers and logs in in one go"""56- register(client, username, password)57- return login(client, username, password)58-59-60-def logout(client):61- """Helper function to logout"""62- return client.get('/logout', follow_redirects=True)63-64-65-def add_message(client, text):66- """Records a message"""67- rv = client.post('/add_message', data={'text': text},68- follow_redirects=True)69- if text:70- assert b'Your message was recorded' in rv.data71- return rv72-73-74-def test_register(client):75- """Make sure registering works"""76- rv = register(client, 'user1', 'default')77- assert b'You were successfully registered ' \78- b'and can login now' in rv.data79- rv = register(client, 'user1', 'default')80- assert b'The username is already taken' in rv.data81- rv = register(client, '', 'default')82- assert b'You have to enter a username' in rv.data83- rv = register(client, 'meh', '')84- assert b'You have to enter a password' in rv.data85- rv = register(client, 'meh', 'x', 'y')86- assert b'The two passwords do not match' in rv.data87- rv = register(client, 'meh', 'foo', email='broken')88- assert b'You have to enter a valid email address' in rv.data89-90-91-def test_login_logout(client):92- """Make sure logging in and logging out works"""93- rv = register_and_login(client, 'user1', 'default')94- assert b'You were logged in' in rv.data95- rv = logout(client)96- assert b'You were logged out' in rv.data97- rv = login(client, 'user1', 'wrongpassword')98- assert b'Invalid password' in rv.data99- rv = login(client, 'user2', 'wrongpassword')100- assert b'Invalid username' in rv.data101-102-103-def test_message_recording(client):104- """Check if adding messages works"""105- register_and_login(client, 'foo', 'default')106- add_message(client, 'test message 1')107- add_message(client, '<test message 2>')108- rv = client.get('/')109- assert b'test message 1' in rv.data110- assert b'<test message 2>' in rv.data111-112-113-def test_timelines(client):114- """Make sure that timelines work"""115- register_and_login(client, 'foo', 'default')116- add_message(client, 'the message by foo')117- logout(client)118- register_and_login(client, 'bar', 'default')119- add_message(client, 'the message by bar')120- rv = client.get('/public')121- assert b'the message by foo' in rv.data122- assert b'the message by bar' in rv.data123-124- # bar's timeline should just show bar's message125- rv = client.get('/')126- assert b'the message by foo' not in rv.data127- assert b'the message by bar' in rv.data128-129- # now let's follow foo130- rv = client.get('/foo/follow', follow_redirects=True)131- assert b'You are now following "foo"' in rv.data132-133- # we should now see foo's message134- rv = client.get('/')135- assert b'the message by foo' in rv.data136- assert b'the message by bar' in rv.data137-138- # but on the user's page we only want the user's message139- rv = client.get('/bar')140- assert b'the message by foo' not in rv.data141- assert b'the message by bar' in rv.data142- rv = client.get('/foo')143- assert b'the message by foo' in rv.data144- assert b'the message by bar' not in rv.data145-146- # now unfollow and check if that worked147- rv = client.get('/foo/unfollow', follow_redirects=True)148- assert b'You are no longer following "foo"' in rv.data149- rv = client.get('/')150- assert b'the message by foo' not in rv.data151- assert b'the message by bar' in rv.dataadded: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('yourapplication')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+)deleted:examples/persona/static/persona.js-52 removed
1-$(function() {2- /* convert the links into clickable buttons that go to the3- persona service */4- $('a.signin').on('click', function() {5- navigator.id.request({6- siteName: 'Flask Persona Example'7- });8- return false;9- });10-11- $('a.signout').on('click', function() {12- navigator.id.logout();13- return false;14- });15-16- /* watch persona state changes */17- navigator.id.watch({18- loggedInUser: $CURRENT_USER,19- onlogin: function(assertion) {20- /* because the login needs to verify the provided assertion21- with the persona service which requires an HTTP request,22- this could take a bit. To not confuse the user we show23- a progress box */24- var box = $('<div class=signinprogress></div>')25- .hide()26- .text('Please wait ...')27- .appendTo('body')28- .fadeIn('fast');29- $.ajax({30- type: 'POST',31- url: $URL_ROOT + '_auth/login',32- data: {assertion: assertion},33- success: function(res, status, xhr) { window.location.reload(); },34- error: function(xhr, status, err) {35- box.remove();36- navigator.id.logout();37- alert('Login failure: ' + err);38- }39- });40- },41- onlogout: function() {42- $.ajax({43- type: 'POST',44- url: $URL_ROOT + '_auth/logout',45- success: function(res, status, xhr) { window.location.reload(); },46- error: function(xhr, status, err) {47- alert('Logout failure: ' + err);48- }49- });50- }51- });52-});deleted:examples/persona/static/spinner.pngbinary
A binary file, deleted.
deleted:examples/persona/static/style.css-39 removed
1-html {2- background: #eee;3-}4-5-body {6- font-family: 'Verdana', sans-serif;7- font-size: 15px;8- margin: 30px auto;9- width: 720px;10- background: white;11- padding: 30px;12-}13-14-h1 {15- margin: 0;16-}17-18-h1, h2, a {19- color: #d00;20-}21-22-div.authbar {23- background: #eee;24- padding: 0 15px;25- margin: 10px -15px;26- line-height: 25px;27- height: 25px;28- vertical-align: middle;29-}30-31-div.signinprogress {32- position: fixed;33- top: 0;34- left: 0;35- right: 0;36- bottom: 0;37- background: rgba(255, 255, 255, 0.8) url(spinner.png) center center no-repeat;38- font-size: 0;39-}deleted:examples/persona/templates/index.html-23 removed
1-{% extends "layout.html" %}2-{% block title %}Welcome{% endblock %}3-{% block body %}4- <h2>Welcome</h2>5- <p>6- This is a small example application that shows how to integrate7- Mozilla's persona signin service into a Flask application.8- <p>9- The advantage of persona over your own login system is that the10- password is managed outside of your application and you get11- a verified mail address as primary identifier for your user.12- <p>13- In this example nothing is actually stored on the server, it14- just takes over the email address from the persona verifier15- and stores it in a session.16- {% if g.user %}17- <p>18- You are now logged in as <strong>{{ g.user }}</strong>19- {% else %}20- <p>21- To sign in click the sign in button above.22- {% endif %}23-{% endblock %}deleted:examples/persona/templates/layout.html-27 removed
1-<!doctype html>2-<title>{% block title %}{% endblock %} | Flask Persona Example</title>3-<meta http-equiv="X-UA-Compatible" content="IE=Edge">4-<script src="{{ config.PERSONA_JS }}"></script>5-<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>6-<script>7- /* the url root is useful for doing HTTP requests */8- var $URL_ROOT = {{ request.url_root|tojson }};9-10- /* we store the current user here so that the persona11- javascript support knows about the current user */12- var $CURRENT_USER = {{ g.user|tojson }};13-</script>14-<script src="{{ url_for('static', filename='persona.js') }}"></script>15-<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">16-<header>17- <h1>Mozilla Persona Example</h1>18- <div class="authbar">19- {% if g.user %}20- Signed in as <em>{{ g.user }}</em>21- (<a href="#" class="signout">Sign out</a>)22- {% else %}23- Not signed in. <a href="#" class="signin">Sign in</a>24- {% endif %}25- </div>26-</header>27-{% block body %}{% endblock %}deleted:examples/persona/persona.py-55 removed
1-from flask import Flask, render_template, session, request, abort, g2-3-import requests4-5-6-app = Flask(__name__)7-app.config.update(8- DEBUG=True,9- SECRET_KEY='my development key',10- PERSONA_JS='https://login.persona.org/include.js',11- PERSONA_VERIFIER='https://verifier.login.persona.org/verify',12-)13-app.config.from_envvar('PERSONA_SETTINGS', silent=True)14-15-16-@app.before_request17-def get_current_user():18- g.user = None19- email = session.get('email')20- if email is not None:21- g.user = email22-23-24-@app.route('/')25-def index():26- """Just a generic index page to show."""27- return render_template('index.html')28-29-30-@app.route('/_auth/login', methods=['GET', 'POST'])31-def login_handler():32- """This is used by the persona.js file to kick off the33- verification securely from the server side. If all is okay34- the email address is remembered on the server.35- """36- resp = requests.post(app.config['PERSONA_VERIFIER'], data={37- 'assertion': request.form['assertion'],38- 'audience': request.host_url,39- }, verify=True)40- if resp.ok:41- verification_data = resp.json()42- if verification_data['status'] == 'okay':43- session['email'] = verification_data['email']44- return 'OK'45-46- abort(400)47-48-49-@app.route('/_auth/logout', methods=['POST'])50-def logout_handler():51- """This is what persona.js will call to sign the user52- out again.53- """54- session.clear()55- return 'OK'deleted:examples/persona/README.md-3 removed
1-A simple example for integrating [Persona](https://login.persona.org/) into a2-Flask application. In addition to Flask, it requires the3-[requests](www.python-requests.org/) library.added:flask/json/__init__.py+271 added
1+# -*- coding: utf-8 -*-2+import io3+import uuid4+from datetime import date5+from flask.globals import current_app, request6+from flask._compat import text_type, PY27+8+from werkzeug.http import http_date9+from jinja2 import Markup10+11+# Use the same json implementation as itsdangerous on which we12+# depend anyways.13+from itsdangerous import json as _json14+15+16+# Figure out if simplejson escapes slashes. This behavior was changed17+# from one version to another without reason.18+_slash_escape = '\\/' not in _json.dumps('/')19+20+21+__all__ = ['dump', 'dumps', 'load', 'loads', 'htmlsafe_dump',22+ 'htmlsafe_dumps', 'JSONDecoder', 'JSONEncoder',23+ 'jsonify']24+25+26+def _wrap_reader_for_text(fp, encoding):27+ if isinstance(fp.read(0), bytes):28+ fp = io.TextIOWrapper(io.BufferedReader(fp), encoding)29+ return fp30+31+32+def _wrap_writer_for_text(fp, encoding):33+ try:34+ fp.write('')35+ except TypeError:36+ fp = io.TextIOWrapper(fp, encoding)37+ return fp38+39+40+class JSONEncoder(_json.JSONEncoder):41+ """The default Flask JSON encoder. This one extends the default simplejson42+ encoder by also supporting ``datetime`` objects, ``UUID`` as well as43+ ``Markup`` objects which are serialized as RFC 822 datetime strings (same44+ as the HTTP date format). In order to support more data types override the45+ :meth:`default` method.46+ """47+48+ def default(self, o):49+ """Implement this method in a subclass such that it returns a50+ serializable object for ``o``, or calls the base implementation (to51+ raise a :exc:`TypeError`).52+53+ For example, to support arbitrary iterators, you could implement54+ default like this::55+56+ def default(self, o):57+ try:58+ iterable = iter(o)59+ except TypeError:60+ pass61+ else:62+ return list(iterable)63+ return JSONEncoder.default(self, o)64+ """65+ if isinstance(o, date):66+ return http_date(o.timetuple())67+ if isinstance(o, uuid.UUID):68+ return str(o)69+ if hasattr(o, '__html__'):70+ return text_type(o.__html__())71+ return _json.JSONEncoder.default(self, o)72+73+74+class JSONDecoder(_json.JSONDecoder):75+ """The default JSON decoder. This one does not change the behavior from76+ the default simplejson decoder. Consult the :mod:`json` documentation77+ for more information. This decoder is not only used for the load78+ functions of this module but also :attr:`~flask.Request`.79+ """80+81+82+def _dump_arg_defaults(kwargs):83+ """Inject default arguments for dump functions."""84+ if current_app:85+ bp = current_app.blueprints.get(request.blueprint) if request else None86+ kwargs.setdefault(87+ 'cls',88+ bp.json_encoder if bp and bp.json_encoder89+ else current_app.json_encoder90+ )91+92+ if not current_app.config['JSON_AS_ASCII']:93+ kwargs.setdefault('ensure_ascii', False)94+95+ kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS'])96+ else:97+ kwargs.setdefault('sort_keys', True)98+ kwargs.setdefault('cls', JSONEncoder)99+100+101+def _load_arg_defaults(kwargs):102+ """Inject default arguments for load functions."""103+ if current_app:104+ bp = current_app.blueprints.get(request.blueprint) if request else None105+ kwargs.setdefault(106+ 'cls',107+ bp.json_decoder if bp and bp.json_decoder108+ else current_app.json_decoder109+ )110+ else:111+ kwargs.setdefault('cls', JSONDecoder)112+113+114+def dumps(obj, **kwargs):115+ """Serialize ``obj`` to a JSON formatted ``str`` by using the application's116+ configured encoder (:attr:`~flask.Flask.json_encoder`) if there is an117+ application on the stack.118+119+ This function can return ``unicode`` strings or ascii-only bytestrings by120+ default which coerce into unicode strings automatically. That behavior by121+ default is controlled by the ``JSON_AS_ASCII`` configuration variable122+ and can be overridden by the simplejson ``ensure_ascii`` parameter.123+ """124+ _dump_arg_defaults(kwargs)125+ encoding = kwargs.pop('encoding', None)126+ rv = _json.dumps(obj, **kwargs)127+ if encoding is not None and isinstance(rv, text_type):128+ rv = rv.encode(encoding)129+ return rv130+131+132+def dump(obj, fp, **kwargs):133+ """Like :func:`dumps` but writes into a file object."""134+ _dump_arg_defaults(kwargs)135+ encoding = kwargs.pop('encoding', None)136+ if encoding is not None:137+ fp = _wrap_writer_for_text(fp, encoding)138+ _json.dump(obj, fp, **kwargs)139+140+141+def loads(s, **kwargs):142+ """Unserialize a JSON object from a string ``s`` by using the application's143+ configured decoder (:attr:`~flask.Flask.json_decoder`) if there is an144+ application on the stack.145+ """146+ _load_arg_defaults(kwargs)147+ if isinstance(s, bytes):148+ s = s.decode(kwargs.pop('encoding', None) or 'utf-8')149+ return _json.loads(s, **kwargs)150+151+152+def load(fp, **kwargs):153+ """Like :func:`loads` but reads from a file object.154+ """155+ _load_arg_defaults(kwargs)156+ if not PY2:157+ fp = _wrap_reader_for_text(fp, kwargs.pop('encoding', None) or 'utf-8')158+ return _json.load(fp, **kwargs)159+160+161+def htmlsafe_dumps(obj, **kwargs):162+ """Works exactly like :func:`dumps` but is safe for use in ``<script>``163+ tags. It accepts the same arguments and returns a JSON string. Note that164+ this is available in templates through the ``|tojson`` filter which will165+ also mark the result as safe. Due to how this function escapes certain166+ characters this is safe even if used outside of ``<script>`` tags.167+168+ The following characters are escaped in strings:169+170+ - ``<``171+ - ``>``172+ - ``&``173+ - ``'``174+175+ This makes it safe to embed such strings in any place in HTML with the176+ notable exception of double quoted attributes. In that case single177+ quote your attributes or HTML escape it in addition.178+179+ .. versionchanged:: 0.10180+ This function's return value is now always safe for HTML usage, even181+ if outside of script tags or if used in XHTML. This rule does not182+ hold true when using this function in HTML attributes that are double183+ quoted. Always single quote attributes if you use the ``|tojson``184+ filter. Alternatively use ``|tojson|forceescape``.185+ """186+ rv = dumps(obj, **kwargs) \187+ .replace(u'<', u'\\u003c') \188+ .replace(u'>', u'\\u003e') \189+ .replace(u'&', u'\\u0026') \190+ .replace(u"'", u'\\u0027')191+ if not _slash_escape:192+ rv = rv.replace('\\/', '/')193+ return rv194+195+196+def htmlsafe_dump(obj, fp, **kwargs):197+ """Like :func:`htmlsafe_dumps` but writes into a file object."""198+ fp.write(text_type(htmlsafe_dumps(obj, **kwargs)))199+200+201+def jsonify(*args, **kwargs):202+ """This function wraps :func:`dumps` to add a few enhancements that make203+ life easier. It turns the JSON output into a :class:`~flask.Response`204+ object with the :mimetype:`application/json` mimetype. For convenience, it205+ also converts multiple arguments into an array or multiple keyword arguments206+ into a dict. This means that both ``jsonify(1,2,3)`` and207+ ``jsonify([1,2,3])`` serialize to ``[1,2,3]``.208+209+ For clarity, the JSON serialization behavior has the following differences210+ from :func:`dumps`:211+212+ 1. Single argument: Passed straight through to :func:`dumps`.213+ 2. Multiple arguments: Converted to an array before being passed to214+ :func:`dumps`.215+ 3. Multiple keyword arguments: Converted to a dict before being passed to216+ :func:`dumps`.217+ 4. Both args and kwargs: Behavior undefined and will throw an exception.218+219+ Example usage::220+221+ from flask import jsonify222+223+ @app.route('/_get_current_user')224+ def get_current_user():225+ return jsonify(username=g.user.username,226+ email=g.user.email,227+ id=g.user.id)228+229+ This will send a JSON response like this to the browser::230+231+ {232+ "username": "admin",233+ "email": "admin@localhost",234+ "id": 42235+ }236+237+238+ .. versionchanged:: 0.11239+ Added support for serializing top-level arrays. This introduces a240+ security risk in ancient browsers. See :ref:`json-security` for details.241+242+ This function's response will be pretty printed if the243+ ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to True or the244+ Flask app is running in debug mode. Compressed (not pretty) formatting245+ currently means no indents and no spaces after separators.246+247+ .. versionadded:: 0.2248+ """249+250+ indent = None251+ separators = (',', ':')252+253+ if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug:254+ indent = 2255+ separators = (', ', ': ')256+257+ if args and kwargs:258+ raise TypeError('jsonify() behavior undefined when passed both args and kwargs')259+ elif len(args) == 1: # single args are passed directly to dumps()260+ data = args[0]261+ else:262+ data = args or kwargs263+264+ return current_app.response_class(265+ (dumps(data, indent=indent, separators=separators), '\n'),266+ mimetype=current_app.config['JSONIFY_MIMETYPE']267+ )268+269+270+def tojson_filter(obj, **kwargs):271+ return Markup(htmlsafe_dumps(obj, **kwargs))added:flask/json/tag.py+297 added
1+"""2+Tagged JSON3+~~~~~~~~~~~4+5+A compact representation for lossless serialization of non-standard JSON types.6+:class:`~flask.sessions.SecureCookieSessionInterface` uses this to serialize7+the session data, but it may be useful in other places. It can be extended to8+support other types.9+10+.. autoclass:: TaggedJSONSerializer11+ :members:12+13+.. autoclass:: JSONTag14+ :members:15+16+Let's seen an example that adds support for :class:`~collections.OrderedDict`.17+Dicts don't have an order in Python or JSON, so to handle this we will dump18+the items as a list of ``[key, value]`` pairs. Subclass :class:`JSONTag` and19+give it the new key ``' od'`` to identify the type. The session serializer20+processes dicts first, so insert the new tag at the front of the order since21+``OrderedDict`` must be processed before ``dict``. ::22+23+ from flask.json.tag import JSONTag24+25+ class TagOrderedDict(JSONTag):26+ __slots__ = ('serializer',)27+ key = ' od'28+29+ def check(self, value):30+ return isinstance(value, OrderedDict)31+32+ def to_json(self, value):33+ return [[k, self.serializer.tag(v)] for k, v in iteritems(value)]34+35+ def to_python(self, value):36+ return OrderedDict(value)37+38+ app.session_interface.serializer.register(TagOrderedDict, 0)39+40+"""41+42+from base64 import b64decode, b64encode43+from datetime import datetime44+from uuid import UUID45+46+from jinja2 import Markup47+from werkzeug.http import http_date, parse_date48+49+from flask._compat import iteritems, text_type50+from flask.json import dumps, loads51+52+53+class JSONTag(object):54+ """Base class for defining type tags for :class:`TaggedJSONSerializer`."""55+56+ __slots__ = ('serializer',)57+58+ #: The tag to mark the serialized object with. If ``None``, this tag is59+ #: only used as an intermediate step during tagging.60+ key = None61+62+ def __init__(self, serializer):63+ """Create a tagger for the given serializer."""64+ self.serializer = serializer65+66+ def check(self, value):67+ """Check if the given value should be tagged by this tag."""68+ raise NotImplementedError69+70+ def to_json(self, value):71+ """Convert the Python object to an object that is a valid JSON type.72+ The tag will be added later."""73+ raise NotImplementedError74+75+ def to_python(self, value):76+ """Convert the JSON representation back to the correct type. The tag77+ will already be removed."""78+ raise NotImplementedError79+80+ def tag(self, value):81+ """Convert the value to a valid JSON type and add the tag structure82+ around it."""83+ return {self.key: self.to_json(value)}84+85+86+class TagDict(JSONTag):87+ """Tag for 1-item dicts whose only key matches a registered tag.88+89+ Internally, the dict key is suffixed with `__`, and the suffix is removed90+ when deserializing.91+ """92+93+ __slots__ = ()94+ key = ' di'95+96+ def check(self, value):97+ return (98+ isinstance(value, dict)99+ and len(value) == 1100+ and next(iter(value)) in self.serializer.tags101+ )102+103+ def to_json(self, value):104+ key = next(iter(value))105+ return {key + '__': self.serializer.tag(value[key])}106+107+ def to_python(self, value):108+ key = next(iter(value))109+ return {key[:-2]: value[key]}110+111+112+class PassDict(JSONTag):113+ __slots__ = ()114+115+ def check(self, value):116+ return isinstance(value, dict)117+118+ def to_json(self, value):119+ # JSON objects may only have string keys, so don't bother tagging the120+ # key here.121+ return dict((k, self.serializer.tag(v)) for k, v in iteritems(value))122+123+ tag = to_json124+125+126+class TagTuple(JSONTag):127+ __slots__ = ()128+ key = ' t'129+130+ def check(self, value):131+ return isinstance(value, tuple)132+133+ def to_json(self, value):134+ return [self.serializer.tag(item) for item in value]135+136+ def to_python(self, value):137+ return tuple(value)138+139+140+class PassList(JSONTag):141+ __slots__ = ()142+143+ def check(self, value):144+ return isinstance(value, list)145+146+ def to_json(self, value):147+ return [self.serializer.tag(item) for item in value]148+149+ tag = to_json150+151+152+class TagBytes(JSONTag):153+ __slots__ = ()154+ key = ' b'155+156+ def check(self, value):157+ return isinstance(value, bytes)158+159+ def to_json(self, value):160+ return b64encode(value).decode('ascii')161+162+ def to_python(self, value):163+ return b64decode(value)164+165+166+class TagMarkup(JSONTag):167+ """Serialize anything matching the :class:`~flask.Markup` API by168+ having a ``__html__`` method to the result of that method. Always169+ deserializes to an instance of :class:`~flask.Markup`."""170+171+ __slots__ = ()172+ key = ' m'173+174+ def check(self, value):175+ return callable(getattr(value, '__html__', None))176+177+ def to_json(self, value):178+ return text_type(value.__html__())179+180+ def to_python(self, value):181+ return Markup(value)182+183+184+class TagUUID(JSONTag):185+ __slots__ = ()186+ key = ' u'187+188+ def check(self, value):189+ return isinstance(value, UUID)190+191+ def to_json(self, value):192+ return value.hex193+194+ def to_python(self, value):195+ return UUID(value)196+197+198+class TagDateTime(JSONTag):199+ __slots__ = ()200+ key = ' d'201+202+ def check(self, value):203+ return isinstance(value, datetime)204+205+ def to_json(self, value):206+ return http_date(value)207+208+ def to_python(self, value):209+ return parse_date(value)210+211+212+class TaggedJSONSerializer(object):213+ """Serializer that uses a tag system to compactly represent objects that214+ are not JSON types. Passed as the intermediate serializer to215+ :class:`itsdangerous.Serializer`.216+217+ The following extra types are supported:218+219+ * :class:`dict`220+ * :class:`tuple`221+ * :class:`bytes`222+ * :class:`~flask.Markup`223+ * :class:`~uuid.UUID`224+ * :class:`~datetime.datetime`225+ """226+227+ __slots__ = ('tags', 'order')228+229+ #: Tag classes to bind when creating the serializer. Other tags can be230+ #: added later using :meth:`~register`.231+ default_tags = [232+ TagDict, PassDict, TagTuple, PassList, TagBytes, TagMarkup, TagUUID,233+ TagDateTime,234+ ]235+236+ def __init__(self):237+ self.tags = {}238+ self.order = []239+240+ for cls in self.default_tags:241+ self.register(cls)242+243+ def register(self, tag_class, force=False, index=-1):244+ """Register a new tag with this serializer.245+246+ :param tag_class: tag class to register. Will be instantiated with this247+ serializer instance.248+ :param force: overwrite an existing tag. If false (default), a249+ :exc:`KeyError` is raised.250+ :param index: index to insert the new tag in the tag order. Useful when251+ the new tag is a special case of an existing tag. If -1 (default),252+ the tag is appended to the end of the order.253+254+ :raise KeyError: if the tag key is already registered and ``force`` is255+ not true.256+ """257+ tag = tag_class(self)258+ key = tag.key259+260+ if key is not None:261+ if not force and key in self.tags:262+ raise KeyError("Tag '{0}' is already registered.".format(key))263+264+ self.tags[key] = tag265+266+ if index == -1:267+ self.order.append(tag)268+ else:269+ self.order.insert(index, tag)270+271+ def tag(self, value):272+ """Convert a value to a tagged representation if necessary."""273+ for tag in self.order:274+ if tag.check(value):275+ return tag.tag(value)276+277+ return value278+279+ def untag(self, value):280+ """Convert a tagged representation back to the original type."""281+ if len(value) != 1:282+ return value283+284+ key = next(iter(value))285+286+ if key not in self.tags:287+ return value288+289+ return self.tags[key].to_python(value[key])290+291+ def dumps(self, value):292+ """Tag the value and dump it to a compact JSON string."""293+ return dumps(self.tag(value), separators=(',', ':'))294+295+ def loads(self, value):296+ """Load data from a JSON string and deserialized any tagged objects."""297+ return loads(value, object_hook=self.untag)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/_compat.py+2 added
23 unmodified lines24 iterkeys = lambda d: iter(d.keys())25 itervalues = lambda d: iter(d.values())26 iteritems = lambda d: iter(d.items())27 28+ from inspect import getfullargspec as getargspec29 from io import StringIO30 31 def reraise(tp, value, tb=None):32 if value.__traceback__ is not tb:10 unmodified lines43 iterkeys = lambda d: d.iterkeys()44 itervalues = lambda d: d.itervalues()45 iteritems = lambda d: d.iteritems()46 47+ from inspect import getargspec48 from cStringIO import StringIO49 50 exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')51 47 unmodified linesmodified:flask/app.py+355 added-197 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 import os12 import sys13-from threading import Lock13+import warnings14 from datetime import timedelta15-from itertools import chain15 from functools import update_wrapper17-from collections import deque16+from itertools import chain17+from threading import Lock18 19-from werkzeug.datastructures import ImmutableDict20-from werkzeug.routing import Map, Rule, RequestRedirect, BuildError21-from werkzeug.exceptions import HTTPException, InternalServerError, \22- MethodNotAllowed, BadRequest, default_exceptions19+from werkzeug.datastructures import ImmutableDict, Headers20+from werkzeug.exceptions import BadRequest, HTTPException, \21+ InternalServerError, MethodNotAllowed, default_exceptions, \22+ BadRequestKeyError23+from werkzeug.routing import BuildError, Map, RequestRedirect, Rule24 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, g25+from . import cli, json26+from ._compat import integer_types, reraise, string_types, text_type27+from .config import Config, ConfigAttribute28+from .ctx import AppContext, RequestContext, _AppCtxGlobals29+from .globals import _request_ctx_stack, g, request, session30+from .helpers import _PackageBoundObject, \31+ _endpoint_from_view_func, find_package, get_debug_flag, \32+ get_flashed_messages, locked_cached_property, url_for33 from .sessions import SecureCookieSessionInterface34+from .signals import appcontext_tearing_down, got_request_exception, \35+ request_finished, request_started, request_tearing_down36 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_types37+ _default_template_ctx_processor38+from .wrappers import Request, Response39 40 # a lock used for logger initialization41 _logger_lock = Lock()42 81 unmodified lines124 125 .. versionadded:: 0.11126 The `root_path` parameter was added.127 128+ .. versionadded:: 0.13129+ The `host_matching` and `static_host` parameters were added.130+131 :param import_name: the name of the application package132 :param static_url_path: can be used to specify a different path for the133 static files on the web. Defaults to the name134 of the `static_folder` folder.135 :param static_folder: the folder with static files that should be served136 at `static_url_path`. Defaults to the ``'static'``137 folder in the root path of the application.138+ :param host_matching: sets the app's ``url_map.host_matching`` to the given139+ 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.74 unmodified lines221 debug = ConfigAttribute('DEBUG')222 223 #: The testing flag. Set this to ``True`` to enable the test mode of224 #: Flask extensions (and in the future probably also Flask itself).216- #: For example this might activate unittest helpers that have an225+ #: For example this might activate test helpers that have an226 #: additional runtime cost which should not be enabled by default.227 #:228 #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the229 #: default it's implicitly enabled.78 unmodified lines308 'USE_X_SENDFILE': False,309 'LOGGER_NAME': None,310 'LOGGER_HANDLER_POLICY': 'always',311 'SERVER_NAME': None,303- 'APPLICATION_ROOT': None,312+ 'APPLICATION_ROOT': '/',313 'SESSION_COOKIE_NAME': 'session',314 'SESSION_COOKIE_DOMAIN': None,315 'SESSION_COOKIE_PATH': None,316 'SESSION_COOKIE_HTTPONLY': True,317 'SESSION_COOKIE_SECURE': False,318 'SESSION_REFRESH_EACH_REQUEST': True,319 'MAX_CONTENT_LENGTH': None,320 'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12),312- 'TRAP_BAD_REQUEST_ERRORS': False,321+ 'TRAP_BAD_REQUEST_ERRORS': None,322 'TRAP_HTTP_EXCEPTIONS': False,323 'EXPLAIN_TEMPLATE_LOADING': False,324 'PREFERRED_URL_SCHEME': 'http',325 'JSON_AS_ASCII': True,326 'JSON_SORT_KEYS': True,318- 'JSONIFY_PRETTYPRINT_REGULAR': True,327+ 'JSONIFY_PRETTYPRINT_REGULAR': False,328 'JSONIFY_MIMETYPE': 'application/json',329 'TEMPLATES_AUTO_RELOAD': None,330 })331 13 unmodified lines345 #:346 #: .. versionadded:: 0.8347 session_interface = SecureCookieSessionInterface()348 349+ # TODO remove the next three attrs when Sphinx :inherited-members: works350+ # https://github.com/sphinx-doc/sphinx/issues/741351+352+ #: The name of the package or module that this app belongs to. Do not353+ #: change this once it is set by the constructor.354+ import_name = None355+356+ #: Location of the template files to be added to the template lookup.357+ #: ``None`` if templates should not be added.358+ template_folder = None359+360+ #: Absolute path to the package on the filesystem. Used to look up361+ #: resources contained in the package.362+ root_path = None363+364 def __init__(self, import_name, static_path=None, static_url_path=None,341- static_folder='static', template_folder='templates',365+ static_folder='static', static_host=None,366+ host_matching=False, template_folder='templates',367 instance_path=None, instance_relative_config=False,368 root_path=None):369 _PackageBoundObject.__init__(self, import_name,370 template_folder=template_folder,45 unmodified lines416 #: special key ``None`` points to a list of tuples where the first item417 #: is the class for the instance check and the second the error handler418 #: function.419 #:395- #: To register a error handler, use the :meth:`errorhandler`420+ #: To register an error handler, use the :meth:`errorhandler`421 #: decorator.422 self.error_handler_spec = {None: self._error_handlers}423 424 #: A list of functions that are called when :meth:`url_for` raises a4 unmodified lines429 #:430 #: .. versionadded:: 0.9431 self.url_build_error_handlers = []432 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.433+ #: A dictionary with lists of functions that will be called at the434+ #: beginning of each request. The key of the dictionary is the name of435+ #: the blueprint this function is active for, or ``None`` for all436+ #: requests. To register a function, use the :meth:`before_request`437+ #: decorator.438 self.before_request_funcs = {}439 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.440+ #: A list of functions that will be called at the beginning of the441+ #: first request to this instance. To register a function, use the442+ #: :meth:`before_first_request` decorator.443 #:444 #: .. versionadded:: 0.8445 self.before_first_request_funcs = []446 23 unmodified lines470 #:471 #: .. versionadded:: 0.9472 self.teardown_appcontext_funcs = []473 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 dictionary474+ #: A dictionary with lists of functions that are called before the475+ #: :attr:`before_request_funcs` functions. The key of the dictionary is476+ #: the name of the blueprint this function is active for, or ``None``477+ #: for all requests. To register a function, use478+ #: :meth:`url_value_preprocessor`.479 #:480 #: .. versionadded:: 0.7481 self.url_value_preprocessors = {}482 58 unmodified lines541 #: class ListConverter(BaseConverter):542 #: def to_python(self, value):543 #: return value.split(',')544 #: def to_url(self, values):522- #: return ','.join(BaseConverter.to_url(value)545+ #: return ','.join(super(ListConverter, self).to_url(value)546 #: for value in values)547 #:548 #: app = Flask(__name__)549 #: app.url_map.converters['list'] = ListConverter550 self.url_map = Map()551 552+ self.url_map.host_matching = host_matching553+554 # tracks internally if the application already handled at least one555 # request.556 self._got_first_request = False557 self._before_request_lock = Lock()558 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.559+ # Add a static route using the provided static_url_path, static_host,560+ # and static_folder if there is a configured static_folder.561+ # Note we do this without checking if static_folder exists.562+ # For one, it might be created while the server is running (e.g. during563+ # development). Also, Google App Engine stores static files somewhere564 if self.has_static_folder:565+ assert bool(static_host) == host_matching, 'Invalid static_host/host_matching combination'566 self.add_url_rule(self.static_url_path + '/<path:filename>',541- endpoint='static',567+ endpoint='static', host=static_host,568 view_func=self.send_static_file)569 570 #: The click command line context for this application. Commands571 #: registered here show up in the :command:`flask` command once the267 unmodified lines839 The default port is now picked from the ``SERVER_NAME`` variable.840 841 :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to842 have the server available externally as well. Defaults to817- ``'127.0.0.1'``.843+ ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config844+ variable if present.845 :param port: the port of the webserver. Defaults to ``5000`` or the846 port defined in the ``SERVER_NAME`` config variable if847 present.848 :param debug: if given, enable or disable debug mode.2 unmodified lines851 Werkzeug server. See852 :func:`werkzeug.serving.run_simple` for more853 information.854 """855+ # Change this into a no-op if the server is invoked from the856+ # command line. Have a look at cli.py for more information.857+ if os.environ.get('FLASK_RUN_FROM_CLI_SERVER') == '1':858+ from .debughelpers import explain_ignored_app_run859+ explain_ignored_app_run()860+ return861+862 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 = 5000863+ _host = '127.0.0.1'864+ _port = 5000865+ server_name = self.config.get("SERVER_NAME")866+ sn_host, sn_port = None, None867+ if server_name:868+ sn_host, _, sn_port = server_name.partition(':')869+ host = host or sn_host or _host870+ port = int(port or sn_port or _port)871 if debug is not None:872 self.debug = bool(debug)873 options.setdefault('use_reloader', self.debug)874 options.setdefault('use_debugger', self.debug)841- options.setdefault('passthrough_errors', True)875 if debug:876 self.jinja_env.auto_reload = True877 try:878 run_simple(host, port, self, **options)879 finally:880 # reset the first request information if the development server848- # resetted normally. This makes it possible to restart the server881+ # reset normally. This makes it possible to restart the server882 # without reloader and that stuff from an interactive shell.883 self._got_first_request = False884 885 def test_client(self, use_cookies=True, **kwargs):25 unmodified lines911 912 from flask.testing import FlaskClient913 914 class CustomClient(FlaskClient):882- def __init__(self, authentication=None, *args, **kwargs):883- FlaskClient.__init__(*args, **kwargs)884- self._authentication = authentication915+ def __init__(self, *args, **kwargs):916+ self._authentication = kwargs.pop("authentication")917+ super(CustomClient,self).__init__( *args, **kwargs)918 919 app.test_client_class = CustomClient920 client = app.test_client(authentication='Basic ....')921 21 unmodified lines943 session data in a signed cookie. This requires that the944 :attr:`secret_key` is set. Instead of overriding this method945 we recommend replacing the :class:`session_interface`.946 947+ .. deprecated: 1.0948+ Will be removed in 1.1. Use ``session_interface.open_session``949+ instead.950+951 :param request: an instance of :attr:`request_class`.952 """953+954+ warnings.warn(DeprecationWarning(955+ '"open_session" is deprecated and will be removed in 1.1. Use'956+ ' "session_interface.open_session" instead.'957+ ))958 return self.session_interface.open_session(self, request)959 960 def save_session(self, session, response):961 """Saves the session if it needs updates. For the default962 implementation, check :meth:`open_session`. Instead of overriding this963 method we recommend replacing the :class:`session_interface`.964 965+ .. deprecated: 1.0966+ Will be removed in 1.1. Use ``session_interface.save_session``967+ instead.968+969 :param session: the session to be saved (a970 :class:`~werkzeug.contrib.securecookie.SecureCookie`971 object)972 :param response: an instance of :attr:`response_class`973 """974+975+ warnings.warn(DeprecationWarning(976+ '"save_session" is deprecated and will be removed in 1.1. Use'977+ ' "session_interface.save_session" instead.'978+ ))979 return self.session_interface.save_session(self, session, response)980 981 def make_null_session(self):982 """Creates a new instance of a missing session. Instead of overriding983 this method we recommend replacing the :class:`session_interface`.984 985+ .. deprecated: 1.0986+ Will be removed in 1.1. Use ``session_interface.make_null_session``987+ instead.988+989 .. versionadded:: 0.7990 """991+992+ warnings.warn(DeprecationWarning(993+ '"make_null_session" is deprecated and will be removed in 1.1. Use'994+ ' "session_interface.make_null_session" instead.'995+ ))996 return self.session_interface.make_null_session(self)997 998 @setupmethod999 def register_blueprint(self, blueprint, **options):940- """Register a blueprint on the application. For information about 941- blueprints head over to :ref:`blueprints`.1000+ """Register a :class:`~flask.Blueprint` on the application. Keyword1001+ arguments passed to this method will override the defaults set on the1002+ blueprint.1003 943- The blueprint name is passed in as the first argument. 944- Options are passed as additional keyword arguments and forwarded to 945- `blueprints` in an "options" dictionary.1004+ Calls the blueprint's :meth:`~flask.Blueprint.register` method after1005+ recording the blueprint in the application's :attr:`blueprints`.1006 947- :param subdomain: set a subdomain for the blueprint948- :param url_prefix: set the prefix for all URLs defined on the blueprint.949- ``(url_prefix='/<lang code>')``950- :param url_defaults: a dictionary with URL defaults that is added to 951- each and every URL defined with this blueprint952- :param static_folder: add a static folder to urls in this blueprint953- :param static_url_path: add a static url path to urls in this blueprint954- :param template_folder: set an alternate template folder955- :param root_path: set an alternate root path for this blueprint1007+ :param blueprint: The blueprint to register.1008+ :param url_prefix: Blueprint routes will be prefixed with this.1009+ :param subdomain: Blueprint routes will match on this subdomain.1010+ :param url_defaults: Blueprint routes will use these default values for1011+ view arguments.1012+ :param options: Additional keyword arguments are passed to1013+ :class:`~flask.blueprints.BlueprintSetupState`. They can be1014+ accessed in :meth:`~flask.Blueprint.record` callbacks.1015 1016 .. versionadded:: 0.71017 """1018 first_registration = False1019+1020 if blueprint.name in self.blueprints:961- assert self.blueprints[blueprint.name] is blueprint, \962- 'A blueprint\'s name collision occurred between %r and ' \963- '%r. Both share the same name "%s". Blueprints that ' \964- 'are created on the fly need unique names.' % \965- (blueprint, self.blueprints[blueprint.name], blueprint.name)1021+ assert self.blueprints[blueprint.name] is blueprint, (1022+ 'A name collision occurred between blueprints %r and %r. Both'1023+ ' share the same name "%s". Blueprints that are created on the'1024+ ' fly need unique names.' % (1025+ blueprint, self.blueprints[blueprint.name], blueprint.name1026+ )1027+ )1028 else:1029 self.blueprints[blueprint.name] = blueprint1030 self._blueprint_order.append(blueprint)1031 first_registration = True1032+1033 blueprint.register(self, options, first_registration)1034 1035 def iter_blueprints(self):1036 """Iterates over all blueprints by the order they were registered.2 unmodified lines1039 """1040 return iter(self._blueprint_order)1041 1042 @setupmethod980- def add_url_rule(self, rule, endpoint=None, view_func=None, **options):1043+ def add_url_rule(self, rule, endpoint=None, view_func=None, provide_automatic_options=None, **options):1044 """Connects a URL rule. Works exactly like the :meth:`route`1045 decorator. If a view_func is provided it will be registered with the1046 endpoint.1047 31 unmodified lines1079 itself assumes the name of the view function as1080 endpoint1081 :param view_func: the function to call when serving a request to the1082 provided endpoint1083+ :param provide_automatic_options: controls whether the ``OPTIONS``1084+ method should be added automatically. This can also be controlled1085+ by setting the ``view_func.provide_automatic_options = False``1086+ before adding the rule.1087 :param options: the options to be forwarded to the underlying1088 :class:`~werkzeug.routing.Rule` object. A change1089 to Werkzeug is handling of method options. methods1090 is a list of methods this rule should be limited21 unmodified lines1112 required_methods = set(getattr(view_func, 'required_methods', ()))1113 1114 # starting with Flask 0.8 the view_func object can disable and1115 # force-enable the automatic options handling.1116+ if provide_automatic_options is None:1049- provide_automatic_options = getattr(view_func,1050- 'provide_automatic_options', None)1117+ provide_automatic_options = getattr(view_func,1118+ 'provide_automatic_options', None)1119 1120 if provide_automatic_options is None:1121 if 'OPTIONS' not in methods:1122 provide_automatic_options = True77 unmodified lines1200 return exc_class, None1201 1202 @setupmethod1203 def errorhandler(self, code_or_exception):1136- """A decorator that is used to register a function give a given1204+ """Register a function to handle errors by code or exception class.1205+1206+ A decorator that is used to register a function given an1207 error code. Example::1208 1209 @app.errorhandler(404)1210 def page_not_found(error):4 unmodified lines1215 @app.errorhandler(DatabaseError)1216 def special_exception_handler(error):1217 return 'Database connection failed', 5001218 1149- You can also register a function as error handler without using1150- the :meth:`errorhandler` decorator. The following example is1151- equivalent to the one above::1152-1153- def page_not_found(error):1154- return 'This page does not exist', 4041155- app.error_handler_spec[None][404] = page_not_found1156-1157- Setting error handlers via assignments to :attr:`error_handler_spec`1158- however is discouraged as it requires fiddling with nested dictionaries1159- and the special case for arbitrary exception types.1160-1161- The first ``None`` refers to the active blueprint. If the error1162- handler should be application wide ``None`` shall be used.1163-1219 .. versionadded:: 0.71220 Use :meth:`register_error_handler` instead of modifying1221 :attr:`error_handler_spec` directly, for application wide error1222 handlers.2 unmodified lines1225 One can now additionally also register custom exception types1226 that do not necessarily have to be a subclass of the1227 :class:`~werkzeug.exceptions.HTTPException` class.1228 1174- :param code: the code as integer for the handler1229+ :param code_or_exception: the code as integer for the handler, or1230+ an arbitrary exception1231 """1232 def decorator(f):1233 self._register_error_handler(None, code_or_exception, f)1234 return f1235 return decorator1236 1237+ @setupmethod1238 def register_error_handler(self, code_or_exception, f):1239 """Alternative error attach function to the :meth:`errorhandler`1240 decorator that is more straightforward to use for non decorator1241 usage.10 unmodified lines1252 :type f: callable1253 """1254 if isinstance(code_or_exception, HTTPException): # old broken behavior1255 raise ValueError(1199- 'Tried to register a handler for an exception instance {0!r}. '1200- 'Handlers can only be registered for exception classes or HTTP error codes.'1201- .format(code_or_exception))1256+ 'Tried to register a handler for an exception instance {0!r}.'1257+ ' Handlers can only be registered for exception classes or'1258+ ' HTTP error codes.'.format(code_or_exception)1259+ )1260 1261+ try:1203- exc_class, code = self._get_exc_class_and_code(code_or_exception)1262+ exc_class, code = self._get_exc_class_and_code(code_or_exception)1263+ except KeyError:1264+ raise KeyError(1265+ "'{0}' is not a recognized HTTP error code. Use a subclass of"1266+ " HTTPException with that code instead.".format(code_or_exception)1267+ )1268 1269 handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})1270 handlers[exc_class] = f1271 97 unmodified lines1369 @setupmethod1370 def before_request(self, f):1371 """Registers a function to run before each request.1372 1309- The function will be called without any arguments.1310- If the function returns a non-None value, it's handled as1311- if it was the return value from the view and further1312- request handling is stopped.1373+ For example, this can be used to open a database connection, or to load1374+ the logged in user from the session.1375+1376+ The function will be called without any arguments. If it returns a1377+ non-None value, the value is handled as if it was the return value from1378+ the view, and further request handling is stopped.1379 """1380 self.before_request_funcs.setdefault(None, []).append(f)1381 return f1382 47 unmodified lines1430 that they will fail. If they do execute code that might fail they1431 will have to surround the execution of these code by try/except1432 statements and log occurring errors.1433 1368- When a teardown function was called because of a exception it will1434+ When a teardown function was called because of an exception it will1435 be passed an error object.1436 1437 The return values of teardown functions are ignored.1438 54 unmodified lines1493 return f1494 1495 @setupmethod1496 def url_value_preprocessor(self, f):1431- """Registers a function as URL value preprocessor for all view1432- functions of the application. It's called before the view functions1433- are called and can modify the url values provided.1497+ """Register a URL value preprocessor function for all view1498+ functions in the application. These functions will be called before the1499+ :meth:`before_request` functions.1500+1501+ The function can modify the values captured from the matched url before1502+ they are passed to the view. For example, this can be used to pop a1503+ common language code value and place it in ``g`` rather than pass it to1504+ every view.1505+1506+ The function is passed the endpoint name and values dict. The return1507+ value is ignored.1508 """1509 self.url_value_preprocessors.setdefault(None, []).append(f)1510 return f1511 6 unmodified lines1518 self.url_default_functions.setdefault(None, []).append(f)1519 return f1520 1521 def _find_error_handler(self, e):1448- """Finds a registered error handler for the request’s blueprint.1449- Otherwise falls back to the app, returns None if not a suitable1450- handler is found.1522+ """Return a registered error handler for an exception in this order:1523+ blueprint handler for a specific code, app handler for a specific code,1524+ blueprint handler for an exception class, app handler for an exception1525+ class, or ``None`` if a suitable handler is not found.1526 """1527 exc_class, code = self._get_exc_class_and_code(type(e))1528 1454- def find_handler(handler_map):1529+ for name, c in (1530+ (request.blueprint, code), (None, code),1531+ (request.blueprint, None), (None, None)1532+ ):1533+ handler_map = self.error_handler_spec.setdefault(name, {}).get(c)1534+1535 if not handler_map:1456- return1457- queue = deque(exc_class.__mro__)1458- # Protect from geniuses who might create circular references in1459- # __mro__1460- done = set()1536+ continue1537 1462- while queue:1463- cls = queue.popleft()1464- if cls in done:1465- continue1466- done.add(cls)1538+ for cls in exc_class.__mro__:1539 handler = handler_map.get(cls)1540+1541 if handler is not None:1469- # cache for next time exc_class is raised1470- handler_map[exc_class] = handler1542 return handler1543 1473- queue.extend(cls.__mro__)1474-1475- # try blueprint handlers1476- handler = find_handler(self.error_handler_spec1477- .get(request.blueprint, {})1478- .get(code))1479- if handler is not None:1480- return handler1481-1482- # fall back to app handlers1483- return find_handler(self.error_handler_spec[None].get(code))1484-1544 def handle_http_exception(self, e):1545 """Handles an HTTP exception. By default this will invoke the1546 registered error handlers and fall back to returning the1547 exception as response.21 unmodified lines1569 exception is not called and it shows up as regular exception in the1570 traceback. This is helpful for debugging implicitly raised HTTP1571 exceptions.1572 1573+ .. versionchanged:: 1.01574+ Bad request errors are not trapped by default in debug mode.1575+1576 .. versionadded:: 0.81577 """1578 if self.config['TRAP_HTTP_EXCEPTIONS']:1579 return True1518- if self.config['TRAP_BAD_REQUEST_ERRORS']:1580+1581+ trap_bad_request = self.config['TRAP_BAD_REQUEST_ERRORS']1582+1583+ # if unset, trap based on debug mode1584+ if (trap_bad_request is None and self.debug) or trap_bad_request:1585 return isinstance(e, BadRequest)1586+1587 return False1588 1589 def handle_user_exception(self, e):1590 """This method is called whenever an exception occurs that should be2 unmodified lines1593 this function to the :meth:`handle_http_exception` method. This1594 function will either return a response value or reraise the1595 exception with the same traceback.1596 1597+ .. versionchanged:: 1.01598+ Key errors raised from request data like ``form`` show the the bad1599+ key in debug mode rather than a generic bad request message.1600+1601 .. versionadded:: 0.71602 """1603 exc_type, exc_value, tb = sys.exc_info()1604 assert exc_value is e1534-1605 # ensure not to trash sys.exc_info() at that point in case someone1606 # wants the traceback preserved in handle_http_exception. Of course1607 # we cannot prevent users from trashing it themselves in a custom1608 # trap_http_exception method so that's their fault then.1609 1610+ # MultiDict passes the key to the exception, but that's ignored1611+ # when generating the response message. Set an informative1612+ # description for key errors in debug mode or when trapping errors.1613+ if (1614+ (self.debug or self.config['TRAP_BAD_REQUEST_ERRORS'])1615+ and isinstance(e, BadRequestKeyError)1616+ # only set it if it's still the default description1617+ and e.description is BadRequestKeyError.description1618+ ):1619+ e.description = "KeyError: '{0}'".format(*e.args)1620+1621 if isinstance(e, HTTPException) and not self.trap_http_exception(e):1622 return self.handle_http_exception(e)1623 1624 handler = self._find_error_handler(e)28 unmodified lines1653 1654 self.log_exception((exc_type, exc_value, tb))1655 if handler is None:1656 return InternalServerError()1576- return handler(e)1657+ return self.finalize_request(handler(e), from_error_handler=True)1658 1659 def log_exception(self, exc_info):1660 """Logs an exception. This is called by :meth:`handle_exception`1661 if debugging is disabled and right before the handler is called.59 unmodified lines1721 if rv is None:1722 rv = self.dispatch_request()1723 except Exception as e:1724 rv = self.handle_user_exception(e)1725+ return self.finalize_request(rv)1726+1727+ def finalize_request(self, rv, from_error_handler=False):1728+ """Given the return value from a view function this finalizes1729+ the request by converting it into a response and invoking the1730+ postprocessing functions. This is invoked for both normal1731+ request dispatching as well as error handlers.1732+1733+ Because this means that it might be called as a result of a1734+ failure a special safe mode is available which can be enabled1735+ with the `from_error_handler` flag. If enabled, failures in1736+ response processing will be logged and otherwise ignored.1737+1738+ :internal:1739+ """1740 response = self.make_response(rv)1741+ try:1645- response = self.process_response(response)1646- request_finished.send(self, response=response)1742+ response = self.process_response(response)1743+ request_finished.send(self, response=response)1744+ except Exception:1745+ if not from_error_handler:1746+ raise1747+ self.logger.exception('Request finalizing failed with an '1748+ 'error while handling an error')1749 return response1750 1751 def try_trigger_before_first_request_functions(self):1752 """Called before each request and will ensure that it triggers44 unmodified lines1797 """1798 return False1799 1800 def make_response(self, rv):1699- """Converts the return value from a view function to a real1700- response object that is an instance of :attr:`response_class`.1801+ """Convert the return value from a view function to an instance of1802+ :attr:`response_class`.1803 1702- The following types are allowed for `rv`:1804+ :param rv: the return value from the view function. The view function1805+ must return a response. Returning ``None``, or the view ending1806+ without returning, is not allowed. The following types are allowed1807+ for ``view_rv``:1808 1704- .. tabularcolumns:: |p{3.5cm}|p{9.5cm}|1809+ ``str`` (``unicode`` in Python 2)1810+ A response object is created with the string encoded to UTF-81811+ as the body.1812 1706- ======================= ===========================================1707- :attr:`response_class` the object is returned unchanged1708- :class:`str` a response object is created with the1709- string as body1710- :class:`unicode` a response object is created with the1711- string encoded to utf-8 as body1712- a WSGI function the function is called as WSGI application1713- and buffered as response object1714- :class:`tuple` A tuple in the form ``(response, status,1715- headers)`` or ``(response, headers)``1716- where `response` is any of the1717- types defined here, `status` is a string1718- or an integer and `headers` is a list or1719- a dictionary with header values.1720- ======================= ===========================================1813+ ``bytes`` (``str`` in Python 2)1814+ A response object is created with the bytes as the body.1815 1722- :param rv: the return value from the view function1816+ ``tuple``1817+ Either ``(body, status, headers)``, ``(body, status)``, or1818+ ``(body, headers)``, where ``body`` is any of the other types1819+ allowed here, ``status`` is a string or an integer, and1820+ ``headers`` is a dictionary or a list of ``(key, value)``1821+ tuples. If ``body`` is a :attr:`response_class` instance,1822+ ``status`` overwrites the exiting value and ``headers`` are1823+ extended.1824 1825+ :attr:`response_class`1826+ The object is returned unchanged.1827+1828+ other :class:`~werkzeug.wrappers.Response` class1829+ The object is coerced to :attr:`response_class`.1830+1831+ :func:`callable`1832+ The function is called as a WSGI application. The result is1833+ used to create a response object.1834+1835 .. versionchanged:: 0.91836 Previously a tuple was interpreted as the arguments for the1837 response object.1838 """1728- status_or_headers = headers = None1729- if isinstance(rv, tuple):1730- rv, status_or_headers, headers = rv + (None,) * (3 - len(rv))1839 1732- if rv is None:1733- raise ValueError('View function did not return a response')1840+ status = headers = None1841 1735- if isinstance(status_or_headers, (dict, list)):1736- headers, status_or_headers = status_or_headers, None1842+ # unpack tuple returns1843+ if isinstance(rv, (tuple, list)):1844+ len_rv = len(rv)1845 1846+ # a 3-tuple is unpacked directly1847+ if len_rv == 3:1848+ rv, status, headers = rv1849+ # decide if a 2-tuple has status or headers1850+ elif len_rv == 2:1851+ if isinstance(rv[1], (Headers, dict, tuple, list)):1852+ rv, headers = rv1853+ else:1854+ rv, status = rv1855+ # other sized tuples are not allowed1856+ else:1857+ raise TypeError(1858+ 'The view function did not return a valid response tuple.'1859+ ' The tuple must have the form (body, status, headers),'1860+ ' (body, status), or (body, headers).'1861+ )1862+1863+ # the body must not be None1864+ if rv is None:1865+ raise TypeError(1866+ 'The view function did not return a valid response. The'1867+ ' function either returned None or ended without a return'1868+ ' statement.'1869+ )1870+1871+ # make sure the body is an instance of the response class1872 if not isinstance(rv, self.response_class):1739- # When we create a response object directly, we let the constructor1740- # set the headers and status. We do this because there can be1741- # some extra logic involved when creating these objects with1742- # specific values (like default content type selection).1873 if isinstance(rv, (text_type, bytes, bytearray)):1744- rv = self.response_class(rv, headers=headers,1745- status=status_or_headers)1746- headers = status_or_headers = None1874+ # let the response class set the status and headers instead of1875+ # waiting to do it manually, so that the class can handle any1876+ # special logic1877+ rv = self.response_class(rv, status=status, headers=headers)1878+ status = headers = None1879 else:1880+ # evaluate a WSGI callable, or coerce a different response1881+ # class to the correct type1882+ try:1748- rv = self.response_class.force_type(rv, request.environ)1883+ rv = self.response_class.force_type(rv, request.environ)1884+ except TypeError as e:1885+ new_error = TypeError(1886+ '{e}\nThe view function did not return a valid'1887+ ' response. The return type must be a string, tuple,'1888+ ' Response instance, or WSGI callable, but it was a'1889+ ' {rv.__class__.__name__}.'.format(e=e, rv=rv)1890+ )1891+ reraise(TypeError, new_error, sys.exc_info()[2])1892 1893+ # prefer the status if it was provided1750- if status_or_headers is not None:1751- if isinstance(status_or_headers, string_types):1752- rv.status = status_or_headers1894+ if status is not None:1895+ if isinstance(status, (text_type, bytes, bytearray)):1896+ rv.status = status1897 else:1754- rv.status_code = status_or_headers1898+ rv.status_code = status1899+1900+ # extend existing headers with provided headers1901 if headers:1902 rv.headers.extend(headers)1903 1904 return rv16 unmodified lines1921 # to work.1922 if self.config['SERVER_NAME'] is not None:1923 return self.url_map.bind(1924 self.config['SERVER_NAME'],1779- script_name=self.config['APPLICATION_ROOT'] or '/',1925+ script_name=self.config['APPLICATION_ROOT'],1926 url_scheme=self.config['PREFERRED_URL_SCHEME'])1927 1928 def inject_url_defaults(self, endpoint, values):1929 """Injects the URL defaults for the given endpoint directly into29 unmodified lines1959 reraise(exc_type, exc_value, tb)1960 raise error1961 1962 def preprocess_request(self):1817- """Called before the actual request dispatching and will1818- call each :meth:`before_request` decorated function, passing no1819- arguments.1820- If any of these functions returns a value, it's handled as1821- if it was the return value from the view and further1822- request handling is stopped.1963+ """Called before the request is dispatched. Calls1964+ :attr:`url_value_preprocessors` registered with the app and the1965+ current blueprint (if any). Then calls :attr:`before_request_funcs`1966+ registered with the app and the blueprint.1967 1824- This also triggers the :meth:`url_value_processor` functions before1825- the actual :meth:`before_request` functions are called.1968+ If any :meth:`before_request` handler returns a non-None value, the1969+ value is handled as if it was the return value from the view, and1970+ further request handling is stopped.1971 """1972+1973 bp = _request_ctx_stack.top.request.blueprint1974 1975 funcs = self.url_value_preprocessors.get(None, ())1976 if bp is not None and bp in self.url_value_preprocessors:31 unmodified lines2008 funcs = chain(funcs, reversed(self.after_request_funcs[None]))2009 for handler in funcs:2010 response = handler(response)2011 if not self.session_interface.is_null_session(ctx.session):1866- self.save_session(ctx.session, response)2012+ self.session_interface.save_session(self, ctx.session, response)2013 return response2014 2015 def do_teardown_request(self, exc=_sentinel):2016 """Called after the actual request dispatching and will76 unmodified lines2093 2094 def test_request_context(self, *args, **kwargs):2095 """Creates a WSGI environment from the given values (see2096 :class:`werkzeug.test.EnvironBuilder` for more information, this1951- function accepts the same arguments).2097+ function accepts the same arguments plus two additional).2098+2099+ Additional arguments (only if ``base_url`` is not specified):2100+2101+ :param subdomain: subdomain to use for route matching2102+ :param url_scheme: scheme for the request, default2103+ ``PREFERRED_URL_SCHEME`` or ``http``.2104 """2105+2106 from flask.testing import make_test_environ_builder2107+2108 builder = make_test_environ_builder(self, *args, **kwargs)2109+2110 try:2111 return self.request_context(builder.get_environ())2112 finally:2113 builder.close()23 unmodified lines2137 a list of headers and an optional2138 exception context to start the response2139 """2140 ctx = self.request_context(environ)1986- ctx.push()2141 error = None2142 try:2143 try:2144+ ctx.push()2145 response = self.full_dispatch_request()2146 except Exception as e:2147 error = e1993- response = self.make_response(self.handle_exception(e))2148+ response = self.handle_exception(e)2149+ except:2150+ error = sys.exc_info()[1]2151+ raise2152 return response(environ, start_response)2153 finally:2154 if self.should_ignore_error(error):2155 error = None11 unmodified linesmodified:flask/blueprints.py+37 added-8 removed
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+ # TODO remove the next three attrs when Sphinx :inherited-members: works100+ # https://github.com/sphinx-doc/sphinx/issues/741101+102+ #: The name of the package or module that this app belongs to. Do not103+ #: change this once it is set by the constructor.104+ import_name = None105+106+ #: Location of the template files to be added to the template lookup.107+ #: ``None`` if templates should not be added.108+ template_folder = None109+110+ #: Absolute path to the package on the filesystem. Used to look up111+ #: resources contained in the package.112+ root_path = None113+114 def __init__(self, name, import_name, static_folder=None,115 static_url_path=None, template_folder=None,116 url_prefix=None, subdomain=None, url_defaults=None,117 root_path=None):40 unmodified lines158 """159 return BlueprintSetupState(self, app, options, first_registration)160 161 def register(self, app, options, first_registration=False):140- """Called by :meth:`Flask.register_blueprint` to register a blueprint141- on the application. This can be overridden to customize the register142- behavior. Keyword arguments from143- :func:`~flask.Flask.register_blueprint` are directly forwarded to this144- method in the `options` dictionary.162+ """Called by :meth:`Flask.register_blueprint` to register all views163+ and callbacks registered on the blueprint with the application. Creates164+ a :class:`.BlueprintSetupState` and calls each :meth:`record` callback165+ with it.166+167+ :param app: The application this blueprint is being registered with.168+ :param options: Keyword arguments forwarded from169+ :meth:`~Flask.register_blueprint`.170+ :param first_registration: Whether this is the first time this171+ blueprint has been registered on the application.172 """173 self._got_registered_once = True174 state = self.make_setup_state(app, options, first_registration)175+176 if self.has_static_folder:149- state.add_url_rule(self.static_url_path + '/<path:filename>',150- view_func=self.send_static_file,151- endpoint='static')177+ state.add_url_rule(178+ self.static_url_path + '/<path:filename>',179+ view_func=self.send_static_file, endpoint='static'180+ )181 182 for deferred in self.deferred_functions:183 deferred(state)184 258 unmodified linesmodified:flask/cli.py+202 added-37 removed
7 unmodified lines8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12+import ast13+import inspect14 import os15+import re16 import sys14-from threading import Lock, Thread17+import traceback18 from functools import update_wrapper19+from operator import attrgetter20+from threading import Lock, Thread21 22 import click23 24+from . import __version__25 from ._compat import iteritems, reraise26+from .globals import current_app27 from .helpers import get_debug_flag21-from . import __version__28+from ._compat import getargspec29 30+31 class NoAppException(click.UsageError):32 """Raised if an application cannot be found or loaded."""33 34 27-def find_best_app(module):35+def find_best_app(script_info, module):36 """Given a module instance this tries to find the best possible37 application in the module or raises an exception.38 """39 from . import Flask40 41 # Search for the most common names first.34- for attr_name in 'app', 'application':42+ for attr_name in ('app', 'application'):43 app = getattr(module, attr_name, None)36- if app is not None and isinstance(app, Flask):44+ if isinstance(app, Flask):45 return app46 47 # Otherwise find the only object that is a Flask instance.40- matches = [v for k, v in iteritems(module.__dict__)41- if isinstance(v, Flask)]48+ matches = [49+ v for k, v in iteritems(module.__dict__) if isinstance(v, Flask)50+ ]51 52 if len(matches) == 1:53 return matches[0]45- raise NoAppException('Failed to find application in module "%s". Are '46- 'you sure it contains a Flask application? Maybe '47- 'you wrapped it in a WSGI middleware or you are '48- 'using a factory function.' % module.__name__)54+ elif len(matches) > 1:55+ raise NoAppException(56+ 'Auto-detected multiple Flask applications in module "{module}".'57+ ' Use "FLASK_APP={module}:name" to specify the correct'58+ ' one.'.format(module=module.__name__)59+ )60 61+ # Search for app factory functions.62+ for attr_name in ('create_app', 'make_app'):63+ app_factory = getattr(module, attr_name, None)64 65+ if inspect.isfunction(app_factory):66+ try:67+ app = call_factory(app_factory, script_info)68+ if isinstance(app, Flask):69+ return app70+ except TypeError:71+ raise NoAppException(72+ 'Auto-detected "{function}()" in module "{module}", but '73+ 'could not call it without specifying arguments.'.format(74+ function=attr_name, module=module.__name__75+ )76+ )77+78+ raise NoAppException(79+ 'Failed to find application in module "{module}". Are you sure '80+ 'it contains a Flask application? Maybe you wrapped it in a WSGI '81+ 'middleware.'.format(module=module.__name__)82+ )83+84+85+def call_factory(app_factory, script_info, arguments=()):86+ """Takes an app factory, a ``script_info` object and optionally a tuple87+ of arguments. Checks for the existence of a script_info argument and calls88+ the app_factory depending on that and the arguments provided.89+ """90+ args_spec = getargspec(app_factory)91+ arg_names = args_spec.args92+ arg_defaults = args_spec.defaults93+94+ if 'script_info' in arg_names:95+ return app_factory(*arguments, script_info=script_info)96+ elif arguments:97+ return app_factory(*arguments)98+ elif not arguments and len(arg_names) == 1 and arg_defaults is None:99+ return app_factory(script_info)100+ return app_factory()101+102+103+def find_app_by_string(string, script_info, module):104+ """Checks if the given string is a variable name or a function. If it is105+ a function, it checks for specified arguments and whether it takes106+ a ``script_info`` argument and calls the function with the appropriate107+ arguments."""108+ from . import Flask109+ function_regex = r'^(?P<name>\w+)(?:\((?P<args>.*)\))?$'110+ match = re.match(function_regex, string)111+ if match:112+ name, args = match.groups()113+ try:114+ if args is not None:115+ args = args.rstrip(' ,')116+ if args:117+ args = ast.literal_eval(118+ "({args}, )".format(args=args))119+ else:120+ args = ()121+ app_factory = getattr(module, name, None)122+ app = call_factory(app_factory, script_info, args)123+ else:124+ attr = getattr(module, name, None)125+ if inspect.isfunction(attr):126+ app = call_factory(attr, script_info)127+ else:128+ app = attr129+130+ if isinstance(app, Flask):131+ return app132+ else:133+ raise RuntimeError('Failed to find application in module '134+ '"{name}"'.format(name=module))135+ except TypeError as e:136+ new_error = NoAppException(137+ '{e}\nThe app factory "{factory}" in module "{module}" could'138+ ' not be called with the specified arguments (and a'139+ ' script_info argument automatically added if applicable).'140+ ' Did you make sure to use the right number of arguments as'141+ ' well as not using keyword arguments or'142+ ' non-literals?'.format(e=e, factory=string, module=module))143+ reraise(NoAppException, new_error, sys.exc_info()[2])144+ else:145+ raise NoAppException(146+ 'The provided string "{string}" is not a valid variable name'147+ 'or function expression.'.format(string=string))148+149+150 def prepare_exec_for_file(filename):151 """Given a filename this will try to calculate the python path, add it152 to the search path and return the actual module name that is expected.153 """21 unmodified lines175 sys.path.insert(0, dirpath)176 return '.'.join(module[::-1])177 178 80-def locate_app(app_id):179+def locate_app(script_info, app_id):180 """Attempts to locate the application."""181 __traceback_hide__ = True182 if ':' in app_id:183 module, app_obj = app_id.split(':', 1)184 else:185 module = app_id186 app_obj = None187 188+ try:89- __import__(module)189+ __import__(module)190+ except ImportError:191+ # Reraise the ImportError if it occurred within the imported module.192+ # Determine this by checking whether the trace has a depth > 1.193+ if sys.exc_info()[-1].tb_next:194+ stack_trace = traceback.format_exc()195+ raise NoAppException('There was an error trying to import'196+ ' the app (%s):\n%s' % (module, stack_trace))197+ else:198+ raise NoAppException('The file/path provided (%s) does not appear'199+ ' to exist. Please verify the path is '200+ 'correct. If app is not on PYTHONPATH, '201+ 'ensure the extension is .py' % module)202+203 mod = sys.modules[module]204 if app_obj is None:92- app = find_best_app(mod)205+ return find_best_app(script_info, mod)206 else:94- app = getattr(mod, app_obj, None)95- if app is None:96- raise RuntimeError('Failed to find application in module "%s"'97- % module)207+ return find_app_by_string(app_obj, script_info, mod)208 99- return app209 101-210 def find_default_import_path():211 app = os.environ.get('FLASK_APP')212 if app is None:213 return18 unmodified lines232 callback=get_version,233 is_flag=True, is_eager=True)234 235 class DispatchingApp(object):128- """Special application that dispatches to a flask application which236+ """Special application that dispatches to a Flask application which237 is imported by name in a background thread. If an error happens130- it is is recorded and shows as part of the WSGI handling which in case238+ it is recorded and shown as part of the WSGI handling which in case239 of the Werkzeug debugger means that it shows up in the browser.240 """241 242 def __init__(self, loader, use_eager_loading=False):78 unmodified lines321 __traceback_hide__ = True322 if self._loaded_app is not None:323 return self._loaded_app324 if self.create_app is not None:217- rv = self.create_app(self)325+ rv = call_factory(self.create_app, self)326 else:327 if not self.app_import_path:328 raise NoAppException(329 'Could not locate Flask application. You did not provide '330 'the FLASK_APP environment variable.\n\nFor more '331 'information see '332 'http://flask.pocoo.org/docs/latest/quickstart/')225- rv = locate_app(self.app_import_path)333+ rv = locate_app(self, self.app_import_path)334 debug = get_debug_flag()335 if debug is not None:336 rv.debug = debug337 self._loaded_app = rv55 unmodified lines393 For information as of why this is useful see :ref:`custom-scripts`.394 395 :param add_default_commands: if this is True then the default run and396 shell commands wil be added.289- :param add_version_option: adds the :option:`--version` option.397+ :param add_version_option: adds the ``--version`` option.398 :param create_app: an optional callback that is passed the script info399 and returns the loaded app.400 """401 9 unmodified lines411 412 if add_default_commands:413 self.add_command(run_command)414 self.add_command(shell_command)415+ self.add_command(routes_command)416 417 self._loaded_plugin_commands = False418 419 def _load_plugin_commands(self):44 unmodified lines464 # Here we intentionally swallow all exceptions as we don't465 # want the help page to break if the app does not exist.466 # If someone attempts to use the command we try to create467 # the app again and this will give us the error.359- pass468+ # However, we will not do so silently because that would confuse469+ # users.470+ traceback.print_exc()471 return sorted(rv)472 473 def main(self, *args, **kwargs):474 obj = kwargs.get('obj')35 unmodified lines510 Flask is enabled and disabled otherwise.511 """512 from werkzeug.serving import run_simple513 514+ # Set a global flag that indicates that we were invoked from the515+ # command line interface provided server command. This is detected516+ # by Flask.run to make the call into a no-op. This is necessary to517+ # avoid ugly errors when the script that is loaded here also attempts518+ # to start a server.519+ os.environ['FLASK_RUN_FROM_CLI_SERVER'] = '1'520+521 debug = get_debug_flag()522 if reload is None:523 reload = bool(debug)524 if debugger is None:2 unmodified lines527 eager_loading = not reload528 529 app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)530 413- # Extra startup messages. This depends a but on Werkzeug internals to531+ # Extra startup messages. This depends a bit on Werkzeug internals to532 # not double execute when the reloader kicks in.533 if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':534 # If we have an import path we can print it out now which can help535 # people understand what's being served. If we do not have an41 unmodified lines577 578 code.interact(banner=banner, local=ctx)579 580 581+@click.command('routes', short_help='Show the routes for the app.')582+@click.option(583+ '--sort', '-s',584+ type=click.Choice(('endpoint', 'methods', 'rule', 'match')),585+ default='endpoint',586+ help=(587+ 'Method to sort routes by. "match" is the order that Flask will match '588+ 'routes when dispatching a request.'589+ )590+)591+@click.option(592+ '--all-methods',593+ is_flag=True,594+ help="Show HEAD and OPTIONS methods."595+)596+@with_appcontext597+def routes_command(sort, all_methods):598+ """Show all registered routes with endpoints and methods."""599+600+ rules = list(current_app.url_map.iter_rules())601+ ignored_methods = set(() if all_methods else ('HEAD', 'OPTIONS'))602+603+ if sort in ('endpoint', 'rule'):604+ rules = sorted(rules, key=attrgetter(sort))605+ elif sort == 'methods':606+ rules = sorted(rules, key=lambda rule: sorted(rule.methods))607+608+ rule_methods = [609+ ', '.join(sorted(rule.methods - ignored_methods)) for rule in rules610+ ]611+612+ headers = ('Endpoint', 'Methods', 'Rule')613+ widths = (614+ max(len(rule.endpoint) for rule in rules),615+ max(len(methods) for methods in rule_methods),616+ max(len(rule.rule) for rule in rules),617+ )618+ widths = [max(len(h), w) for h, w in zip(headers, widths)]619+ row = '{{0:<{0}}} {{1:<{1}}} {{2:<{2}}}'.format(*widths)620+621+ click.echo(row.format(*headers).strip())622+ click.echo(row.format(*('-' * width for width in widths)))623+624+ for rule, methods in zip(rules, rule_methods):625+ click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())626+627+628 cli = FlaskGroup(help="""\629 This shell command acts as general utility script for Flask applications.630 466-It loads the application configured (either through the FLASK_APP environment631+It loads the application configured (through the FLASK_APP environment632 variable) and then provides commands either provided by the application or633 Flask itself.634 635 The most useful commands are the "run" and "shell" command.10 unmodified lines646 })647 648 649 def main(as_module=False):485- this_module = __package__ + '.cli'650 args = sys.argv[1:]651 652 if as_module:489- if sys.version_info >= (2, 7):490- name = 'python -m ' + this_module.rsplit('.', 1)[0]491- else:492- name = 'python -m ' + this_module653+ this_module = 'flask'654 494- # This module is always executed as "python -m flask.run" and as such495- # we need to ensure that we restore the actual command line so that496- # the reloader can properly operate.497- sys.argv = ['-m', this_module] + sys.argv[1:]655+ if sys.version_info < (2, 7):656+ this_module += '.cli'657+658+ name = 'python -m ' + this_module659+660+ # Python rewrites "python -m flask" to the path to the file in argv.661+ # Restore the original command so that the reloader works.662+ sys.argv = ['-m', this_module] + args663 else:664 name = None665 666 cli.main(args=args, prog_name=name)4 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/ctx.py+11 added-6 removed
323 unmodified lines324 sys.exc_clear()325 326 _request_ctx_stack.push(self)327 328- # Open the session at the moment that the request context is329- # available. This allows a custom open_session method to use the330- # request context (e.g. code that access database information331- # stored on `g` instead of the appcontext).332- self.session = self.app.open_session(self.request)328+ # Open the session at the moment that the request context is available.329+ # This allows a custom open_session method to use the request context.330+ # Only open a new session if this is the first time the request was331+ # pushed, otherwise stream_with_context loses the session.332 if self.session is None:334- self.session = self.app.make_null_session()333+ session_interface = self.app.session_interface334+ self.session = session_interface.open_session(335+ self.app, self.request336+ )337 338+ if self.session is None:339+ self.session = session_interface.make_null_session(self.app)340+341 def pop(self, exc=_sentinel):342 """Pops the request context and unbinds it by doing that. This will343 also trigger the execution of functions registered by the344 :meth:`~flask.Flask.teardown_request` decorator.71 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+146 added-51 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:26 from werkzeug.urls import url_quote27 except ImportError:28 from urlparse import quote as url_quote29 28-from werkzeug.datastructures import Headers29-from werkzeug.exceptions import BadRequest, NotFound30+from werkzeug.datastructures import Headers, Range31+from werkzeug.exceptions import BadRequest, NotFound, \32+ RequestedRangeNotSatisfiable33 34 # this was moved in 0.735 try:36 from werkzeug.wsgi import wrap_file4 unmodified lines41 42 from .signals import message_flashed43 from .globals import session, _request_ctx_stack, _app_ctx_stack, \44 current_app, request42-from ._compat import string_types, text_type, PY245+from ._compat import string_types, text_type46 47 48 # sentinel49 _missing = object()9 unmodified lines59 def get_debug_flag(default=None):60 val = os.environ.get('FLASK_DEBUG')61 if not val:62 return default60- 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)100 unmodified lines440 you can set the application's :attr:`~Flask.use_x_sendfile` attribute441 to ``True`` to directly emit an ``X-Sendfile`` header. This however442 requires support of the underlying webserver for ``X-Sendfile``.443 440- You must explicitly provide the mimetype for the filename or file object.444+ By default it will try to guess the mimetype for you, but you can445+ also explicitly provide one. For extra security you probably want446+ to send certain files as attachment (HTML for instance). The mimetype447+ guessing requires a `filename` or an `attachment_filename` to be448+ provided.449 450+ ETags will also be attached automatically if a `filename` is provided. You451+ can turn this off by setting `add_etags=False`.452+453+ If `conditional=True` and `filename` is provided, this method will try to454+ upgrade the response stream to support range requests. This will allow455+ the request to be answered with partial content response.456+457 Please never pass filenames to this function from user sources;458 you should use :func:`send_from_directory` instead.459 460 .. versionadded:: 0.211 unmodified lines472 .. versionchanged:: 0.9473 cache_timeout pulls its default from application config, when None.474 475 .. versionchanged:: 0.12461- mimetype guessing and etag support removed for file objects.462- If no mimetype or attachment_filename is provided, application/octet-stream463- will be used.476+ The filename is no longer automatically inferred from file objects. If477+ you want to use automatic mimetype and etag support, pass a filepath via478+ `filename_or_fp` or `attachment_filename`.479 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+465- :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 fall494 back to the traditional method. Make sure that the495 file pointer is positioned at the start of data to496 send before calling :func:`send_file`.473- :param mimetype: the mimetype of the file if provided, otherwise474- auto detection happens.497+ :param mimetype: the mimetype of the file if provided. If a file path is498+ given, auto detection happens as fallback, otherwise an499+ error will be raised.500 :param as_attachment: set to ``True`` if you want to send this file with501 a ``Content-Disposition: attachment`` header.502 :param attachment_filename: the filename for the attachment if it503 differs from the file's filename.8 unmodified lines512 a :class:`~datetime.datetime` or timestamp.513 If a file was passed, this overrides its mtime.514 """515 mtime = None516+ fsize = None517 if isinstance(filename_or_fp, string_types):518 filename = filename_or_fp519+ if not os.path.isabs(filename):520+ filename = os.path.join(current_app.root_path, filename)521 file = None522+ if attachment_filename is None:523+ attachment_filename = os.path.basename(filename)524 else:525 file = filename_or_fp496- filename = getattr(file, 'name', None)526+ filename = None527 498- if filename is not None:499- if not os.path.isabs(filename):500- filename = os.path.join(current_app.root_path, filename)501- if mimetype is None and (filename or attachment_filename):502- mimetype = mimetypes.guess_type(filename or attachment_filename)[0]528 if mimetype is None:529+ if attachment_filename is not None:530+ mimetype = mimetypes.guess_type(attachment_filename)[0] \504- mimetype = 'application/octet-stream'531+ or 'application/octet-stream'532 533+ if mimetype is None:534+ raise ValueError(535+ 'Unable to infer MIME-type because no filename is available. '536+ 'Please set either `attachment_filename`, pass a filepath to '537+ '`filename_or_fp` or set your own MIME-type via `mimetype`.'538+ )539+540 headers = Headers()541 if as_attachment:542 if attachment_filename is None:509- if filename is None:510- raise TypeError('filename unavailable, required for '511- 'sending as attachment')543+ raise TypeError('filename unavailable, required for '544+ 'sending as attachment')512- attachment_filename = os.path.basename(filename)513- headers.add('Content-Disposition', 'attachment',514- 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'] = filename520- headers['Content-Length'] = os.path.getsize(filename)563+ fsize = os.path.getsize(filename)564+ headers['Content-Length'] = fsize565 data = None566 else:567 if file is None:568 file = open(filename, 'rb')569 mtime = os.path.getmtime(filename)526- headers['Content-Length'] = os.path.getsize(filename)570+ fsize = os.path.getsize(filename)571+ headers['Content-Length'] = fsize572 data = wrap_file(request.environ, file)573 574 rv = current_app.response_class(data, mimetype=mimetype, headers=headers,575 direct_passthrough=True)9 unmodified lines585 if cache_timeout is not None:586 rv.cache_control.max_age = cache_timeout587 rv.expires = int(time() + cache_timeout)588 544- if add_etags and filename is not None and file is None:589+ if add_etags and filename is not None:590 from warnings import warn591 592 try:593 rv.set_etag('%s-%s-%s' % (7 unmodified lines601 except OSError:602 warn('Access %s failed, maybe it does not exist, so ignore etags in '603 'headers' % filename, stacklevel=2)604 560- if conditional:605+ if conditional:606+ if callable(getattr(Range, 'to_content_range_header', None)):607+ # Werkzeug supports Range Requests608+ # Remove this test when support for Werkzeug <0.12 is dropped609+ try:610+ rv = rv.make_conditional(request, accept_ranges=True,611+ complete_length=fsize)612+ except RequestedRangeNotSatisfiable:613+ file.close()614+ raise615+ else:616 rv = rv.make_conditional(request)562- # make sure we don't send x-sendfile for servers that563- # ignore the 304 status code for x-sendfile.564- if rv.status_code == 304:565- rv.headers.pop('x-sendfile', None)617+ # make sure we don't send x-sendfile for servers that618+ # ignore the 304 status code for x-sendfile.619+ if rv.status_code == 304:620+ rv.headers.pop('x-sendfile', None)621 return rv622 623 624 def safe_join(directory, *pathnames):12 unmodified lines637 :param pathnames: the untrusted pathnames relative to that directory.638 :raises: :class:`~werkzeug.exceptions.NotFound` if one or more passed639 paths fall out of its boundaries.640 """641+642+ parts = [directory]643+644 for filename in pathnames:645 if filename != '':646 filename = posixpath.normpath(filename)589- for sep in _os_alt_seps:590- if sep in filename:591- raise NotFound()592- if os.path.isabs(filename) or \593- filename == '..' or \594- filename.startswith('../'):647+648+ if (649+ any(sep in filename for sep in _os_alt_seps)650+ or os.path.isabs(filename)651+ or filename == '..'652+ or filename.startswith('../')653+ ):654 raise NotFound()596- directory = os.path.join(directory, filename)597- return directory655 656+ parts.append(filename)657 658+ return posixpath.join(*parts)659+660+661 def send_from_directory(directory, filename, **options):662 """Send a file from a given directory with :func:`send_file`. This663 is a secure way to quickly expose static files from an upload folder664 or something similar.182 unmodified lines847 return value848 849 850 class _PackageBoundObject(object):851+ #: The name of the package or module that this app belongs to. Do not852+ #: change this once it is set by the constructor.853+ import_name = None854 855+ #: Location of the template files to be added to the template lookup.856+ #: ``None`` if templates should not be added.857+ template_folder = None858+859+ #: Absolute path to the package on the filesystem. Used to look up860+ #: resources contained in the package.861+ root_path = None862+863 def __init__(self, import_name, template_folder=None, root_path=None):792- #: The name of the package or module. Do not change this once793- #: it was set by the constructor.864 self.import_name = import_name795-796- #: location of the templates. ``None`` if templates should not be797- #: exposed.865 self.template_folder = template_folder866 867 if root_path is None:868 root_path = get_root_path(self.import_name)869 803- #: Where is the app root located?870 self.root_path = root_path805-871 self._static_folder = None872 self._static_url_path = None873 874 def _get_static_folder(self):875 if self._static_folder is not None:876 return os.path.join(self.root_path, self._static_folder)877+878 def _set_static_folder(self, value):879 self._static_folder = value814- static_folder = property(_get_static_folder, _set_static_folder, doc='''815- The absolute path to the configured static folder.816- ''')880+881+ static_folder = property(882+ _get_static_folder, _set_static_folder,883+ doc='The absolute path to the configured static folder.'884+ )885 del _get_static_folder, _set_static_folder886 887 def _get_static_url_path(self):888 if self._static_url_path is not None:889 return self._static_url_path890+891 if self.static_folder is not None:892 return '/' + os.path.basename(self.static_folder)893+894 def _set_static_url_path(self, value):895 self._static_url_path = value826- static_url_path = property(_get_static_url_path, _set_static_url_path)896+897+ static_url_path = property(898+ _get_static_url_path, _set_static_url_path,899+ doc='The URL prefix that the static route will be registered for.'900+ )901 del _get_static_url_path, _set_static_url_path902 903 @property904 def has_static_folder(self):90 unmodified lines995 :returns: number of seconds996 :rtype: int997 """998 return td.days * 60 * 60 * 24 + td.seconds999+1000+1001+def is_ip(value):1002+ """Determine if the given string is an IP address.1003+1004+ :param value: value to check1005+ :type value: str1006+1007+ :return: True if string is an IP address1008+ :rtype: bool1009+ """1010+1011+ for family in (socket.AF_INET, socket.AF_INET6):1012+ try:1013+ socket.inet_pton(family, value)1014+ except socket.error:1015+ pass1016+ else:1017+ return True1018+1019+ return Falsedeleted:flask/json.py-272 removed
1-# -*- coding: utf-8 -*-2-"""3- flask.jsonimpl4- ~~~~~~~~~~~~~~5-6- Implementation helpers for the JSON support in Flask.7-8- :copyright: (c) 2015 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-import io12-import uuid13-from datetime import date14-from .globals import current_app, request15-from ._compat import text_type, PY216-17-from werkzeug.http import http_date18-from jinja2 import Markup19-20-# Use the same json implementation as itsdangerous on which we21-# depend anyways.22-try:23- from itsdangerous import simplejson as _json24-except ImportError:25- from itsdangerous import json as _json26-27-28-# Figure out if simplejson escapes slashes. This behavior was changed29-# from one version to another without reason.30-_slash_escape = '\\/' not in _json.dumps('/')31-32-33-__all__ = ['dump', 'dumps', 'load', 'loads', 'htmlsafe_dump',34- 'htmlsafe_dumps', 'JSONDecoder', 'JSONEncoder',35- 'jsonify']36-37-38-def _wrap_reader_for_text(fp, encoding):39- if isinstance(fp.read(0), bytes):40- fp = io.TextIOWrapper(io.BufferedReader(fp), encoding)41- return fp42-43-44-def _wrap_writer_for_text(fp, encoding):45- try:46- fp.write('')47- except TypeError:48- fp = io.TextIOWrapper(fp, encoding)49- return fp50-51-52-class JSONEncoder(_json.JSONEncoder):53- """The default Flask JSON encoder. This one extends the default simplejson54- encoder by also supporting ``datetime`` objects, ``UUID`` as well as55- ``Markup`` objects which are serialized as RFC 822 datetime strings (same56- as the HTTP date format). In order to support more data types override the57- :meth:`default` method.58- """59-60- def default(self, o):61- """Implement this method in a subclass such that it returns a62- serializable object for ``o``, or calls the base implementation (to63- raise a :exc:`TypeError`).64-65- For example, to support arbitrary iterators, you could implement66- default like this::67-68- def default(self, o):69- try:70- iterable = iter(o)71- except TypeError:72- pass73- else:74- return list(iterable)75- return JSONEncoder.default(self, o)76- """77- if isinstance(o, date):78- return http_date(o.timetuple())79- if isinstance(o, uuid.UUID):80- return str(o)81- if hasattr(o, '__html__'):82- return text_type(o.__html__())83- return _json.JSONEncoder.default(self, o)84-85-86-class JSONDecoder(_json.JSONDecoder):87- """The default JSON decoder. This one does not change the behavior from88- the default simplejson decoder. Consult the :mod:`json` documentation89- for more information. This decoder is not only used for the load90- functions of this module but also :attr:`~flask.Request`.91- """92-93-94-def _dump_arg_defaults(kwargs):95- """Inject default arguments for dump functions."""96- if current_app:97- kwargs.setdefault('cls', current_app.json_encoder)98- if not current_app.config['JSON_AS_ASCII']:99- kwargs.setdefault('ensure_ascii', False)100- kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS'])101- else:102- kwargs.setdefault('sort_keys', True)103- kwargs.setdefault('cls', JSONEncoder)104-105-106-def _load_arg_defaults(kwargs):107- """Inject default arguments for load functions."""108- if current_app:109- kwargs.setdefault('cls', current_app.json_decoder)110- else:111- kwargs.setdefault('cls', JSONDecoder)112-113-114-def dumps(obj, **kwargs):115- """Serialize ``obj`` to a JSON formatted ``str`` by using the application's116- configured encoder (:attr:`~flask.Flask.json_encoder`) if there is an117- application on the stack.118-119- This function can return ``unicode`` strings or ascii-only bytestrings by120- default which coerce into unicode strings automatically. That behavior by121- default is controlled by the ``JSON_AS_ASCII`` configuration variable122- and can be overridden by the simplejson ``ensure_ascii`` parameter.123- """124- _dump_arg_defaults(kwargs)125- encoding = kwargs.pop('encoding', None)126- rv = _json.dumps(obj, **kwargs)127- if encoding is not None and isinstance(rv, text_type):128- rv = rv.encode(encoding)129- return rv130-131-132-def dump(obj, fp, **kwargs):133- """Like :func:`dumps` but writes into a file object."""134- _dump_arg_defaults(kwargs)135- encoding = kwargs.pop('encoding', None)136- if encoding is not None:137- fp = _wrap_writer_for_text(fp, encoding)138- _json.dump(obj, fp, **kwargs)139-140-141-def loads(s, **kwargs):142- """Unserialize a JSON object from a string ``s`` by using the application's143- configured decoder (:attr:`~flask.Flask.json_decoder`) if there is an144- application on the stack.145- """146- _load_arg_defaults(kwargs)147- if isinstance(s, bytes):148- s = s.decode(kwargs.pop('encoding', None) or 'utf-8')149- return _json.loads(s, **kwargs)150-151-152-def load(fp, **kwargs):153- """Like :func:`loads` but reads from a file object.154- """155- _load_arg_defaults(kwargs)156- if not PY2:157- fp = _wrap_reader_for_text(fp, kwargs.pop('encoding', None) or 'utf-8')158- return _json.load(fp, **kwargs)159-160-161-def htmlsafe_dumps(obj, **kwargs):162- """Works exactly like :func:`dumps` but is safe for use in ``<script>``163- tags. It accepts the same arguments and returns a JSON string. Note that164- this is available in templates through the ``|tojson`` filter which will165- also mark the result as safe. Due to how this function escapes certain166- characters this is safe even if used outside of ``<script>`` tags.167-168- The following characters are escaped in strings:169-170- - ``<``171- - ``>``172- - ``&``173- - ``'``174-175- This makes it safe to embed such strings in any place in HTML with the176- notable exception of double quoted attributes. In that case single177- quote your attributes or HTML escape it in addition.178-179- .. versionchanged:: 0.10180- This function's return value is now always safe for HTML usage, even181- if outside of script tags or if used in XHTML. This rule does not182- hold true when using this function in HTML attributes that are double183- quoted. Always single quote attributes if you use the ``|tojson``184- filter. Alternatively use ``|tojson|forceescape``.185- """186- rv = dumps(obj, **kwargs) \187- .replace(u'<', u'\\u003c') \188- .replace(u'>', u'\\u003e') \189- .replace(u'&', u'\\u0026') \190- .replace(u"'", u'\\u0027')191- if not _slash_escape:192- rv = rv.replace('\\/', '/')193- return rv194-195-196-def htmlsafe_dump(obj, fp, **kwargs):197- """Like :func:`htmlsafe_dumps` but writes into a file object."""198- fp.write(text_type(htmlsafe_dumps(obj, **kwargs)))199-200-201-def jsonify(*args, **kwargs):202- """This function wraps :func:`dumps` to add a few enhancements that make203- life easier. It turns the JSON output into a :class:`~flask.Response`204- object with the :mimetype:`application/json` mimetype. For convenience, it205- also converts multiple arguments into an array or multiple keyword arguments206- into a dict. This means that both ``jsonify(1,2,3)`` and207- ``jsonify([1,2,3])`` serialize to ``[1,2,3]``.208-209- For clarity, the JSON serialization behavior has the following differences210- from :func:`dumps`:211-212- 1. Single argument: Passed straight through to :func:`dumps`.213- 2. Multiple arguments: Converted to an array before being passed to214- :func:`dumps`.215- 3. Multiple keyword arguments: Converted to a dict before being passed to216- :func:`dumps`.217- 4. Both args and kwargs: Behavior undefined and will throw an exception.218-219- Example usage::220-221- from flask import jsonify222-223- @app.route('/_get_current_user')224- def get_current_user():225- return jsonify(username=g.user.username,226- email=g.user.email,227- id=g.user.id)228-229- This will send a JSON response like this to the browser::230-231- {232- "username": "admin",233- "email": "admin@localhost",234- "id": 42235- }236-237-238- .. versionchanged:: 0.11239- Added support for serializing top-level arrays. This introduces a240- security risk in ancient browsers. See :ref:`json-security` for details.241-242- This function's response will be pretty printed if it was not requested243- with ``X-Requested-With: XMLHttpRequest`` to simplify debugging unless244- the ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to false.245- Compressed (not pretty) formatting currently means no indents and no246- spaces after separators.247-248- .. versionadded:: 0.2249- """250-251- indent = None252- separators = (',', ':')253-254- if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and not request.is_xhr:255- indent = 2256- separators = (', ', ': ')257-258- if args and kwargs:259- raise TypeError('jsonify() behavior undefined when passed both args and kwargs')260- elif len(args) == 1: # single args are passed directly to dumps()261- data = args[0]262- else:263- data = args or kwargs264-265- return current_app.response_class(266- (dumps(data, indent=indent, separators=separators), '\n'),267- mimetype=current_app.config['JSONIFY_MIMETYPE']268- )269-270-271-def tojson_filter(obj, **kwargs):272- return Markup(htmlsafe_dumps(obj, **kwargs))modified:flask/logging.py+4 added
85 unmodified lines86 del logger.handlers[:]87 logger.__class__ = DebugLogger88 logger.addHandler(debug_handler)89 logger.addHandler(prod_handler)90+91+ # Disable propagation by default92+ logger.propagate = False93+94 return loggermodified:flask/sessions.py+117 added-115 removed
6 unmodified lines7 8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11-12-import uuid11 import hashlib14-from base64 import b64encode, b64decode12+import warnings13 from datetime import datetime16-from werkzeug.http import http_date, parse_date14+15+from itsdangerous import BadSignature, URLSafeTimedSerializer16 from werkzeug.datastructures import CallbackDict18-from . import Markup, json19-from ._compat import iteritems, text_type20-from .helpers import total_seconds17 22-from itsdangerous import URLSafeTimedSerializer, BadSignature18+from flask.helpers import is_ip, total_seconds19+from flask.json.tag import TaggedJSONSerializer20 21 22 class SessionMixin(object):23 """Expands a basic dictionary with an accessors that are expected20 unmodified lines44 #: long as changes do not happen on mutable structures in the session.45 #: The default mixin implementation just hardcodes ``True`` in.46 modified = True47 48+ #: the accessed variable indicates whether or not the session object has49+ #: been accessed in that request. This allows flask to append a `Vary:50+ #: Cookie` header to the response if the session is being accessed. This51+ #: allows caching proxy servers, like Varnish, to use both the URL and the52+ #: session cookie as keys when caching pages, preventing multiple users53+ #: from being served the same cache.54+ accessed = True55 52-def _tag(value):53- if isinstance(value, tuple):54- return {' t': [_tag(x) for x in value]}55- elif isinstance(value, uuid.UUID):56- return {' u': value.hex}57- elif isinstance(value, bytes):58- return {' b': b64encode(value).decode('ascii')}59- elif callable(getattr(value, '__html__', None)):60- return {' m': text_type(value.__html__())}61- elif isinstance(value, list):62- return [_tag(x) for x in value]63- elif isinstance(value, datetime):64- return {' d': http_date(value)}65- elif isinstance(value, dict):66- return dict((k, _tag(v)) for k, v in iteritems(value))67- elif isinstance(value, str):68- try:69- return text_type(value)70- except UnicodeError:71- from flask.debughelpers import UnexpectedUnicodeError72- raise UnexpectedUnicodeError(u'A byte string with '73- u'non-ASCII data was passed to the session system '74- u'which can only store unicode strings. Consider '75- u'base64 encoding your string (String was %r)' % value)76- return value56 78-79-class TaggedJSONSerializer(object):80- """A customized JSON serializer that supports a few extra types that81- we take for granted when serializing (tuples, markup objects, datetime).82- """83-84- def dumps(self, value):85- return json.dumps(_tag(value), separators=(',', ':'))86-87- def loads(self, value):88- def object_hook(obj):89- if len(obj) != 1:90- return obj91- 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)102- return obj103- return json.loads(value, object_hook=object_hook)104-105-106-session_json_serializer = TaggedJSONSerializer()107-108-57 class SecureCookieSession(CallbackDict, SessionMixin):58 """Base class for sessions based on signed cookies."""59 60 def __init__(self, initial=None):61 def on_update(self):62 self.modified = True115- CallbackDict.__init__(self, initial, on_update)63+ self.accessed = True64+65+ super(SecureCookieSession, self).__init__(initial, on_update)66 self.modified = False67+ self.accessed = False68 69+ def __getitem__(self, key):70+ self.accessed = True71+ return super(SecureCookieSession, self).__getitem__(key)72 73+ def get(self, key, default=None):74+ self.accessed = True75+ return super(SecureCookieSession, self).get(key, default)76+77+ def setdefault(self, key, default=None):78+ self.accessed = True79+ return super(SecureCookieSession, self).setdefault(key, default)80+81+82 class NullSession(SecureCookieSession):83 """Class used to generate nicer error messages if sessions are not84 available. Will still allow read-only access to the empty session85 but fail on setting.44 unmodified lines130 #: this type.131 null_session_class = NullSession132 133 #: A flag that indicates if the session interface is pickle based.171- #: This can be used by flask extensions to make a decision in regards134+ #: This can be used by Flask extensions to make a decision in regards135 #: to how to deal with the session object.136 #:137 #: .. versionadded:: 0.10138 pickle_based = False19 unmodified lines158 """159 return isinstance(obj, self.null_session_class)160 161 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.162+ """Returns the domain that should be set for the session cookie.163+164+ Uses ``SESSION_COOKIE_DOMAIN`` if it is configured, otherwise165+ falls back to detecting the domain based on ``SERVER_NAME``.166+167+ Once detected (or if not set at all), ``SESSION_COOKIE_DOMAIN`` is168+ updated to avoid re-running the logic.169 """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]170 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 = None171+ rv = app.config['SESSION_COOKIE_DOMAIN']172 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('.')173+ # set explicitly, or cached from SERVER_NAME detection174+ # if False, return None175+ if rv is not None:176+ return rv if rv else None177 222- return rv178+ rv = app.config['SERVER_NAME']179 180+ # server name not set, cache False to return none next time181+ if not rv:182+ app.config['SESSION_COOKIE_DOMAIN'] = False183+ return None184+185+ # chop off the port which is usually not supported by browsers186+ # remove any leading '.' since we'll add that later187+ rv = rv.rsplit(':', 1)[0].lstrip('.')188+189+ if '.' not in rv:190+ # Chrome doesn't allow names without a '.'191+ # this should only come up with localhost192+ # hack around this by not setting the name, and show a warning193+ warnings.warn(194+ '"{rv}" is not a valid cookie domain, it must contain a ".".'195+ ' Add an entry to your hosts file, for example'196+ ' "{rv}.localdomain", and use that instead.'.format(rv=rv)197+ )198+ app.config['SESSION_COOKIE_DOMAIN'] = False199+ return None200+201+ ip = is_ip(rv)202+203+ if ip:204+ warnings.warn(205+ 'The session cookie domain is an IP address. This may not work'206+ ' as intended in some browsers. Add an entry to your hosts'207+ ' file, for example "localhost.localdomain", and use that'208+ ' instead.'209+ )210+211+ # if this is not an ip and app is mounted at the root, allow subdomain212+ # matching by adding a '.' prefix213+ if self.get_cookie_path(app) == '/' and not ip:214+ rv = '.' + rv215+216+ app.config['SESSION_COOKIE_DOMAIN'] = rv217+ return rv218+219 def get_cookie_path(self, app):220 """Returns the path for which the cookie should be valid. The221 default implementation uses the value from the ``SESSION_COOKIE_PATH``222 config var if it's set, and falls back to ``APPLICATION_ROOT`` or223 uses ``/`` if it's ``None``.224 """230- return app.config['SESSION_COOKIE_PATH'] or \231- app.config['APPLICATION_ROOT'] or '/'225+ return app.config['SESSION_COOKIE_PATH'] \226+ or app.config['APPLICATION_ROOT']227 228 def get_cookie_httponly(self, app):229 """Returns True if the session cookie should be httponly. This230 currently just returns the value of the ``SESSION_COOKIE_HTTPONLY``16 unmodified lines247 if session.permanent:248 return datetime.utcnow() + app.permanent_session_lifetime249 250 def should_set_cookie(self, app, session):256- """Indicates whether a cookie should be set now or not. This is257- used by session backends to figure out if they should emit a258- set-cookie header or not. The default behavior is controlled by259- the ``SESSION_REFRESH_EACH_REQUEST`` config variable. If260- it's set to ``False`` then a cookie is only set if the session is261- modified, if set to ``True`` it's always set if the session is262- permanent.251+ """Used by session backends to determine if a ``Set-Cookie`` header252+ should be set for this session cookie for this response. If the session253+ has been modified, the cookie is set. If the session is permanent and254+ the ``SESSION_REFRESH_EACH_REQUEST`` config is true, the cookie is255+ always set.256 264- This check is usually skipped if sessions get deleted.257+ This check is usually skipped if the session was deleted.258 259 .. versionadded:: 0.11260 """268- if session.modified:269- return True270- save_each = app.config['SESSION_REFRESH_EACH_REQUEST']271- return save_each and session.permanent261 262+ return session.modified or (263+ session.permanent and app.config['SESSION_REFRESH_EACH_REQUEST']264+ )265+266 def open_session(self, app, request):267 """This method has to be implemented and must either return ``None``268 in case the loading failed because of a configuration error or an269 instance of a session object which implements a dictionary like9 unmodified lines279 """280 raise NotImplementedError()281 282 283+session_json_serializer = TaggedJSONSerializer()284+285+286 class SecureCookieSessionInterface(SessionInterface):287 """The default session interface that stores sessions in signed cookies288 through the :mod:`itsdangerous` module.289 """39 unmodified lines329 def save_session(self, app, session, response):330 domain = self.get_cookie_domain(app)331 path = self.get_cookie_path(app)332 337- # Delete case. If there is no session we bail early.338- # If the session was modified to be empty we remove the339- # whole cookie.333+ # If the session is modified to be empty, remove the cookie.334+ # If the session is empty, return without setting the cookie.335 if not session:336 if session.modified:342- response.delete_cookie(app.session_cookie_name,343- domain=domain, path=path)337+ response.delete_cookie(338+ app.session_cookie_name,339+ domain=domain,340+ path=path341+ )342+343 return344 346- # Modification case. There are upsides and downsides to347- # emitting a set-cookie header each request. The behavior348- # is controlled by the :meth:`should_set_cookie` method349- # which performs a quick check to figure out if the cookie350- # should be set or not. This is controlled by the351- # SESSION_REFRESH_EACH_REQUEST config flag as well as352- # the permanent flag on the session itself.345+ # Add a "Vary: Cookie" header if the session was accessed at all.346+ if session.accessed:347+ response.vary.add('Cookie')348+349 if not self.should_set_cookie(app, session):350 return351 352 httponly = self.get_cookie_httponly(app)353 secure = self.get_cookie_secure(app)354 expires = self.get_expiration_time(app, session)355 val = self.get_signing_serializer(app).dumps(dict(session))360- response.set_cookie(app.session_cookie_name, val,361- expires=expires, httponly=httponly,362- domain=domain, path=path, secure=secure)356+ response.set_cookie(357+ app.session_cookie_name,358+ val,359+ expires=expires,360+ httponly=httponly,361+ domain=domain,362+ path=path,363+ secure=secure364+ )modified: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+59 added-13 removed
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+from flask.json import dumps as json_dumps18 19 try:20 from werkzeug.urls import url_parse21 except ImportError:22 from urlparse import urlsplit as url_parse23 24 23-def make_test_environ_builder(app, path='/', base_url=None, *args, **kwargs):25+def make_test_environ_builder(26+ app, path='/', base_url=None, subdomain=None, url_scheme=None,27+ *args, **kwargs28+):29 """Creates a new test builder with some application defaults thrown in."""25- http_host = app.config.get('SERVER_NAME')26- app_root = app.config.get('APPLICATION_ROOT')30+31+ assert (32+ not (base_url or subdomain or url_scheme)33+ or (base_url is not None) != bool(subdomain or url_scheme)34+ ), 'Cannot pass "subdomain" or "url_scheme" with "base_url".'35+36 if base_url is None:37+ http_host = app.config.get('SERVER_NAME') or 'localhost'38+ app_root = app.config['APPLICATION_ROOT']39+40+ if subdomain:41+ http_host = '{0}.{1}'.format(subdomain, http_host)42+43+ if url_scheme is None:44+ url_scheme = app.config['PREFERRED_URL_SCHEME']45+46 url = url_parse(path)29- base_url = 'http://%s/' % (url.netloc or http_host or 'localhost')30- if app_root:31- base_url += app_root.lstrip('/')32- if url.netloc:33- path = url.path34- if url.query:35- path += '?' + url.query47+ base_url = '{0}://{1}/{2}'.format(48+ url_scheme, url.netloc or http_host, app_root.lstrip('/')49+ )50+ path = url.path51+52+ if url.query:53+ sep = b'?' if isinstance(url.query, bytes) else '?'54+ path += sep + url.query55+56+ if 'json' in kwargs:57+ assert 'data' not in kwargs, (58+ "Client cannot provide both 'json' and 'data'."59+ )60+61+ # push a context so flask.json can use app's json attributes62+ with app.app_context():63+ kwargs['data'] = json_dumps(kwargs.pop('json'))64+65+ if 'content_type' not in kwargs:66+ kwargs['content_type'] = 'application/json'67+68 return EnvironBuilder(path, base_url, *args, **kwargs)69 70 71 class FlaskClient(Client):2 unmodified lines74 end of a ``with`` body when used in a ``with`` statement. For general75 information about how to use this class refer to76 :class:`werkzeug.test.Client`.77 78+ .. versionchanged:: 0.1279+ `app.test_client()` includes preset default environment, which can be80+ set after instantiation of the `app.test_client()` object in81+ `client.environ_base`.82+83 Basic usage is outlined in the :ref:`testing` chapter.84 """85 86 preserve_context = False87 88+ def __init__(self, *args, **kwargs):89+ super(FlaskClient, self).__init__(*args, **kwargs)90+ self.environ_base = {91+ "REMOTE_ADDR": "127.0.0.1",92+ "HTTP_USER_AGENT": "werkzeug/" + werkzeug.__version__93+ }94+95 @contextmanager96 def session_transaction(self, *args, **kwargs):97 """When used in combination with a ``with`` statement this opens a98 session transaction. This can be used to modify the session that18 unmodified lines117 environ_overrides = kwargs.setdefault('environ_overrides', {})118 self.cookie_jar.inject_wsgi(environ_overrides)119 outer_reqctx = _request_ctx_stack.top120 with app.test_request_context(*args, **kwargs) as c:77- sess = app.open_session(c.request)121+ session_interface = app.session_interface122+ sess = session_interface.open_session(app, c.request)123 if sess is None:124 raise RuntimeError('Session backend did not open a session. '125 'Check the configuration')126 10 unmodified lines137 finally:138 _request_ctx_stack.pop()139 140 resp = app.response_class()96- if not app.session_interface.is_null_session(sess):97- app.save_session(sess, resp)141+ if not session_interface.is_null_session(sess):142+ session_interface.save_session(app, sess, resp)143 headers = resp.get_wsgi_headers(c.request.environ)144 self.cookie_jar.extract_wsgi(c.request.environ, headers)145 146 def open(self, *args, **kwargs):147 kwargs.setdefault('environ_overrides', {}) \148 ['flask._preserve_context'] = self.preserve_context149+ kwargs.setdefault('environ_base', self.environ_base)150 151 as_tuple = kwargs.pop('as_tuple', False)152 buffered = kwargs.pop('buffered', False)153 follow_redirects = kwargs.pop('follow_redirects', False)22 unmodified linesmodified:flask/views.py+26 added-18 removed
49 unmodified lines50 51 #: A list of methods this view can handle.52 methods = None53 54+ #: Setting this disables or force-enables the automatic options handling.55+ provide_automatic_options = None56+57 #: The canonical way to decorate class-based views is to decorate the58 #: return value of as_view(). However since this moves parts of the59 #: logic from the class declaration to the place where it's hooked60 #: into the routing system.40 unmodified lines101 view.__name__ = name102 view.__doc__ = cls.__doc__103 view.__module__ = cls.__module__104 view.methods = cls.methods105+ view.provide_automatic_options = cls.provide_automatic_options106 return view107 108 109 class MethodViewType(type):110+ """Metaclass for :class:`MethodView` that determines what methods the view111+ defines.112+ """113 107- def __new__(cls, name, bases, d):108- rv = type.__new__(cls, name, bases, d)114+ def __init__(cls, name, bases, d):115+ super(MethodViewType, cls).__init__(name, bases, d)116+117 if 'methods' not in d:110- methods = set(rv.methods or [])111- for key in d:112- if key in http_method_funcs:118+ methods = set()119+120+ for key in http_method_funcs:121+ if hasattr(cls, key):122 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).123+124+ # If we have no method at all in there we don't want to add a125+ # method list. This is for instance the case for the base class126+ # or another subclass of a base method view that does not introduce127+ # new methods.128 if methods:119- rv.methods = sorted(methods)120- return rv129+ cls.methods = methods130 131 132 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 you will response to ``'GET'`` requests and127- the :meth:`dispatch_request` implementation will automatically128- forward your request to that. Also :attr:`options` is set for you129- automatically::133+ """A class-based view that dispatches request methods to the corresponding134+ class methods. For example, if you implement a ``get`` method, it will be135+ used to handle ``GET`` requests. ::136 137 class CounterAPI(MethodView):132-138 def get(self):139 return session.get('counter', 0)140 141 def post(self):1 unmodified line143 return 'OK'144 145 app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))146 """147+148 def dispatch_request(self, *args, **kwargs):149 meth = getattr(self, request.method.lower(), None)150+151 # If the request method is HEAD and we don't have a handler for it152 # retry with GET.153 if meth is None and request.method == 'HEAD':154 meth = getattr(self, 'get', None)155+156 assert meth is not None, 'Unimplemented method %r' % request.method157 return meth(*args, **kwargs)modified:flask/wrappers.py+113 added-102 removed
6 unmodified lines7 8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11+from warnings import warn12 12-from werkzeug.wrappers import Request as RequestBase, Response as ResponseBase13 from werkzeug.exceptions import BadRequest14+from werkzeug.wrappers import Request as RequestBase, Response as ResponseBase15 15-from . import json16-from .globals import _request_ctx_stack16+from flask import json17+from flask.globals import current_app18 18-_missing = object()19 20+class JSONMixin(object):21+ """Common mixin for both request and response objects to provide JSON22+ parsing capabilities.23 21-def _get_data(req, cache):22- getter = getattr(req, 'get_data', None)23- if getter is not None:24- return getter(cache=cache)25- return req.data24+ .. versionadded:: 1.025+ """26 27+ _cached_json = Ellipsis28 29+ @property30+ def is_json(self):31+ """Check if the mimetype indicates JSON data, either32+ :mimetype:`application/json` or :mimetype:`application/*+json`.33+34+ .. versionadded:: 0.1135+ """36+ mt = self.mimetype37+ return (38+ mt == 'application/json'39+ or (mt.startswith('application/')) and mt.endswith('+json')40+ )41+42+ @property43+ def json(self):44+ """This will contain the parsed JSON data if the mimetype indicates45+ JSON (:mimetype:`application/json`, see :meth:`is_json`), otherwise it46+ will be ``None``.47+48+ .. deprecated:: 1.049+ Use :meth:`get_json` instead.50+ """51+ warn(DeprecationWarning(52+ "'json' is deprecated. Use 'get_json()' instead."53+ ), stacklevel=2)54+ return self.get_json()55+56+ def _get_data_for_json(self, cache):57+ return self.get_data(cache=cache)58+59+ def get_json(self, force=False, silent=False, cache=True):60+ """Parse and return the data as JSON. If the mimetype does not indicate61+ JSON (:mimetype:`application/json`, see :meth:`is_json`), this returns62+ ``None`` unless ``force`` is true. If parsing fails,63+ :meth:`on_json_loading_failed` is called and its return value is used64+ as the return value.65+66+ :param force: Ignore the mimetype and always try to parse JSON.67+ :param silent: Silence parsing errors and return ``None`` instead.68+ :param cache: Store the parsed JSON to return for subsequent calls.69+ """70+ if cache and self._cached_json is not Ellipsis:71+ return self._cached_json72+73+ if not (force or self.is_json):74+ return None75+76+ # We accept MIME charset against the specification as certain clients77+ # have used this in the past. For responses, we assume that if the78+ # charset is set then the data has been encoded correctly as well.79+ charset = self.mimetype_params.get('charset')80+81+ try:82+ data = self._get_data_for_json(cache=cache)83+ rv = json.loads(data, encoding=charset)84+ except ValueError as e:85+ if silent:86+ rv = None87+ else:88+ rv = self.on_json_loading_failed(e)89+90+ if cache:91+ self._cached_json = rv92+93+ return rv94+95+ def on_json_loading_failed(self, e):96+ """Called if :meth:`get_json` parsing fails and isn't silenced. If97+ this method returns a value, it is used as the return value for98+ :meth:`get_json`. The default implementation raises a99+ :class:`BadRequest` exception.100+101+ .. versionchanged:: 0.10102+ Raise a :exc:`BadRequest` error instead of returning an error103+ message as JSON. If you want that behavior you can add it by104+ subclassing.105+106+ .. versionadded:: 0.8107+ """108+ if current_app is not None and current_app.debug:109+ raise BadRequest('Failed to decode JSON object: {0}'.format(e))110+111+ raise BadRequest()112+113+28-class Request(RequestBase):114+class Request(RequestBase, JSONMixin):115 """The request object used by default in Flask. Remembers the116 matched endpoint and view arguments.117 118 It is what ends up as :class:`~flask.request`. If you want to replace28 unmodified lines147 148 @property149 def max_content_length(self):150 """Read-only view of the ``MAX_CONTENT_LENGTH`` config key."""65- ctx = _request_ctx_stack.top66- if ctx is not None:67- return ctx.app.config['MAX_CONTENT_LENGTH']151+ if current_app:152+ return current_app.config['MAX_CONTENT_LENGTH']153 154 @property155 def endpoint(self):156 """The endpoint that matched the request. This in combination with22 unmodified lines179 """The name of the current blueprint"""180 if self.url_rule and '.' in self.url_rule.endpoint:181 return self.url_rule.endpoint.rsplit('.', 1)[0]182 98- @property99- def json(self):100- """If the mimetype is :mimetype:`application/json` this will contain the101- parsed JSON data. Otherwise this will be ``None``.102-103- The :meth:`get_json` method should be used instead.104- """105- from warnings import warn106- warn(DeprecationWarning('json is deprecated. '107- 'Use get_json() instead.'), stacklevel=2)108- return self.get_json()109-110- @property111- def is_json(self):112- """Indicates if this request is JSON or not. By default a request113- is considered to include JSON data if the mimetype is114- :mimetype:`application/json` or :mimetype:`application/*+json`.115-116- .. versionadded:: 0.11117- """118- mt = self.mimetype119- if mt == 'application/json':120- return True121- if mt.startswith('application/') and mt.endswith('+json'):122- return True123- return False124-125- def get_json(self, force=False, silent=False, cache=True):126- """Parses the incoming JSON request data and returns it. By default127- this function will return ``None`` if the mimetype is not128- :mimetype:`application/json` but this can be overridden by the129- ``force`` parameter. If parsing fails the130- :meth:`on_json_loading_failed` method on the request object will be131- invoked.132-133- :param force: if set to ``True`` the mimetype is ignored.134- :param silent: if set to ``True`` this method will fail silently135- and return ``None``.136- :param cache: if set to ``True`` the parsed JSON data is remembered137- on the request.138- """139- rv = getattr(self, '_cached_json', _missing)140- if rv is not _missing:141- return rv142-143- if not (force or self.is_json):144- return None145-146- # We accept a request charset against the specification as147- # certain clients have been using this in the past. This148- # fits our general approach of being nice in what we accept149- # and strict in what we send out.150- request_charset = self.mimetype_params.get('charset')151- try:152- data = _get_data(self, cache)153- if request_charset is not None:154- rv = json.loads(data, encoding=request_charset)155- else:156- rv = json.loads(data)157- except ValueError as e:158- if silent:159- rv = None160- else:161- rv = self.on_json_loading_failed(e)162- if cache:163- self._cached_json = rv164- return rv165-166- def on_json_loading_failed(self, e):167- """Called if decoding of the JSON data failed. The return value of168- this method is used by :meth:`get_json` when an error occurred. The169- default implementation just raises a :class:`BadRequest` exception.170-171- .. versionchanged:: 0.10172- Removed buggy previous behavior of generating a random JSON173- response. If you want that behavior back you can trivially174- add it by subclassing.175-176- .. versionadded:: 0.8177- """178- ctx = _request_ctx_stack.top179- if ctx is not None and ctx.app.config.get('DEBUG', False):180- raise BadRequest('Failed to decode JSON object: {0}'.format(e))181- raise BadRequest()182-183 def _load_form_data(self):184 RequestBase._load_form_data(self)185 186 # In debug mode we're replacing the files multidict with an ad-hoc187 # subclass that raises a different error for key errors.188- ctx = _request_ctx_stack.top189- if ctx is not None and ctx.app.debug and \190- self.mimetype != 'multipart/form-data' and not self.files:188+ if (189+ current_app190+ and current_app.debug191+ and self.mimetype != 'multipart/form-data'192+ and not self.files193+ ):194 from .debughelpers import attach_enctype_error_multidict195 attach_enctype_error_multidict(self)196 197 195-class Response(ResponseBase):198+class Response(ResponseBase, JSONMixin):199 """The response object that is used by default in Flask. Works like the200 response object from Werkzeug but is set to have an HTML mimetype by201 default. Quite often you don't have to create this object yourself because202 :meth:`~flask.Flask.make_response` will take care of that for you.203 204 If you want to replace the response object used you can subclass this and205 set :attr:`~flask.Flask.response_class` to your subclass.206+207+ .. versionchanged:: 1.0208+ JSON support is added to the response, like the request. This is useful209+ when testing to get the test client response data as JSON.210 """211+212 default_mimetype = 'text/html'213+214+ def _get_data_for_json(self, cache):215+ return self.get_data()modified: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/factory.py+15 added
1+from __future__ import absolute_import, print_function2+3+from flask import Flask4+5+6+def create_app():7+ return Flask('create_app')8+9+10+def create_app2(foo, bar):11+ return Flask("_".join(['create_app2', foo, bar]))12+13+14+def create_app3(foo, bar, script_info):15+ return Flask("_".join(['create_app3', foo, bar]))added: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/conftest.py+55 added-16 removed
11 unmodified lines12 import sys13 import pkgutil14 import pytest15 import textwrap16+from flask import Flask as _Flask17 18 19+class Flask(_Flask):20+ testing = True21+ secret_key = __name__22+23+ def make_response(self, rv):24+ if rv is None:25+ rv = ''26+ return super(Flask, self).make_response(rv)27+28+29 @pytest.fixture30+def app():31+ app = Flask(__name__)32+ return app33+34+35+@pytest.fixture36+def app_ctx(app):37+ with app.app_context() as ctx:38+ yield ctx39+40+41+@pytest.fixture42+def req_ctx(app):43+ with app.test_request_context() as ctx:44+ yield ctx45+46+47+@pytest.fixture48+def client(app):49+ return app.test_client()50+51+52+@pytest.fixture53 def test_apps(monkeypatch):54 monkeypatch.syspath_prepend(55 os.path.abspath(os.path.join(56 os.path.dirname(__file__), 'test_apps'))57 )58 59+60 @pytest.fixture(autouse=True)26-def leak_detector(request):27- def ensure_clean_request_context():28- # make sure we're not leaking a request context since we are29- # testing flask internally in debug mode in a few cases30- leaks = []31- while flask._request_ctx_stack.top is not None:32- leaks.append(flask._request_ctx_stack.pop())33- assert leaks == []34- request.addfinalizer(ensure_clean_request_context)61+def leak_detector():62+ yield63 64+ # make sure we're not leaking a request context since we are65+ # testing flask internally in debug mode in a few cases66+ leaks = []67+ while flask._request_ctx_stack.top is not None:68+ leaks.append(flask._request_ctx_stack.pop())69+ assert leaks == []70 71+72 @pytest.fixture(params=(True, False))73 def limit_loader(request, monkeypatch):74 """Patch pkgutil.get_loader to give loader without get_filename or archive.75 20 unmodified lines96 old_get_loader = pkgutil.get_loader97 98 def get_loader(*args, **kwargs):99 return LimitedLoader(old_get_loader(*args, **kwargs))100+101 monkeypatch.setattr(pkgutil, 'get_loader', get_loader)102 103 104 @pytest.fixture105 def modules_tmpdir(tmpdir, monkeypatch):70- '''A tmpdir added to sys.path'''106+ """A tmpdir added to sys.path."""107 rv = tmpdir.mkdir('modules_tmpdir')108 monkeypatch.syspath_prepend(str(rv))109 return rv110 5 unmodified lines116 117 118 @pytest.fixture119 def site_packages(modules_tmpdir, monkeypatch):84- '''Create a fake site-packages'''120+ """Create a fake site-packages."""121 rv = modules_tmpdir \86- .mkdir('lib')\87- .mkdir('python{x[0]}.{x[1]}'.format(x=sys.version_info))\122+ .mkdir('lib') \123+ .mkdir('python{x[0]}.{x[1]}'.format(x=sys.version_info)) \124 .mkdir('site-packages')125 monkeypatch.syspath_prepend(str(rv))126 return rv127 128 129 @pytest.fixture130 def install_egg(modules_tmpdir, monkeypatch):95- '''Generate egg from package name inside base and put the egg into96- sys.path'''131+ """Generate egg from package name inside base and put the egg into132+ sys.path."""133+134 def inner(name, base=modules_tmpdir):135 if not isinstance(name, str):136 raise ValueError(name)137 base.join(name).ensure_dir()15 unmodified lines153 )154 egg_path, = modules_tmpdir.join('dist/').listdir()155 monkeypatch.syspath_prepend(str(egg_path))156 return egg_path157+158 return inner159 160 161 @pytest.fixture162 def purge_module(request):163 def inner(name):164 request.addfinalizer(lambda: sys.modules.pop(name, None))165+166 return inner167 168 169 @pytest.yield_fixture(autouse=True)170 def catch_deprecation_warnings(recwarn):171 yield172 gc.collect()134- assert not recwarn.list173+ assert not recwarn.list, '\n'.join(str(w.message) for w in recwarn.list)modified:tests/test_appctx.py+50 added-44 removed
12 unmodified lines13 14 import flask15 16 17-def test_basic_url_generation():18- app = flask.Flask(__name__)17+def test_basic_url_generation(app):18 app.config['SERVER_NAME'] = 'localhost'19 app.config['PREFERRED_URL_SCHEME'] = 'https'20 21 @app.route('/')3 unmodified lines25 with app.app_context():26 rv = flask.url_for('index')27 assert rv == 'https://localhost/'28 30-def test_url_generation_requires_server_name():31- app = flask.Flask(__name__)29+30+def test_url_generation_requires_server_name(app):31 with app.app_context():32 with pytest.raises(RuntimeError):33 flask.url_for('index')34 35+36 def test_url_generation_without_context_fails():37 with pytest.raises(RuntimeError):38 flask.url_for('index')39 40-def test_request_context_means_app_context():41- app = flask.Flask(__name__)40+41+def test_request_context_means_app_context(app):42 with app.test_request_context():43 assert flask.current_app._get_current_object() == app44 assert flask._app_ctx_stack.top is None45 46-def test_app_context_provides_current_app():47- app = flask.Flask(__name__)46+47+def test_app_context_provides_current_app(app):48 with app.app_context():49 assert flask.current_app._get_current_object() == app50 assert flask._app_ctx_stack.top is None51 52+52-def test_app_tearing_down():53+def test_app_tearing_down(app):54 cleanup_stuff = []54- app = flask.Flask(__name__)55+56 @app.teardown_appcontext57 def cleanup(exception):58 cleanup_stuff.append(exception)59 1 unmodified line61 pass62 63 assert cleanup_stuff == [None]64 65+64-def test_app_tearing_down_with_previous_exception():66+def test_app_tearing_down_with_previous_exception(app):67 cleanup_stuff = []66- app = flask.Flask(__name__)68+69 @app.teardown_appcontext70 def cleanup(exception):71 cleanup_stuff.append(exception)72 6 unmodified lines79 pass80 81 assert cleanup_stuff == [None]82 83+81-def test_app_tearing_down_with_handled_exception():84+def test_app_tearing_down_with_handled_exception(app):85 cleanup_stuff = []83- app = flask.Flask(__name__)86+87 @app.teardown_appcontext88 def cleanup(exception):89 cleanup_stuff.append(exception)90 4 unmodified lines95 pass96 97 assert cleanup_stuff == [None]98 96-def test_app_ctx_globals_methods():97- app = flask.Flask(__name__)98- with app.app_context():99- # get100- assert flask.g.get('foo') is None101- assert flask.g.get('foo', 'bar') == 'bar'102- # __contains__103- assert 'foo' not in flask.g104- flask.g.foo = 'bar'105- assert 'foo' in flask.g106- # setdefault107- flask.g.setdefault('bar', 'the cake is a lie')108- flask.g.setdefault('bar', 'hello world')109- assert flask.g.bar == 'the cake is a lie'110- # pop111- assert flask.g.pop('bar') == 'the cake is a lie'112- with pytest.raises(KeyError):113- flask.g.pop('bar')114- assert flask.g.pop('bar', 'more cake') == 'more cake'115- # __iter__116- assert list(flask.g) == ['foo']99 100+def test_app_ctx_globals_methods(app, app_ctx):101+ # get102+ assert flask.g.get('foo') is None103+ assert flask.g.get('foo', 'bar') == 'bar'104+ # __contains__105+ assert 'foo' not in flask.g106+ flask.g.foo = 'bar'107+ assert 'foo' in flask.g108+ # setdefault109+ flask.g.setdefault('bar', 'the cake is a lie')110+ flask.g.setdefault('bar', 'hello world')111+ assert flask.g.bar == 'the cake is a lie'112+ # pop113+ assert flask.g.pop('bar') == 'the cake is a lie'114+ with pytest.raises(KeyError):115+ flask.g.pop('bar')116+ assert flask.g.pop('bar', 'more cake') == 'more cake'117+ # __iter__118+ assert list(flask.g) == ['foo']119+120+118-def test_custom_app_ctx_globals_class():121+def test_custom_app_ctx_globals_class(app):122 class CustomRequestGlobals(object):123 def __init__(self):124 self.spam = 'eggs'122- app = flask.Flask(__name__)125+126 app.app_ctx_globals_class = CustomRequestGlobals127 with app.app_context():128 assert flask.render_template_string('{{ g.spam }}') == 'eggs'129 130+127-def test_context_refcounts():131+def test_context_refcounts(app, client):132 called = []129- app = flask.Flask(__name__)133+134 @app.teardown_request135 def teardown_req(error=None):136 called.append('request')137+138 @app.teardown_appcontext139 def teardown_app(error=None):140 called.append('app')141+142 @app.route('/')143 def index():144 with flask._app_ctx_stack.top:145 with flask._request_ctx_stack.top:146 pass147 env = flask._request_ctx_stack.top.request.environ148 assert env['werkzeug.request'] is not None149 return u''144- c = app.test_client()145- res = c.get('/')150+151+ res = client.get('/')152 assert res.status_code == 200153 assert res.data == b''154 assert called == ['request', 'app']155 156 151-def test_clean_pop():157+def test_clean_pop(app):158+ app.testing = False159 called = []153- app = flask.Flask(__name__)160 161 @app.teardown_request162 def teardown_req(error=None):163 1 / 07 unmodified lines171 called.append(flask.current_app.name)172 except ZeroDivisionError:173 pass174 169- assert called == ['test_appctx', 'TEARDOWN']175+ assert called == ['conftest', 'TEARDOWN']176 assert not flask.current_appmodified:tests/test_basic.py+666 added-463 removed
7 unmodified lines8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12-import pytest13-12+import pickle13 import re15-import uuid14 import time17-import flask18-import pickle15+import uuid16 from datetime import datetime17 from threading import Thread21-from flask._compat import text_type22-from werkzeug.exceptions import BadRequest, NotFound, Forbidden18+19+import pytest20+import werkzeug.serving21+from werkzeug.exceptions import BadRequest, Forbidden, NotFound22 from werkzeug.http import parse_date23 from werkzeug.routing import BuildError25-import werkzeug.serving24 25+import flask26+from flask._compat import text_type27 28-def test_options_work():29- app = flask.Flask(__name__)28 29+def test_options_work(app, client):30 @app.route('/', methods=['GET', 'POST'])31 def index():32 return 'Hello World'33+34- rv = app.test_client().open('/', method='OPTIONS')34+ rv = client.open('/', method='OPTIONS')35 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']36 assert rv.data == b''37 38 39-def test_options_on_multiple_rules():40- app = flask.Flask(__name__)41-39+def test_options_on_multiple_rules(app, client):40 @app.route('/', methods=['GET', 'POST'])41 def index():42 return 'Hello World'43 44 @app.route('/', methods=['PUT'])45 def index_put():46 return 'Aha!'47+49- rv = app.test_client().open('/', method='OPTIONS')48+ rv = client.open('/', method='OPTIONS')49 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']50 51 53-def test_options_handling_disabled():52+def test_provide_automatic_options_attr():53 app = flask.Flask(__name__)54 55 def index():56 return 'Hello World!'57+58 index.provide_automatic_options = False59 app.route('/')(index)60 rv = app.test_client().open('/', method='OPTIONS')61 assert rv.status_code == 4051 unmodified line63 app = flask.Flask(__name__)64 65 def index2():66 return 'Hello World!'67+68 index2.provide_automatic_options = True69 app.route('/', methods=['OPTIONS'])(index2)70 rv = app.test_client().open('/', method='OPTIONS')71 assert sorted(rv.allow) == ['OPTIONS']72 73 73-def test_request_dispatching():74- app = flask.Flask(__name__)74+def test_provide_automatic_options_kwarg(app, client):75+ def index():76+ return flask.request.method77 78+ def more():79+ return flask.request.method80+81+ app.add_url_rule('/', view_func=index, provide_automatic_options=False)82+ app.add_url_rule(83+ '/more', view_func=more, methods=['GET', 'POST'],84+ provide_automatic_options=False85+ )86+ assert client.get('/').data == b'GET'87+88+ rv = client.post('/')89+ assert rv.status_code == 40590+ assert sorted(rv.allow) == ['GET', 'HEAD']91+92+ # Older versions of Werkzeug.test.Client don't have an options method93+ if hasattr(client, 'options'):94+ rv = client.options('/')95+ else:96+ rv = client.open('/', method='OPTIONS')97+98+ assert rv.status_code == 40599+100+ rv = client.head('/')101+ assert rv.status_code == 200102+ assert not rv.data # head truncates103+ assert client.post('/more').data == b'POST'104+ assert client.get('/more').data == b'GET'105+106+ rv = client.delete('/more')107+ assert rv.status_code == 405108+ assert sorted(rv.allow) == ['GET', 'HEAD', 'POST']109+110+ if hasattr(client, 'options'):111+ rv = client.options('/more')112+ else:113+ rv = client.open('/more', method='OPTIONS')114+115+ assert rv.status_code == 405116+117+118+def test_request_dispatching(app, client):119 @app.route('/')120 def index():121 return flask.request.method122 123 @app.route('/more', methods=['GET', 'POST'])124 def more():125 return flask.request.method126 84- c = app.test_client()85- assert c.get('/').data == b'GET'86- rv = c.post('/')127+ assert client.get('/').data == b'GET'128+ rv = client.post('/')129 assert rv.status_code == 405130 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']89- rv = c.head('/')131+ rv = client.head('/')132 assert rv.status_code == 200133 assert not rv.data # head truncates92- assert c.post('/more').data == b'POST'93- assert c.get('/more').data == b'GET'94- rv = c.delete('/more')134+ assert client.post('/more').data == b'POST'135+ assert client.get('/more').data == b'GET'136+ rv = client.delete('/more')137 assert rv.status_code == 405138 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']139 140 99-def test_disallow_string_for_allowed_methods():100- app = flask.Flask(__name__)141+def test_disallow_string_for_allowed_methods(app):142 with pytest.raises(TypeError):143 @app.route('/', methods='GET POST')144 def index():145 return "Hey"146 147 107-def test_url_mapping():108- app = flask.Flask(__name__)109-148+def test_url_mapping(app, client):149 random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"150 151 def index():152 return flask.request.method3 unmodified lines156 157 def options():158 return random_uuid4159 121-160 app.add_url_rule('/', 'index', index)161 app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])162 163 # Issue 1288: Test that automatic options are not added when non-uppercase 'options' in methods164 app.add_url_rule('/options', 'options', options, methods=['options'])165 128- c = app.test_client()129- assert c.get('/').data == b'GET'130- rv = c.post('/')166+ assert client.get('/').data == b'GET'167+ rv = client.post('/')168 assert rv.status_code == 405169 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']133- rv = c.head('/')170+ rv = client.head('/')171 assert rv.status_code == 200172 assert not rv.data # head truncates136- assert c.post('/more').data == b'POST'137- assert c.get('/more').data == b'GET'138- rv = c.delete('/more')173+ assert client.post('/more').data == b'POST'174+ assert client.get('/more').data == b'GET'175+ rv = client.delete('/more')176 assert rv.status_code == 405177 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']141- rv = c.open('/options', method='OPTIONS')178+ rv = client.open('/options', method='OPTIONS')179 assert rv.status_code == 200180 assert random_uuid4 in rv.data.decode("utf-8")181 182 146-def test_werkzeug_routing():183+def test_werkzeug_routing(app, client):184 from werkzeug.routing import Submount, Rule148- app = flask.Flask(__name__)185 app.url_map.add(Submount('/foo', [186 Rule('/bar', endpoint='bar'),187 Rule('/', endpoint='index')188 ]))2 unmodified lines191 return 'bar'192 193 def index():194 return 'index'195+196 app.view_functions['bar'] = bar197 app.view_functions['index'] = index198 162- c = app.test_client()163- assert c.get('/foo/').data == b'index'164- assert c.get('/foo/bar').data == b'bar'199+ assert client.get('/foo/').data == b'index'200+ assert client.get('/foo/bar').data == b'bar'201 202 167-def test_endpoint_decorator():203+def test_endpoint_decorator(app, client):204 from werkzeug.routing import Submount, Rule169- app = flask.Flask(__name__)205 app.url_map.add(Submount('/foo', [206 Rule('/bar', endpoint='bar'),207 Rule('/', endpoint='index')208 ]))5 unmodified lines214 @app.endpoint('index')215 def index():216 return 'index'217 183- c = app.test_client()184- assert c.get('/foo/').data == b'index'185- assert c.get('/foo/bar').data == b'bar'218+ assert client.get('/foo/').data == b'index'219+ assert client.get('/foo/bar').data == b'bar'220 221 188-def test_session():189- app = flask.Flask(__name__)222+def test_session(app, client):223 app.secret_key = 'testkey'224 225 @app.route('/set', methods=['POST'])226 def set():3 unmodified lines230 @app.route('/get')231 def get():232 return flask.session['value']233 201- c = app.test_client()202- assert c.post('/set', data={'value': '42'}).data == b'value set'203- assert c.get('/get').data == b'42'234+ assert client.post('/set', data={'value': '42'}).data == b'value set'235+ assert client.get('/get').data == b'42'236 237 206-def test_session_using_server_name():207- app = flask.Flask(__name__)238+def test_session_using_server_name(app, client):239 app.config.update(240 SECRET_KEY='foo',241 SERVER_NAME='example.com'242 )1 unmodified line244 @app.route('/')245 def index():246 flask.session['testing'] = 42247 return 'Hello World'248+217- rv = app.test_client().get('/', 'http://example.com/')249+ rv = client.get('/', 'http://example.com/')250 assert 'domain=.example.com' in rv.headers['set-cookie'].lower()251 assert 'httponly' in rv.headers['set-cookie'].lower()252 253 222-def test_session_using_server_name_and_port():223- app = flask.Flask(__name__)254+def test_session_using_server_name_and_port(app, client):255 app.config.update(256 SECRET_KEY='foo',257 SERVER_NAME='example.com:8080'258 )1 unmodified line260 @app.route('/')261 def index():262 flask.session['testing'] = 42263 return 'Hello World'264+233- rv = app.test_client().get('/', 'http://example.com:8080/')265+ rv = client.get('/', 'http://example.com:8080/')266 assert 'domain=.example.com' in rv.headers['set-cookie'].lower()267 assert 'httponly' in rv.headers['set-cookie'].lower()268 269 238-def test_session_using_server_name_port_and_path():239- app = flask.Flask(__name__)270+def test_session_using_server_name_port_and_path(app, client):271 app.config.update(272 SECRET_KEY='foo',273 SERVER_NAME='example.com:8080',274 APPLICATION_ROOT='/foo'2 unmodified lines277 @app.route('/')278 def index():279 flask.session['testing'] = 42280 return 'Hello World'281+250- rv = app.test_client().get('/', 'http://example.com:8080/foo')282+ rv = client.get('/', 'http://example.com:8080/foo')283 assert 'domain=example.com' in rv.headers['set-cookie'].lower()284 assert 'path=/foo' in rv.headers['set-cookie'].lower()285 assert 'httponly' in rv.headers['set-cookie'].lower()286 287 256-def test_session_using_application_root():288+def test_session_using_application_root(app, client):289 class PrefixPathMiddleware(object):258-290 def __init__(self, app, prefix):291 self.app = app292 self.prefix = prefix293 294 def __call__(self, environ, start_response):295 environ['SCRIPT_NAME'] = self.prefix296 return self.app(environ, start_response)297 267- app = flask.Flask(__name__)298 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar')299 app.config.update(300 SECRET_KEY='foo',301 APPLICATION_ROOT='/bar'2 unmodified lines304 @app.route('/')305 def index():306 flask.session['testing'] = 42307 return 'Hello World'308+278- rv = app.test_client().get('/', 'http://example.com:8080/')309+ rv = client.get('/', 'http://example.com:8080/')310 assert 'path=/bar' in rv.headers['set-cookie'].lower()311 312 282-def test_session_using_session_settings():283- app = flask.Flask(__name__)313+def test_session_using_session_settings(app, client):314 app.config.update(315 SECRET_KEY='foo',316 SERVER_NAME='www.example.com:8080',317 APPLICATION_ROOT='/test',6 unmodified lines324 @app.route('/')325 def index():326 flask.session['testing'] = 42327 return 'Hello World'328+298- rv = app.test_client().get('/', 'http://www.example.com:8080/test/')329+ rv = client.get('/', 'http://www.example.com:8080/test/')330 cookie = rv.headers['set-cookie'].lower()331 assert 'domain=.example.com' in cookie332 assert 'path=/' in cookie333 assert 'secure' in cookie334 assert 'httponly' not in cookie335 336 337+def test_session_localhost_warning(recwarn, app, client):338+ app.config.update(339+ SECRET_KEY='testing',340+ SERVER_NAME='localhost:5000',341+ )342+343+ @app.route('/')344+ def index():345+ flask.session['testing'] = 42346+ return 'testing'347+348+ rv = client.get('/', 'http://localhost:5000/')349+ assert 'domain' not in rv.headers['set-cookie'].lower()350+ w = recwarn.pop(UserWarning)351+ assert '"localhost" is not a valid cookie domain' in str(w.message)352+353+354+def test_session_ip_warning(recwarn, app, client):355+ app.config.update(356+ SECRET_KEY='testing',357+ SERVER_NAME='127.0.0.1:5000',358+ )359+360+ @app.route('/')361+ def index():362+ flask.session['testing'] = 42363+ return 'testing'364+365+ rv = client.get('/', 'http://127.0.0.1:5000/')366+ assert 'domain=127.0.0.1' in rv.headers['set-cookie'].lower()367+ w = recwarn.pop(UserWarning)368+ assert 'cookie domain is an IP' in str(w.message)369+370+371 def test_missing_session():372 app = flask.Flask(__name__)373 374 def expect_exception(f, *args, **kwargs):375 e = pytest.raises(RuntimeError, f, *args, **kwargs)376 assert e.value.args and 'session is unavailable' in e.value.args[0]377+378 with app.test_request_context():379 assert flask.session.get('missing_key') is None380 expect_exception(flask.session.__setitem__, 'foo', 42)381 expect_exception(flask.session.pop, 'foo')382 383 318-def test_session_expiration():384+def test_session_expiration(app, client):385 permanent = True320- app = flask.Flask(__name__)386 app.secret_key = 'testkey'387 388 @app.route('/')389 def index():4 unmodified lines394 @app.route('/test')395 def test():396 return text_type(flask.session.permanent)397 333- client = app.test_client()398 rv = client.get('/')399 assert 'set-cookie' in rv.headers336- match = re.search(r'\bexpires=([^;]+)(?i)', rv.headers['set-cookie'])400+ match = re.search(r'(?i)\bexpires=([^;]+)', rv.headers['set-cookie'])401 expires = parse_date(match.group())402 expected = datetime.utcnow() + app.permanent_session_lifetime403 assert expires.year == expected.year404 assert expires.month == expected.month2 unmodified lines407 rv = client.get('/test')408 assert rv.data == b'True'409 410 permanent = False347- rv = app.test_client().get('/')411+ rv = client.get('/')412 assert 'set-cookie' in rv.headers413 match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])414 assert match is None415 416 353-def test_session_stored_last():354- app = flask.Flask(__name__)417+def test_session_stored_last(app, client):418 app.secret_key = 'development-key'356- app.testing = True419 420 @app.after_request421 def modify_session(response):422 flask.session['foo'] = 422 unmodified lines425 @app.route('/')426 def dump_session_contents():427 return repr(flask.session.get('foo'))428 367- c = app.test_client()368- assert c.get('/').data == b'None'369- assert c.get('/').data == b'42'429+ assert client.get('/').data == b'None'430+ assert client.get('/').data == b'42'431 432 372-def test_session_special_types():373- app = flask.Flask(__name__)433+def test_session_special_types(app, client):434 app.secret_key = 'development-key'375- app.testing = True435 now = datetime.utcnow().replace(microsecond=0)436 the_uuid = uuid.uuid4()437 379- @app.after_request380- def modify_session(response):381- flask.session['m'] = flask.Markup('Hello!')382- flask.session['u'] = the_uuid383- flask.session['dt'] = now384- flask.session['b'] = b'\xff'385- flask.session['t'] = (1, 2, 3)386- return response387-438 @app.route('/')439 def dump_session_contents():390- return pickle.dumps(dict(flask.session))440+ flask.session['t'] = (1, 2, 3)441+ flask.session['b'] = b'\xff'442+ flask.session['m'] = flask.Markup('<html>')443+ flask.session['u'] = the_uuid444+ flask.session['d'] = now445+ flask.session['t_tag'] = {' t': 'not-a-tuple'}446+ flask.session['di_t_tag'] = {' t__': 'not-a-tuple'}447+ flask.session['di_tag'] = {' di': 'not-a-dict'}448+ return '', 204449 392- c = app.test_client()393- c.get('/')394- rv = pickle.loads(c.get('/').data)395- assert rv['m'] == flask.Markup('Hello!')396- assert type(rv['m']) == flask.Markup397- assert rv['dt'] == now398- assert rv['u'] == the_uuid399- assert rv['b'] == b'\xff'400- assert type(rv['b']) == bytes401- assert rv['t'] == (1, 2, 3)450+ with client:451+ client.get('/')452+ s = flask.session453+ assert s['t'] == (1, 2, 3)454+ assert type(s['b']) == bytes455+ assert s['b'] == b'\xff'456+ assert type(s['m']) == flask.Markup457+ assert s['m'] == flask.Markup('<html>')458+ assert s['u'] == the_uuid459+ assert s['d'] == now460+ assert s['t_tag'] == {' t': 'not-a-tuple'}461+ assert s['di_t_tag'] == {' t__': 'not-a-tuple'}462+ assert s['di_tag'] == {' di': 'not-a-dict'}463 464 404-def test_session_cookie_setting():405- app = flask.Flask(__name__)406- app.testing = True465+def test_session_cookie_setting(app):466 app.secret_key = 'dev key'467 is_permanent = True468 469 @app.route('/bump')33 unmodified lines503 app.config['SESSION_REFRESH_EACH_REQUEST'] = False504 run_test(expect_header=False)505 506 448-def test_flashes():449- app = flask.Flask(__name__)507+def test_session_vary_cookie(app, client):508 app.secret_key = 'testkey'509 452- with app.test_request_context():453- assert not flask.session.modified454- flask.flash('Zap')455- flask.session.modified = False456- flask.flash('Zip')457- assert flask.session.modified458- assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']510+ @app.route('/set')511+ def set_session():512+ flask.session['test'] = 'test'513+ return ''514 515+ @app.route('/get')516+ def get():517+ return flask.session.get('test')518 519+ @app.route('/getitem')520+ def getitem():521+ return flask.session['test']522+523+ @app.route('/setdefault')524+ def setdefault():525+ return flask.session.setdefault('test', 'default')526+527+ @app.route('/vary-cookie-header-set')528+ def vary_cookie_header_set():529+ response = flask.Response()530+ response.vary.add('Cookie')531+ flask.session['test'] = 'test'532+ return response533+534+ @app.route('/vary-header-set')535+ def vary_header_set():536+ response = flask.Response()537+ response.vary.update(('Accept-Encoding', 'Accept-Language'))538+ flask.session['test'] = 'test'539+ return response540+541+ @app.route('/no-vary-header')542+ def no_vary_header():543+ return ''544+545+ def expect(path, header_value='Cookie'):546+ rv = client.get(path)547+548+ if header_value:549+ # The 'Vary' key should exist in the headers only once.550+ assert len(rv.headers.get_all('Vary')) == 1551+ assert rv.headers['Vary'] == header_value552+ else:553+ assert 'Vary' not in rv.headers554+555+ expect('/set')556+ expect('/get')557+ expect('/getitem')558+ expect('/setdefault')559+ expect('/vary-cookie-header-set')560+ expect('/vary-header-set', 'Accept-Encoding, Accept-Language, Cookie')561+ expect('/no-vary-header', None)562+563+564+def test_flashes(app, req_ctx):565+ app.secret_key = 'testkey'566+567+ assert not flask.session.modified568+ flask.flash('Zap')569+ flask.session.modified = False570+ flask.flash('Zip')571+ assert flask.session.modified572+ assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']573+574+461-def test_extended_flashing():575+def test_extended_flashing(app):576 # Be sure app.testing=True below, else tests can fail silently.577 #578 # Specifically, if app.testing is not set to True, the AssertionErrors579 # in the view functions will cause a 500 response to the test client580 # instead of propagating exceptions.581 468- app = flask.Flask(__name__)582 app.secret_key = 'testkey'470- app.testing = True583 584 @app.route('/')585 def index():586 flask.flash(u'Hello World')49 unmodified lines636 return ''637 638 # Create new test client on each test to clean flashed messages.639 528- c = app.test_client()529- c.get('/')530- c.get('/test/')640+ client = app.test_client()641+ client.get('/')642+ client.get('/test_with_categories/')643 532- c = app.test_client()533- c.get('/')534- c.get('/test_with_categories/')644+ client = app.test_client()645+ client.get('/')646+ client.get('/test_filter/')647 536- c = app.test_client()537- c.get('/')538- c.get('/test_filter/')648+ client = app.test_client()649+ client.get('/')650+ client.get('/test_filters/')651 540- c = app.test_client()541- c.get('/')542- c.get('/test_filters/')652+ client = app.test_client()653+ client.get('/')654+ client.get('/test_filters_without_returning_categories/')655 544- c = app.test_client()545- c.get('/')546- c.get('/test_filters_without_returning_categories/')656 548-549-def test_request_processing():657+def test_request_processing(app, client):550- app = flask.Flask(__name__)658 evts = []659 660 @app.before_request661 def before_request():9 unmodified lines671 def index():672 assert 'before' in evts673 assert 'after' not in evts674 return 'request'675+676 assert 'after' not in evts569- rv = app.test_client().get('/').data677+ rv = client.get('/').data678 assert 'after' in evts679 assert rv == b'request|after'680 681 574-def test_request_preprocessing_early_return():575- app = flask.Flask(__name__)682+def test_request_preprocessing_early_return(app, client):683 evts = []684 685 @app.before_request686 def before_request1():13 unmodified lines700 def index():701 evts.append('index')702 return "damnit"703 597- rv = app.test_client().get('/').data.strip()704+ rv = client.get('/').data.strip()705 assert rv == b'hello'706 assert evts == [1, 2]707 708 602-def test_after_request_processing():603- app = flask.Flask(__name__)604- app.testing = True605-709+def test_after_request_processing(app, client):710 @app.route('/')711 def index():712 @flask.after_this_request713 def foo(response):714 response.headers['X-Foo'] = 'a header'715 return response716+717 return 'Test'613- c = app.test_client()614- resp = c.get('/')718+719+ resp = client.get('/')720 assert resp.status_code == 200721 assert resp.headers['X-Foo'] == 'a header'722 723 619-def test_teardown_request_handler():724+def test_teardown_request_handler(app, client):725 called = []621- app = flask.Flask(__name__)726 727 @app.teardown_request728 def teardown_request(exc):729 called.append(True)1 unmodified line731 732 @app.route('/')733 def root():734 return "Response"631- rv = app.test_client().get('/')735+736+ rv = client.get('/')737 assert rv.status_code == 200738 assert b'Response' in rv.data739 assert len(called) == 1740 741 637-def test_teardown_request_handler_debug_mode():742+def test_teardown_request_handler_debug_mode(app, client):743 called = []639- app = flask.Flask(__name__)640- app.testing = True744 745 @app.teardown_request746 def teardown_request(exc):747 called.append(True)1 unmodified line749 750 @app.route('/')751 def root():752 return "Response"650- rv = app.test_client().get('/')753+754+ rv = client.get('/')755 assert rv.status_code == 200756 assert b'Response' in rv.data757 assert len(called) == 1758 759 656-def test_teardown_request_handler_error():760+def test_teardown_request_handler_error(app, client):761 called = []658- app = flask.Flask(__name__)762 app.config['LOGGER_HANDLER_POLICY'] = 'never'763+ app.testing = False764 765 @app.teardown_request766 def teardown_request1(exc):767 assert type(exc) == ZeroDivisionError20 unmodified lines788 789 @app.route('/')790 def fails():791 1 // 0688- rv = app.test_client().get('/')792+793+ rv = client.get('/')794 assert rv.status_code == 500795 assert b'Internal Server Error' in rv.data796 assert len(called) == 2797 798 694-def test_before_after_request_order():799+def test_before_after_request_order(app, client):800 called = []696- app = flask.Flask(__name__)801 802 @app.before_request803 def before1():804 called.append(1)22 unmodified lines827 828 @app.route('/')829 def index():830 return '42'727- rv = app.test_client().get('/')831+832+ rv = client.get('/')833 assert rv.data == b'42'834 assert called == [1, 2, 3, 4, 5, 6]835 836 732-def test_error_handling():733- app = flask.Flask(__name__)837+def test_error_handling(app, client):838 app.config['LOGGER_HANDLER_POLICY'] = 'never'839+ app.testing = False840 841 @app.errorhandler(404)842 def not_found(e):843 return 'not found', 40416 unmodified lines860 861 @app.route('/forbidden')862 def error2():863 flask.abort(403)759- c = app.test_client()760- rv = c.get('/')864+865+ rv = client.get('/')866 assert rv.status_code == 404867 assert rv.data == b'not found'763- rv = c.get('/error')868+ rv = client.get('/error')869 assert rv.status_code == 500870 assert b'internal server error' == rv.data766- rv = c.get('/forbidden')871+ rv = client.get('/forbidden')872 assert rv.status_code == 403873 assert b'forbidden' == rv.data874 875 771-def test_before_request_and_routing_errors():772- app = flask.Flask(__name__)876+def test_error_handler_unknown_code(app):877+ with pytest.raises(KeyError) as exc_info:878+ app.register_error_handler(999, lambda e: ('999', 999))879 880+ assert 'Use a subclass' in exc_info.value.args[0]881+882+883+def test_error_handling_processing(app, client):884+ app.config['LOGGER_HANDLER_POLICY'] = 'never'885+ app.testing = False886+887+ @app.errorhandler(500)888+ def internal_server_error(e):889+ return 'internal server error', 500890+891+ @app.route('/')892+ def broken_func():893+ 1 // 0894+895+ @app.after_request896+ def after_request(resp):897+ resp.mimetype = 'text/x-special'898+ return resp899+900+ resp = client.get('/')901+ assert resp.mimetype == 'text/x-special'902+ assert resp.data == b'internal server error'903+904+905+def test_baseexception_error_handling(app, client):906+ app.config['LOGGER_HANDLER_POLICY'] = 'never'907+ app.testing = False908+909+ @app.route('/')910+ def broken_func():911+ raise KeyboardInterrupt()912+913+ with pytest.raises(KeyboardInterrupt):914+ client.get('/')915+916+ ctx = flask._request_ctx_stack.top917+ assert ctx.preserved918+ assert type(ctx._preserved_exc) is KeyboardInterrupt919+920+921+def test_before_request_and_routing_errors(app, client):922 @app.before_request923 def attach_something():924 flask.g.something = 'value'925 926 @app.errorhandler(404)927 def return_something(error):928 return flask.g.something, 404781- rv = app.test_client().get('/')929+930+ rv = client.get('/')931 assert rv.status_code == 404932 assert rv.data == b'value'933 934 786-def test_user_error_handling():935+def test_user_error_handling(app, client):936 class MyException(Exception):937 pass938 790- app = flask.Flask(__name__)791-939 @app.errorhandler(MyException)940 def handle_my_exception(e):941 assert isinstance(e, MyException)942 return '42'1 unmodified line944 @app.route('/')945 def index():946 raise MyException()947 801- c = app.test_client()802- assert c.get('/').data == b'42'948+ assert client.get('/').data == b'42'949 950 805-def test_http_error_subclass_handling():951+def test_http_error_subclass_handling(app, client):952 class ForbiddenSubclass(Forbidden):953 pass954 809- app = flask.Flask(__name__)810-955 @app.errorhandler(ForbiddenSubclass)956 def handle_forbidden_subclass(e):957 assert isinstance(e, ForbiddenSubclass)958 return 'banana'15 unmodified lines974 @app.route('/3')975 def index3():976 raise Forbidden()977 834- c = app.test_client()835- assert c.get('/1').data == b'banana'836- assert c.get('/2').data == b'apple'837- assert c.get('/3').data == b'apple'978+ assert client.get('/1').data == b'banana'979+ assert client.get('/2').data == b'apple'980+ assert client.get('/3').data == b'apple'981 982 840-def test_trapping_of_bad_request_key_errors():841- app = flask.Flask(__name__)842- app.testing = True983+def test_errorhandler_precedence(app, client):984+ class E1(Exception):985+ pass986 987+ class E2(Exception):988+ pass989+990+ class E3(E1, E2):991+ pass992+993+ @app.errorhandler(E2)994+ def handle_e2(e):995+ return 'E2'996+997+ @app.errorhandler(Exception)998+ def handle_exception(e):999+ return 'Exception'1000+1001+ @app.route('/E1')1002+ def raise_e1():1003+ raise E11004+1005+ @app.route('/E3')1006+ def raise_e3():1007+ raise E31008+1009+ rv = client.get('/E1')1010+ assert rv.data == b'Exception'1011+1012+ rv = client.get('/E3')1013+ assert rv.data == b'E2'1014+1015+1016+def test_trapping_of_bad_request_key_errors(app, client):1017 @app.route('/fail')1018 def fail():1019 flask.request.form['missing_key']847- c = app.test_client()848- assert c.get('/fail').status_code == 4001020 1021+ rv = client.get('/fail')1022+ assert rv.status_code == 4001023+ assert b'missing_key' not in rv.data1024+1025 app.config['TRAP_BAD_REQUEST_ERRORS'] = True851- c = app.test_client()1026+1027 with pytest.raises(KeyError) as e:853- c.get("/fail")1028+ client.get("/fail")1029+1030 assert e.errisinstance(BadRequest)1031+ assert 'missing_key' in e.value.description1032 1033 857-def test_trapping_of_all_http_exceptions():858- app = flask.Flask(__name__)859- app.testing = True1034+def test_trapping_of_all_http_exceptions(app, client):1035 app.config['TRAP_HTTP_EXCEPTIONS'] = True1036 1037 @app.route('/fail')1038 def fail():1039 flask.abort(404)1040 866- c = app.test_client()1041 with pytest.raises(NotFound):868- c.get('/fail')1042+ client.get('/fail')1043 1044 871-def test_enctype_debug_helper():1045+def test_enctype_debug_helper(app, client):1046 from flask.debughelpers import DebugFilesKeyError873- app = flask.Flask(__name__)1047 app.debug = True1048 1049 @app.route('/fail', methods=['POST'])1050 def index():1 unmodified line1052 1053 # with statement is important because we leave an exception on the1054 # stack otherwise and we want to ensure that this is not the case1055 # to not negatively affect other tests.883- with app.test_client() as c:1056+ with client:1057 with pytest.raises(DebugFilesKeyError) as e:885- c.post('/fail', data={'foo': 'index.txt'})1058+ client.post('/fail', data={'foo': 'index.txt'})1059 assert 'no file contents were transmitted' in str(e.value)1060 assert 'This was submitted: "index.txt"' in str(e.value)1061 1062 890-def test_response_creation():891- app = flask.Flask(__name__)892-893- @app.route('/unicode')894- def from_unicode():1063+def test_response_types(app, client):1064+ @app.route('/text')1065+ def from_text():1066 return u'Hällo Wörld'1067 897- @app.route('/string')898- def from_string():1068+ @app.route('/bytes')1069+ def from_bytes():1070 return u'Hällo Wörld'.encode('utf-8')1071 901- @app.route('/args')902- def from_tuple():1072+ @app.route('/full_tuple')1073+ def from_full_tuple():1074 return 'Meh', 400, {1075 'X-Foo': 'Testing',1076 'Content-Type': 'text/plain; charset=utf-8'1077 }1078 908- @app.route('/two_args')909- def from_two_args_tuple():1079+ @app.route('/text_headers')1080+ def from_text_headers():1081 return 'Hello', {1082 'X-Foo': 'Test',1083 'Content-Type': 'text/plain; charset=utf-8'1084 }1085 915- @app.route('/args_status')916- def from_status_tuple():1086+ @app.route('/text_status')1087+ def from_text_status():1088 return 'Hi, status!', 4001089 919- @app.route('/args_header')920- def from_response_instance_status_tuple():921- return flask.Response('Hello world', 404), {1090+ @app.route('/response_headers')1091+ def from_response_headers():1092+ return flask.Response('Hello world', 404, {'X-Foo': 'Baz'}), {1093 "X-Foo": "Bar",1094 "X-Bar": "Foo"1095 }1096 926- c = app.test_client()927- assert c.get('/unicode').data == u'Hällo Wörld'.encode('utf-8')928- assert c.get('/string').data == u'Hällo Wörld'.encode('utf-8')929- rv = c.get('/args')1097+ @app.route('/response_status')1098+ def from_response_status():1099+ return app.response_class('Hello world', 400), 5001100+1101+ @app.route('/wsgi')1102+ def from_wsgi():1103+ return NotFound()1104+1105+ assert client.get('/text').data == u'Hällo Wörld'.encode('utf-8')1106+ assert client.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')1107+1108+ rv = client.get('/full_tuple')1109 assert rv.data == b'Meh'1110 assert rv.headers['X-Foo'] == 'Testing'1111 assert rv.status_code == 4001112 assert rv.mimetype == 'text/plain'934- rv2 = c.get('/two_args')935- assert rv2.data == b'Hello'936- assert rv2.headers['X-Foo'] == 'Test'937- assert rv2.status_code == 200938- assert rv2.mimetype == 'text/plain'939- rv3 = c.get('/args_status')940- assert rv3.data == b'Hi, status!'941- assert rv3.status_code == 400942- assert rv3.mimetype == 'text/html'943- rv4 = c.get('/args_header')944- assert rv4.data == b'Hello world'945- assert rv4.headers['X-Foo'] == 'Bar'946- assert rv4.headers['X-Bar'] == 'Foo'947- assert rv4.status_code == 4041113 1114+ rv = client.get('/text_headers')1115+ assert rv.data == b'Hello'1116+ assert rv.headers['X-Foo'] == 'Test'1117+ assert rv.status_code == 2001118+ assert rv.mimetype == 'text/plain'1119 950-def test_make_response():951- app = flask.Flask(__name__)952- with app.test_request_context():953- rv = flask.make_response()954- assert rv.status_code == 200955- assert rv.data == b''956- assert rv.mimetype == 'text/html'1120+ rv = client.get('/text_status')1121+ assert rv.data == b'Hi, status!'1122+ assert rv.status_code == 4001123+ assert rv.mimetype == 'text/html'1124 958- rv = flask.make_response('Awesome')959- assert rv.status_code == 200960- assert rv.data == b'Awesome'961- assert rv.mimetype == 'text/html'1125+ rv = client.get('/response_headers')1126+ assert rv.data == b'Hello world'1127+ assert rv.headers.getlist('X-Foo') == ['Baz', 'Bar']1128+ assert rv.headers['X-Bar'] == 'Foo'1129+ assert rv.status_code == 4041130 963- rv = flask.make_response('W00t', 404)964- assert rv.status_code == 404965- assert rv.data == b'W00t'966- assert rv.mimetype == 'text/html'1131+ rv = client.get('/response_status')1132+ assert rv.data == b'Hello world'1133+ assert rv.status_code == 5001134 1135+ rv = client.get('/wsgi')1136+ assert b'Not Found' in rv.data1137+ assert rv.status_code == 4041138 969-def test_make_response_with_response_instance():1139+1140+def test_response_type_errors():1141 app = flask.Flask(__name__)971- with app.test_request_context():972- rv = flask.make_response(973- flask.jsonify({'msg': 'W00t'}), 400)974- assert rv.status_code == 400975- assert rv.data == b'{\n "msg": "W00t"\n}\n'976- assert rv.mimetype == 'application/json'1142+ app.testing = True1143 978- rv = flask.make_response(979- flask.Response(''), 400)980- assert rv.status_code == 400981- assert rv.data == b''982- assert rv.mimetype == 'text/html'1144+ @app.route('/none')1145+ def from_none():1146+ pass1147 984- rv = flask.make_response(985- flask.Response('', headers={'Content-Type': 'text/html'}),986- 400, [('X-Foo', 'bar')])987- assert rv.status_code == 400988- assert rv.headers['Content-Type'] == 'text/html'989- assert rv.headers['X-Foo'] == 'bar'1148+ @app.route('/small_tuple')1149+ def from_small_tuple():1150+ return 'Hello',1151 1152+ @app.route('/large_tuple')1153+ def from_large_tuple():1154+ return 'Hello', 234, {'X-Foo': 'Bar'}, '???'1155 992-def test_jsonify_no_prettyprint():993- app = flask.Flask(__name__)1156+ @app.route('/bad_type')1157+ def from_bad_type():1158+ return True1159+1160+ @app.route('/bad_wsgi')1161+ def from_bad_wsgi():1162+ return lambda: None1163+1164+ c = app.test_client()1165+1166+ with pytest.raises(TypeError) as e:1167+ c.get('/none')1168+ assert 'returned None' in str(e)1169+1170+ with pytest.raises(TypeError) as e:1171+ c.get('/small_tuple')1172+ assert 'tuple must have the form' in str(e)1173+1174+ pytest.raises(TypeError, c.get, '/large_tuple')1175+1176+ with pytest.raises(TypeError) as e:1177+ c.get('/bad_type')1178+ assert 'it was a bool' in str(e)1179+1180+ pytest.raises(TypeError, c.get, '/bad_wsgi')1181+1182+1183+def test_make_response(app, req_ctx):1184+ rv = flask.make_response()1185+ assert rv.status_code == 2001186+ assert rv.data == b''1187+ assert rv.mimetype == 'text/html'1188+1189+ rv = flask.make_response('Awesome')1190+ assert rv.status_code == 2001191+ assert rv.data == b'Awesome'1192+ assert rv.mimetype == 'text/html'1193+1194+ rv = flask.make_response('W00t', 404)1195+ assert rv.status_code == 4041196+ assert rv.data == b'W00t'1197+ assert rv.mimetype == 'text/html'1198+1199+1200+def test_make_response_with_response_instance(app, req_ctx):1201+ rv = flask.make_response(1202+ flask.jsonify({'msg': 'W00t'}), 400)1203+ assert rv.status_code == 4001204+ assert rv.data == b'{"msg":"W00t"}\n'1205+ assert rv.mimetype == 'application/json'1206+1207+ rv = flask.make_response(1208+ flask.Response(''), 400)1209+ assert rv.status_code == 4001210+ assert rv.data == b''1211+ assert rv.mimetype == 'text/html'1212+1213+ rv = flask.make_response(1214+ flask.Response('', headers={'Content-Type': 'text/html'}),1215+ 400, [('X-Foo', 'bar')])1216+ assert rv.status_code == 4001217+ assert rv.headers['Content-Type'] == 'text/html'1218+ assert rv.headers['X-Foo'] == 'bar'1219+1220+1221+def test_jsonify_no_prettyprint(app, req_ctx):1222 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})995- with app.test_request_context():996- compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'997- uncompressed_msg = {998- "msg": {999- "submsg": "W00t"1000- },1001- "msg2": "foobar"1002- }1223+ compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1224+ uncompressed_msg = {1225+ "msg": {1226+ "submsg": "W00t"1227+ },1228+ "msg2": "foobar"1229+ }1230 1004- rv = flask.make_response(1005- flask.jsonify(uncompressed_msg), 200)1006- assert rv.data == compressed_msg1231+ rv = flask.make_response(1232+ flask.jsonify(uncompressed_msg), 200)1233+ assert rv.data == compressed_msg1234 1235 1009-def test_jsonify_prettyprint():1010- app = flask.Flask(__name__)1236+def test_jsonify_prettyprint(app, req_ctx):1237 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1012- with app.test_request_context():1013- compressed_msg = {"msg":{"submsg":"W00t"},"msg2":"foobar"}1014- pretty_response =\1015- b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'1238+ compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1239+ pretty_response = \1240+ b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'1241 1017- rv = flask.make_response(1018- flask.jsonify(compressed_msg), 200)1019- assert rv.data == pretty_response1242+ rv = flask.make_response(1243+ flask.jsonify(compressed_msg), 200)1244+ assert rv.data == pretty_response1245 1246 1022-def test_jsonify_mimetype():1023- app = flask.Flask(__name__)1247+def test_jsonify_mimetype(app, req_ctx):1248 app.config.update({"JSONIFY_MIMETYPE": 'application/vnd.api+json'})1025- with app.test_request_context():1026- msg = {1027- "msg": {"submsg": "W00t"},1028- }1029- rv = flask.make_response(1030- flask.jsonify(msg), 200)1031- assert rv.mimetype == 'application/vnd.api+json'1249+ msg = {1250+ "msg": {"submsg": "W00t"},1251+ }1252+ rv = flask.make_response(1253+ flask.jsonify(msg), 200)1254+ assert rv.mimetype == 'application/vnd.api+json'1255 1256 1034-def test_jsonify_args_and_kwargs_check():1035- app = flask.Flask(__name__)1036- with app.test_request_context():1037- with pytest.raises(TypeError) as e:1038- flask.jsonify('fake args', kwargs='fake')1039- assert 'behavior undefined' in str(e.value)1257+def test_jsonify_args_and_kwargs_check(app, req_ctx):1258+ with pytest.raises(TypeError) as e:1259+ flask.jsonify('fake args', kwargs='fake')1260+ assert 'behavior undefined' in str(e.value)1261 1262 1042-def test_url_generation():1043- app = flask.Flask(__name__)1044-1263+def test_url_generation(app, req_ctx):1264 @app.route('/hello/<name>', methods=['POST'])1265 def hello():1266 pass1048- with app.test_request_context():1049- assert flask.url_for('hello', name='test x') == '/hello/test%20x'1050- assert flask.url_for('hello', name='test x', _external=True) == \1051- 'http://localhost/hello/test%20x'1267 1268+ assert flask.url_for('hello', name='test x') == '/hello/test%20x'1269+ assert flask.url_for('hello', name='test x', _external=True) == \1270+ 'http://localhost/hello/test%20x'1271 1054-def test_build_error_handler():1055- app = flask.Flask(__name__)1272 1273+def test_build_error_handler(app):1274 # Test base case, a URL which results in a BuildError.1275 with app.test_request_context():1276 pytest.raises(BuildError, flask.url_for, 'spam')1277 12 unmodified lines1290 # Test a custom handler.1291 def handler(error, endpoint, values):1292 # Just a test.1293 return '/test_handler/'1294+1295 app.url_build_error_handlers.append(handler)1296 with app.test_request_context():1297 assert flask.url_for('spam') == '/test_handler/'1298 1299 1082-def test_build_error_handler_reraise():1083- app = flask.Flask(__name__)1084-1300+def test_build_error_handler_reraise(app):1301 # Test a custom handler which reraises the BuildError1302 def handler_raises_build_error(error, endpoint, values):1303 raise error1304+1305 app.url_build_error_handlers.append(handler_raises_build_error)1306 1307 with app.test_request_context():1308 pytest.raises(BuildError, flask.url_for, 'not.existing')1309 1310 1311+def test_url_for_passes_special_values_to_build_error_handler(app):1312+ @app.url_build_error_handlers.append1313+ def handler(error, endpoint, values):1314+ assert values == {1315+ '_external': False,1316+ '_anchor': None,1317+ '_method': None,1318+ '_scheme': None,1319+ }1320+ return 'handled'1321+1322+ with app.test_request_context():1323+ flask.url_for('/')1324+1325+1094-def test_custom_converters():1326+def test_custom_converters(app, client):1327 from werkzeug.routing import BaseConverter1328 1329 class ListConverter(BaseConverter):1098-1330 def to_python(self, value):1331 return value.split(',')1332 1333 def to_url(self, value):1334 base_to_url = super(ListConverter, self).to_url1335 return ','.join(base_to_url(x) for x in value)1105- app = flask.Flask(__name__)1336+1337 app.url_map.converters['list'] = ListConverter1338 1339 @app.route('/<list:args>')1340 def index(args):1341 return '|'.join(args)1111- c = app.test_client()1112- assert c.get('/1,2,3').data == b'1|2|3'1342 1343+ assert client.get('/1,2,3').data == b'1|2|3'1344 1115-def test_static_files():1116- app = flask.Flask(__name__)1117- app.testing = True1118- rv = app.test_client().get('/static/index.html')1345+1346+def test_static_files(app, client):1347+ rv = client.get('/static/index.html')1348 assert rv.status_code == 2001349 assert rv.data.strip() == b'<h1>Hello World!</h1>'1350 with app.test_request_context():1351 assert flask.url_for('static', filename='index.html') == \1123- '/static/index.html'1352+ '/static/index.html'1353 rv.close()1354 1355 1356 def test_static_path_deprecated(recwarn):19 unmodified lines1376 with app.test_request_context():1377 assert flask.url_for('static', filename='index.html') == '/foo/index.html'1378 1379 1151-def test_none_response():1152- app = flask.Flask(__name__)1153- app.testing = True1380+def test_static_route_with_host_matching():1381+ app = flask.Flask(__name__, host_matching=True, static_host='example.com')1382+ c = app.test_client()1383+ rv = c.get('http://example.com/static/index.html')1384+ assert rv.status_code == 2001385+ rv.close()1386+ with app.test_request_context():1387+ rv = flask.url_for('static', filename='index.html', _external=True)1388+ assert rv == 'http://example.com/static/index.html'1389+ # Providing static_host without host_matching=True should error.1390+ with pytest.raises(Exception):1391+ flask.Flask(__name__, static_host='example.com')1392+ # Providing host_matching=True with static_folder but without static_host should error.1393+ with pytest.raises(Exception):1394+ flask.Flask(__name__, host_matching=True)1395+ # Providing host_matching=True without static_host but with static_folder=None should not error.1396+ flask.Flask(__name__, host_matching=True, static_folder=None)1397 1155- @app.route('/')1156- def test():1157- return None1158- try:1159- app.test_client().get('/')1160- except ValueError as e:1161- assert str(e) == 'View function did not return a response'1162- pass1163- else:1164- assert "Expected ValueError"1398 1166-1399 def test_request_locals():1400 assert repr(flask.g) == '<LocalProxy unbound>'1401 assert not flask.g1402 1403 1172-def test_test_app_proper_environ():1173- app = flask.Flask(__name__)1404+def test_test_app_proper_environ(app, client):1405 app.config.update(1406 SERVER_NAME='localhost.localdomain:5000'1407 )1408 4 unmodified lines1413 @app.route('/', subdomain='foo')1414 def subdomain():1415 return 'Foo SubDomain'1416 1186- rv = app.test_client().get('/')1417+ rv = client.get('/')1418 assert rv.data == b'Foo'1419 1189- rv = app.test_client().get('/', 'http://localhost.localdomain:5000')1420+ rv = client.get('/', 'http://localhost.localdomain:5000')1421 assert rv.data == b'Foo'1422 1192- rv = app.test_client().get('/', 'https://localhost.localdomain:5000')1423+ rv = client.get('/', 'https://localhost.localdomain:5000')1424 assert rv.data == b'Foo'1425 1426 app.config.update(SERVER_NAME='localhost.localdomain')1196- rv = app.test_client().get('/', 'https://localhost.localdomain')1427+ rv = client.get('/', 'https://localhost.localdomain')1428 assert rv.data == b'Foo'1429 1430 try:1431 app.config.update(SERVER_NAME='localhost.localdomain:443')1201- rv = app.test_client().get('/', 'https://localhost.localdomain')1432+ rv = client.get('/', 'https://localhost.localdomain')1433 # Werkzeug 0.81434 assert rv.status_code == 4041435 except ValueError as e:1436 # Werkzeug 0.74 unmodified lines1441 )1442 1443 try:1444 app.config.update(SERVER_NAME='localhost.localdomain')1214- rv = app.test_client().get('/', 'http://foo.localhost')1445+ rv = client.get('/', 'http://foo.localhost')1446 # Werkzeug 0.81447 assert rv.status_code == 4041448 except ValueError as e:1449 # Werkzeug 0.72 unmodified lines1452 "('localhost.localdomain') does not match the "1453 "server name from the WSGI environment ('foo.localhost')"1454 )1455 1225- rv = app.test_client().get('/', 'http://foo.localhost.localdomain')1456+ rv = client.get('/', 'http://foo.localhost.localdomain')1457 assert rv.data == b'Foo SubDomain'1458 1459 1229-def test_exception_propagation():1460+def test_exception_propagation(app, client):1461 def apprunner(config_key):1231- app = flask.Flask(__name__)1462 app.config['LOGGER_HANDLER_POLICY'] = 'never'1463 1464 @app.route('/')1465 def index():1466 1 // 01237- c = app.test_client()1467+1468 if config_key is not None:1469 app.config[config_key] = True1470 with pytest.raises(Exception):1241- c.get('/')1471+ client.get('/')1472 else:1243- assert c.get('/').status_code == 5001473+ assert client.get('/').status_code == 5001474 1475 # we have to run this test in an isolated thread because if the1476 # debug flag is set to true and an exception happens the context is1477 # not torn down. This causes other tests that run after this fail8 unmodified lines1486 @pytest.mark.parametrize('use_debugger', [True, False])1487 @pytest.mark.parametrize('use_reloader', [True, False])1488 @pytest.mark.parametrize('propagate_exceptions', [None, True, False])1489 def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1260- use_reloader, propagate_exceptions):1490+ use_reloader, propagate_exceptions, app):1491 rv = {}1492 1493 # Mocks werkzeug.serving.run_simple method1494 def run_simple_mock(*args, **kwargs):1495 rv['passthrough_errors'] = kwargs.get('passthrough_errors')1496 1267- app = flask.Flask(__name__)1497 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1498 app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1499 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)1271- # make sure werkzeug always passes errors through1272- assert rv['passthrough_errors']1500 1501 1275-def test_max_content_length():1276- app = flask.Flask(__name__)1502+def test_max_content_length(app, client):1503 app.config['MAX_CONTENT_LENGTH'] = 641504 1505 @app.before_request1506 def always_first():8 unmodified lines1515 @app.errorhandler(413)1516 def catcher(error):1517 return '42'1518 1293- c = app.test_client()1294- rv = c.post('/accept', data={'myfile': 'foo' * 100})1519+ rv = client.post('/accept', data={'myfile': 'foo' * 100})1520 assert rv.data == b'42'1521 1522 1298-def test_url_processors():1299- app = flask.Flask(__name__)1523+def test_url_processors(app, client):1524 1525 @app.url_defaults1526 def add_language_code(endpoint, values):1527 if flask.g.lang_code is not None and \1304- app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1528+ app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1529 values.setdefault('lang_code', flask.g.lang_code)1530 1531 @app.url_value_preprocessor1532 def pull_lang_code(endpoint, values):10 unmodified lines1543 @app.route('/foo')1544 def something_else():1545 return flask.url_for('about', lang_code='en')1546 1323- c = app.test_client()1547+ assert client.get('/de/').data == b'/de/about'1548+ assert client.get('/de/about').data == b'/foo'1549+ assert client.get('/foo').data == b'/en/about'1550 1325- assert c.get('/de/').data == b'/de/about'1326- assert c.get('/de/about').data == b'/foo'1327- assert c.get('/foo').data == b'/en/about'1551 1329-1330-def test_inject_blueprint_url_defaults():1552+def test_inject_blueprint_url_defaults(app):1331- app = flask.Flask(__name__)1553 bp = flask.Blueprint('foo.bar.baz', __name__,1554 template_folder='template')1555 1556 @bp.url_defaults16 unmodified lines1573 expected = '/login'1574 assert url == expected1575 1576 1356-def test_nonascii_pathinfo():1357- app = flask.Flask(__name__)1358- app.testing = True1359-1577+def test_nonascii_pathinfo(app, client):1578 @app.route(u'/киртест')1579 def index():1580 return 'Hello World!'1581 1364- c = app.test_client()1365- rv = c.get(u'/киртест')1582+ rv = client.get(u'/киртест')1583 assert rv.data == b'Hello World!'1584 1585 1369-def test_debug_mode_complains_after_first_request():1370- app = flask.Flask(__name__)1586+def test_debug_mode_complains_after_first_request(app, client):1587 app.debug = True1588 1589 @app.route('/')1590 def index():1591 return 'Awesome'1592+1593 assert not app.got_first_request1377- assert app.test_client().get('/').data == b'Awesome'1594+ assert client.get('/').data == b'Awesome'1595 with pytest.raises(AssertionError) as e:1596 @app.route('/foo')1597 def broken():1598 return 'Meh'3 unmodified lines1602 1603 @app.route('/foo')1604 def working():1605 return 'Meh'1606+1389- assert app.test_client().get('/foo').data == b'Meh'1607+ assert client.get('/foo').data == b'Meh'1608 assert app.got_first_request1609 1610 1393-def test_before_first_request_functions():1611+def test_before_first_request_functions(app, client):1612 got = []1395- app = flask.Flask(__name__)1613 1614 @app.before_first_request1615 def foo():1616 got.append(42)1400- c = app.test_client()1401- c.get('/')1617+1618+ client.get('/')1619 assert got == [42]1403- c.get('/')1620+ client.get('/')1621 assert got == [42]1622 assert app.got_first_request1623 1624 1408-def test_before_first_request_functions_concurrent():1625+def test_before_first_request_functions_concurrent(app, client):1626 got = []1410- app = flask.Flask(__name__)1627 1628 @app.before_first_request1629 def foo():1630 time.sleep(0.2)1631 got.append(42)1632 1417- c = app.test_client()1418-1633 def get_and_assert():1420- c.get("/")1634+ client.get("/")1635 assert got == [42]1636 1637 t = Thread(target=get_and_assert)1638 t.start()1 unmodified line1640 t.join()1641 assert app.got_first_request1642 1643 1430-def test_routing_redirect_debugging():1431- app = flask.Flask(__name__)1644+def test_routing_redirect_debugging(app, client):1645 app.debug = True1646 1647 @app.route('/foo/', methods=['GET', 'POST'])1648 def foo():1649 return 'success'1437- with app.test_client() as c:1650+1651+ with client:1652 with pytest.raises(AssertionError) as e:1439- c.post('/foo', data={})1653+ client.post('/foo', data={})1654 assert 'http://localhost/foo/' in str(e)1655 assert ('Make sure to directly send '1656 'your POST-request to this URL') in str(e)1657 1444- rv = c.get('/foo', data={}, follow_redirects=True)1658+ rv = client.get('/foo', data={}, follow_redirects=True)1659 assert rv.data == b'success'1660 1661 app.debug = False1448- with app.test_client() as c:1449- rv = c.post('/foo', data={}, follow_redirects=True)1662+ with client:1663+ rv = client.post('/foo', data={}, follow_redirects=True)1664 assert rv.data == b'success'1665 1666 1453-def test_route_decorator_custom_endpoint():1454- app = flask.Flask(__name__)1667+def test_route_decorator_custom_endpoint(app, client):1668 app.debug = True1669 1670 @app.route('/foo/')1671 def foo():11 unmodified lines1683 assert flask.url_for('foo') == '/foo/'1684 assert flask.url_for('bar') == '/bar/'1685 assert flask.url_for('123') == '/bar/123'1686 1474- c = app.test_client()1475- assert c.get('/foo/').data == b'foo'1476- assert c.get('/bar/').data == b'bar'1477- assert c.get('/bar/123').data == b'123'1687+ assert client.get('/foo/').data == b'foo'1688+ assert client.get('/bar/').data == b'bar'1689+ assert client.get('/bar/123').data == b'123'1690 1691 1480-def test_preserve_only_once():1481- app = flask.Flask(__name__)1692+def test_preserve_only_once(app, client):1693 app.debug = True1694 1695 @app.route('/fail')1696 def fail_func():1697 1 // 01698 1488- c = app.test_client()1699 for x in range(3):1700 with pytest.raises(ZeroDivisionError):1491- c.get('/fail')1701+ client.get('/fail')1702 1703 assert flask._request_ctx_stack.top is not None1704 assert flask._app_ctx_stack.top is not None1705 # implicit appctx disappears too1 unmodified line1707 assert flask._request_ctx_stack.top is None1708 assert flask._app_ctx_stack.top is None1709 1710 1501-def test_preserve_remembers_exception():1502- app = flask.Flask(__name__)1711+def test_preserve_remembers_exception(app, client):1712 app.debug = True1713 errors = []1714 1715 @app.route('/fail')7 unmodified lines1723 @app.teardown_request1724 def teardown_handler(exc):1725 errors.append(exc)1726 1518- c = app.test_client()1519-1727 # After this failure we did not yet call the teardown handler1728 with pytest.raises(ZeroDivisionError):1522- c.get('/fail')1729+ client.get('/fail')1730 assert errors == []1731 1732 # But this request triggers it, and it's an error1526- c.get('/success')1733+ client.get('/success')1734 assert len(errors) == 21735 assert isinstance(errors[0], ZeroDivisionError)1736 1737 # At this point another request does nothing.1531- c.get('/success')1738+ client.get('/success')1739 assert len(errors) == 31740 assert errors[1] is None1741 1742 1536-def test_get_method_on_g():1537- app = flask.Flask(__name__)1538- app.testing = True1743+def test_get_method_on_g(app_ctx):1744+ assert flask.g.get('x') is None1745+ assert flask.g.get('x', 11) == 111746+ flask.g.x = 421747+ assert flask.g.get('x') == 421748+ assert flask.g.x == 421749 1540- with app.app_context():1541- assert flask.g.get('x') is None1542- assert flask.g.get('x', 11) == 111543- flask.g.x = 421544- assert flask.g.get('x') == 421545- assert flask.g.x == 421750 1751+def test_g_iteration_protocol(app_ctx):1752+ flask.g.foo = 231753+ flask.g.bar = 421754+ assert 'foo' in flask.g1755+ assert 'foos' not in flask.g1756+ assert sorted(flask.g) == ['bar', 'foo']1757 1548-def test_g_iteration_protocol():1549- app = flask.Flask(__name__)1550- app.testing = True1758 1552- with app.app_context():1553- flask.g.foo = 231554- flask.g.bar = 421555- assert 'foo' in flask.g1556- assert 'foos' not in flask.g1557- assert sorted(flask.g) == ['bar', 'foo']1759+def test_subdomain_basic_support(app, client):1760+ app.config['SERVER_NAME'] = 'localhost.localdomain'1761 1559-1560-def test_subdomain_basic_support():1561- app = flask.Flask(__name__)1562- app.config['SERVER_NAME'] = 'localhost'1563-1762 @app.route('/')1763 def normal_index():1764 return 'normal index'1765 1766 @app.route('/', subdomain='test')1767 def test_index():1768 return 'test index'1769 1572- c = app.test_client()1573- rv = c.get('/', 'http://localhost/')1770+ rv = client.get('/', 'http://localhost.localdomain/')1771 assert rv.data == b'normal index'1772 1576- rv = c.get('/', 'http://test.localhost/')1773+ rv = client.get('/', 'http://test.localhost.localdomain/')1774 assert rv.data == b'test index'1775 1776 1580-def test_subdomain_matching():1581- app = flask.Flask(__name__)1582- app.config['SERVER_NAME'] = 'localhost'1777+def test_subdomain_matching(app, client):1778+ app.config['SERVER_NAME'] = 'localhost.localdomain'1779 1780 @app.route('/', subdomain='<user>')1781 def index(user):1782 return 'index for %s' % user1783 1588- c = app.test_client()1589- rv = c.get('/', 'http://mitsuhiko.localhost/')1784+ rv = client.get('/', 'http://mitsuhiko.localhost.localdomain/')1785 assert rv.data == b'index for mitsuhiko'1786 1787 1593-def test_subdomain_matching_with_ports():1594- app = flask.Flask(__name__)1595- app.config['SERVER_NAME'] = 'localhost:3000'1788+def test_subdomain_matching_with_ports(app, client):1789+ app.config['SERVER_NAME'] = 'localhost.localdomain:3000'1790 1791 @app.route('/', subdomain='<user>')1792 def index(user):1793 return 'index for %s' % user1794 1601- c = app.test_client()1602- rv = c.get('/', 'http://mitsuhiko.localhost:3000/')1795+ rv = client.get('/', 'http://mitsuhiko.localhost.localdomain:3000/')1796 assert rv.data == b'index for mitsuhiko'1797 1798 1606-def test_multi_route_rules():1607- app = flask.Flask(__name__)1608-1799+def test_multi_route_rules(app, client):1800 @app.route('/')1801 @app.route('/<test>/')1802 def index(test='a'):1803 return test1804 1614- rv = app.test_client().open('/')1805+ rv = client.open('/')1806 assert rv.data == b'a'1616- rv = app.test_client().open('/b/')1807+ rv = client.open('/b/')1808 assert rv.data == b'b'1809 1810 1620-def test_multi_route_class_views():1811+def test_multi_route_class_views(app, client):1812 class View(object):1622-1813 def __init__(self, app):1814 app.add_url_rule('/', 'index', self.index)1815 app.add_url_rule('/<test>/', 'index', self.index)1816 1817 def index(self, test='a'):1818 return test1819 1630- app = flask.Flask(__name__)1820 _ = View(app)1632- rv = app.test_client().open('/')1821+ rv = client.open('/')1822 assert rv.data == b'a'1634- rv = app.test_client().open('/b/')1823+ rv = client.open('/b/')1824 assert rv.data == b'b'1825 1826 1638-def test_run_defaults(monkeypatch):1827+def test_run_defaults(monkeypatch, app):1828 rv = {}1829 1830 # Mocks werkzeug.serving.run_simple method1831 def run_simple_mock(*args, **kwargs):1832 rv['result'] = 'running...'1833 1645- app = flask.Flask(__name__)1834 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1835 app.run()1836 assert rv['result'] == 'running...'1837 1838 1651-def test_run_server_port(monkeypatch):1839+def test_run_server_port(monkeypatch, app):1840 rv = {}1841 1842 # Mocks werkzeug.serving.run_simple method1843 def run_simple_mock(hostname, port, application, *args, **kwargs):1844 rv['result'] = 'running on %s:%s ...' % (hostname, port)1845 1658- app = flask.Flask(__name__)1846 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1847 hostname, port = 'localhost', 80001848 app.run(hostname, port, debug=True)1849 assert rv['result'] == 'running on %s:%s ...' % (hostname, port)1850+1851+1852+@pytest.mark.parametrize('host,port,expect_host,expect_port', (1853+ (None, None, 'pocoo.org', 8080),1854+ ('localhost', None, 'localhost', 8080),1855+ (None, 80, 'pocoo.org', 80),1856+ ('localhost', 80, 'localhost', 80),1857+))1858+def test_run_from_config(monkeypatch, host, port, expect_host, expect_port, app):1859+ def run_simple_mock(hostname, port, *args, **kwargs):1860+ assert hostname == expect_host1861+ assert port == expect_port1862+1863+ monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1864+ app.config['SERVER_NAME'] = 'pocoo.org:8080'1865+ app.run(host, port)modified:tests/test_blueprints.py+355 added-109 removed
16 unmodified lines17 from werkzeug.http import parse_cache_control_header18 from jinja2 import TemplateNotFound19 20 21-def test_blueprint_specific_error_handling():21+def test_blueprint_specific_error_handling(app, client):22 frontend = flask.Blueprint('frontend', __name__)23 backend = flask.Blueprint('backend', __name__)24 sideend = flask.Blueprint('sideend', __name__)25 16 unmodified lines42 @sideend.route('/what-is-a-sideend')43 def sideend_no():44 flask.abort(403)45 46- app = flask.Flask(__name__)46 app.register_blueprint(frontend)47 app.register_blueprint(backend)48 app.register_blueprint(sideend)49 50 @app.errorhandler(403)51 def app_forbidden(e):52 return 'application itself says no', 40353 55- c = app.test_client()54+ assert client.get('/frontend-no').data == b'frontend says no'55+ assert client.get('/backend-no').data == b'backend says no'56+ assert client.get('/what-is-a-sideend').data == b'application itself says no'57 57- assert c.get('/frontend-no').data == b'frontend says no'58- assert c.get('/backend-no').data == b'backend says no'59- assert c.get('/what-is-a-sideend').data == b'application itself says no'58 61-def test_blueprint_specific_user_error_handling():59+def test_blueprint_specific_user_error_handling(app, client):60 class MyDecoratorException(Exception):61 pass62+63 class MyFunctionException(Exception):64 pass65 66 blue = flask.Blueprint('blue', __name__)5 unmodified lines72 73 def my_function_exception_handler(e):74 assert isinstance(e, MyFunctionException)75 return 'bam'76+77 blue.register_error_handler(MyFunctionException, my_function_exception_handler)78 79 @blue.route('/decorator')80 def blue_deco_test():81 raise MyDecoratorException()82+83 @blue.route('/function')84 def blue_func_test():85 raise MyFunctionException()86 86- app = flask.Flask(__name__)87 app.register_blueprint(blue)88 89- c = app.test_client()89+ assert client.get('/decorator').data == b'boom'90+ assert client.get('/function').data == b'bam'91 91- assert c.get('/decorator').data == b'boom'92- assert c.get('/function').data == b'bam'92 94-def test_blueprint_url_definitions():93+def test_blueprint_app_error_handling(app, client):94+ errors = flask.Blueprint('errors', __name__)95+96+ @errors.app_errorhandler(403)97+ def forbidden_handler(e):98+ return 'you shall not pass', 40399+100+ @app.route('/forbidden')101+ def app_forbidden():102+ flask.abort(403)103+104+ forbidden_bp = flask.Blueprint('forbidden_bp', __name__)105+106+ @forbidden_bp.route('/nope')107+ def bp_forbidden():108+ flask.abort(403)109+110+ app.register_blueprint(errors)111+ app.register_blueprint(forbidden_bp)112+113+ assert client.get('/forbidden').data == b'you shall not pass'114+ assert client.get('/nope').data == b'you shall not pass'115+116+117+def test_blueprint_url_definitions(app, client):118 bp = flask.Blueprint('test', __name__)119 120 @bp.route('/foo', defaults={'baz': 42})121 def foo(bar, baz):2 unmodified lines124 @bp.route('/bar')125 def bar(bar):126 return text_type(bar)127 105- app = flask.Flask(__name__)128 app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23})129 app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19})130 109- c = app.test_client()110- assert c.get('/1/foo').data == b'23/42'111- assert c.get('/2/foo').data == b'19/42'112- assert c.get('/1/bar').data == b'23'113- assert c.get('/2/bar').data == b'19'131+ assert client.get('/1/foo').data == b'23/42'132+ assert client.get('/2/foo').data == b'19/42'133+ assert client.get('/1/bar').data == b'23'134+ assert client.get('/2/bar').data == b'19'135 136+115-def test_blueprint_url_processors():137+def test_blueprint_url_processors(app, client):138 bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')139 140 @bp.url_defaults141 def add_language_code(endpoint, values):10 unmodified lines152 @bp.route('/about')153 def about():154 return flask.url_for('.index')155 134- app = flask.Flask(__name__)156 app.register_blueprint(bp)157 137- c = app.test_client()158+ assert client.get('/de/').data == b'/de/about'159+ assert client.get('/de/about').data == b'/de/'160 139- assert c.get('/de/').data == b'/de/about'140- assert c.get('/de/about').data == b'/de/'161 162 def test_templates_and_static(test_apps):163 from blueprintapp import app144- c = app.test_client()164+ client = app.test_client()165 146- rv = c.get('/')166+ rv = client.get('/')167 assert rv.data == b'Hello from the Frontend'148- rv = c.get('/admin/')168+ rv = client.get('/admin/')169 assert rv.data == b'Hello from the Admin'150- rv = c.get('/admin/index2')170+ rv = client.get('/admin/index2')171 assert rv.data == b'Hello from the Admin'152- rv = c.get('/admin/static/test.txt')172+ rv = client.get('/admin/static/test.txt')173 assert rv.data.strip() == b'Admin File'174 rv.close()155- rv = c.get('/admin/static/css/test.css')175+ rv = client.get('/admin/static/css/test.css')176 assert rv.data.strip() == b'/* nested file */'177 rv.close()178 179 # try/finally, in case other tests use this app for Blueprint tests.2 unmodified lines182 expected_max_age = 3600183 if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == expected_max_age:184 expected_max_age = 7200185 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age166- rv = c.get('/admin/static/css/test.css')186+ rv = client.get('/admin/static/css/test.css')187 cc = parse_cache_control_header(rv.headers['Cache-Control'])188 assert cc.max_age == expected_max_age189 rv.close()190 finally:9 unmodified lines200 201 with flask.Flask(__name__).test_request_context():202 assert flask.render_template('nested/nested.txt') == 'I\'m nested'203 184-def test_default_static_cache_timeout():185- app = flask.Flask(__name__)204+205+def test_default_static_cache_timeout(app):206 class MyBlueprint(flask.Blueprint):207 def get_send_file_max_age(self, filename):208 return 100209 14 unmodified lines224 rv.close()225 finally:226 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default227 228+229 def test_templates_list(test_apps):230 from blueprintapp import app231 templates = sorted(app.jinja_env.list_templates())232 assert templates == ['admin/index.html', 'frontend/index.html']233 234+213-def test_dotted_names():235+def test_dotted_names(app, client):236 frontend = flask.Blueprint('myapp.frontend', __name__)237 backend = flask.Blueprint('myapp.backend', __name__)238 239 @frontend.route('/fe')7 unmodified lines247 @backend.route('/be')248 def backend_index():249 return flask.url_for('myapp.frontend.frontend_index')250 229- app = flask.Flask(__name__)251 app.register_blueprint(frontend)252 app.register_blueprint(backend)253 233- c = app.test_client()234- assert c.get('/fe').data.strip() == b'/be'235- assert c.get('/fe2').data.strip() == b'/fe'236- assert c.get('/be').data.strip() == b'/fe'254+ assert client.get('/fe').data.strip() == b'/be'255+ assert client.get('/fe2').data.strip() == b'/fe'256+ assert client.get('/be').data.strip() == b'/fe'257 238-def test_dotted_names_from_app():239- app = flask.Flask(__name__)240- app.testing = True258+259+def test_dotted_names_from_app(app, client):260 test = flask.Blueprint('test', __name__)261 262 @app.route('/')263 def app_index():4 unmodified lines268 return flask.url_for('app_index')269 270 app.register_blueprint(test)271 253- with app.test_client() as c:254- rv = c.get('/')255- assert rv.data == b'/test/'272+ rv = client.get('/')273+ assert rv.data == b'/test/'274 275+257-def test_empty_url_defaults():276+def test_empty_url_defaults(app, client):277 bp = flask.Blueprint('bp', __name__)278 279 @bp.route('/', defaults={'page': 1})280 @bp.route('/page/<int:page>')281 def something(page):282 return str(page)283 265- app = flask.Flask(__name__)284 app.register_blueprint(bp)285 268- c = app.test_client()269- assert c.get('/').data == b'1'270- assert c.get('/page/2').data == b'2'286+ assert client.get('/').data == b'1'287+ assert client.get('/page/2').data == b'2'288 272-def test_route_decorator_custom_endpoint():289 290+def test_route_decorator_custom_endpoint(app, client):291 bp = flask.Blueprint('bp', __name__)292 293 @bp.route('/foo')294 def foo():10 unmodified lines305 @bp.route('/bar/foo')306 def bar_foo():307 return flask.request.endpoint308 292- app = flask.Flask(__name__)309 app.register_blueprint(bp, url_prefix='/py')310 311 @app.route('/')312 def index():313 return flask.request.endpoint314 299- c = app.test_client()300- assert c.get('/').data == b'index'301- assert c.get('/py/foo').data == b'bp.foo'302- assert c.get('/py/bar').data == b'bp.bar'303- assert c.get('/py/bar/123').data == b'bp.123'304- assert c.get('/py/bar/foo').data == b'bp.bar_foo'315+ assert client.get('/').data == b'index'316+ assert client.get('/py/foo').data == b'bp.foo'317+ assert client.get('/py/bar').data == b'bp.bar'318+ assert client.get('/py/bar/123').data == b'bp.123'319+ assert client.get('/py/bar/foo').data == b'bp.bar_foo'320 321+306-def test_route_decorator_custom_endpoint_with_dots():322+def test_route_decorator_custom_endpoint_with_dots(app, client):323 bp = flask.Blueprint('bp', __name__)324 325 @bp.route('/foo')326 def foo():32 unmodified lines359 bp.route('/bar/123', endpoint='bar.123'),360 lambda: None361 )362 347- app = flask.Flask(__name__)363 app.register_blueprint(bp, url_prefix='/py')364 350- c = app.test_client()351- assert c.get('/py/foo').data == b'bp.foo'365+ assert client.get('/py/foo').data == b'bp.foo'366 # The rule's didn't actually made it through353- rv = c.get('/py/bar')367+ rv = client.get('/py/bar')368 assert rv.status_code == 404355- rv = c.get('/py/bar/123')369+ rv = client.get('/py/bar/123')370 assert rv.status_code == 404371 358-def test_template_filter():372+373+def test_endpoint_decorator(app, client):374+ from werkzeug.routing import Rule375+ app.url_map.add(Rule('/foo', endpoint='bar'))376+377 bp = flask.Blueprint('bp', __name__)378+379+ @bp.endpoint('bar')380+ def foobar():381+ return flask.request.endpoint382+383+ app.register_blueprint(bp, url_prefix='/bp_prefix')384+385+ assert client.get('/foo').data == b'bar'386+ assert client.get('/bp_prefix/bar').status_code == 404387+388+389+def test_template_filter(app):390+ bp = flask.Blueprint('bp', __name__)391+392 @bp.app_template_filter()393 def my_reverse(s):394 return s[::-1]363- app = flask.Flask(__name__)395+396 app.register_blueprint(bp, url_prefix='/py')397 assert 'my_reverse' in app.jinja_env.filters.keys()398 assert app.jinja_env.filters['my_reverse'] == my_reverse399 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'400 401+369-def test_add_template_filter():402+def test_add_template_filter(app):403 bp = flask.Blueprint('bp', __name__)404+405 def my_reverse(s):406 return s[::-1]407+408 bp.add_app_template_filter(my_reverse)374- app = flask.Flask(__name__)409 app.register_blueprint(bp, url_prefix='/py')410 assert 'my_reverse' in app.jinja_env.filters.keys()411 assert app.jinja_env.filters['my_reverse'] == my_reverse412 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'413 414+380-def test_template_filter_with_name():415+def test_template_filter_with_name(app):416 bp = flask.Blueprint('bp', __name__)417+418 @bp.app_template_filter('strrev')419 def my_reverse(s):420 return s[::-1]385- app = flask.Flask(__name__)421+422 app.register_blueprint(bp, url_prefix='/py')423 assert 'strrev' in app.jinja_env.filters.keys()424 assert app.jinja_env.filters['strrev'] == my_reverse425 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'426 427+391-def test_add_template_filter_with_name():428+def test_add_template_filter_with_name(app):429 bp = flask.Blueprint('bp', __name__)430+431 def my_reverse(s):432 return s[::-1]433+434 bp.add_app_template_filter(my_reverse, 'strrev')396- app = flask.Flask(__name__)435 app.register_blueprint(bp, url_prefix='/py')436 assert 'strrev' in app.jinja_env.filters.keys()437 assert app.jinja_env.filters['strrev'] == my_reverse438 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'439 440+402-def test_template_filter_with_template():441+def test_template_filter_with_template(app, client):442 bp = flask.Blueprint('bp', __name__)443+444 @bp.app_template_filter()445 def super_reverse(s):446 return s[::-1]407- app = flask.Flask(__name__)447+448 app.register_blueprint(bp, url_prefix='/py')449+450 @app.route('/')451 def index():452 return flask.render_template('template_filter.html', value='abcd')412- rv = app.test_client().get('/')453+454+ rv = client.get('/')455 assert rv.data == b'dcba'456 415-def test_template_filter_after_route_with_template():416- app = flask.Flask(__name__)457+458+def test_template_filter_after_route_with_template(app, client):459 @app.route('/')460 def index():461 return flask.render_template('template_filter.html', value='abcd')462+463 bp = flask.Blueprint('bp', __name__)464+465 @bp.app_template_filter()466 def super_reverse(s):467 return s[::-1]468+469 app.register_blueprint(bp, url_prefix='/py')425- rv = app.test_client().get('/')470+ rv = client.get('/')471 assert rv.data == b'dcba'472 473+428-def test_add_template_filter_with_template():474+def test_add_template_filter_with_template(app, client):475 bp = flask.Blueprint('bp', __name__)476+477 def super_reverse(s):478 return s[::-1]479+480 bp.add_app_template_filter(super_reverse)433- app = flask.Flask(__name__)481 app.register_blueprint(bp, url_prefix='/py')482+483 @app.route('/')484 def index():485 return flask.render_template('template_filter.html', value='abcd')438- rv = app.test_client().get('/')486+487+ rv = client.get('/')488 assert rv.data == b'dcba'489 490+441-def test_template_filter_with_name_and_template():491+def test_template_filter_with_name_and_template(app, client):492 bp = flask.Blueprint('bp', __name__)493+494 @bp.app_template_filter('super_reverse')495 def my_reverse(s):496 return s[::-1]446- app = flask.Flask(__name__)497+498 app.register_blueprint(bp, url_prefix='/py')499+500 @app.route('/')501 def index():502 return flask.render_template('template_filter.html', value='abcd')451- rv = app.test_client().get('/')503+504+ rv = client.get('/')505 assert rv.data == b'dcba'506 507+454-def test_add_template_filter_with_name_and_template():508+def test_add_template_filter_with_name_and_template(app, client):509 bp = flask.Blueprint('bp', __name__)510+511 def my_reverse(s):512 return s[::-1]513+514 bp.add_app_template_filter(my_reverse, 'super_reverse')459- app = flask.Flask(__name__)515 app.register_blueprint(bp, url_prefix='/py')516+517 @app.route('/')518 def index():519 return flask.render_template('template_filter.html', value='abcd')464- rv = app.test_client().get('/')520+521+ rv = client.get('/')522 assert rv.data == b'dcba'523 524+467-def test_template_test():525+def test_template_test(app):526 bp = flask.Blueprint('bp', __name__)527+528 @bp.app_template_test()529 def is_boolean(value):530 return isinstance(value, bool)472- app = flask.Flask(__name__)531+532 app.register_blueprint(bp, url_prefix='/py')533 assert 'is_boolean' in app.jinja_env.tests.keys()534 assert app.jinja_env.tests['is_boolean'] == is_boolean535 assert app.jinja_env.tests['is_boolean'](False)536 537+478-def test_add_template_test():538+def test_add_template_test(app):539 bp = flask.Blueprint('bp', __name__)540+541 def is_boolean(value):542 return isinstance(value, bool)543+544 bp.add_app_template_test(is_boolean)483- app = flask.Flask(__name__)545 app.register_blueprint(bp, url_prefix='/py')546 assert 'is_boolean' in app.jinja_env.tests.keys()547 assert app.jinja_env.tests['is_boolean'] == is_boolean548 assert app.jinja_env.tests['is_boolean'](False)549 550+489-def test_template_test_with_name():551+def test_template_test_with_name(app):552 bp = flask.Blueprint('bp', __name__)553+554 @bp.app_template_test('boolean')555 def is_boolean(value):556 return isinstance(value, bool)494- app = flask.Flask(__name__)557+558 app.register_blueprint(bp, url_prefix='/py')559 assert 'boolean' in app.jinja_env.tests.keys()560 assert app.jinja_env.tests['boolean'] == is_boolean561 assert app.jinja_env.tests['boolean'](False)562 563+500-def test_add_template_test_with_name():564+def test_add_template_test_with_name(app):565 bp = flask.Blueprint('bp', __name__)566+567 def is_boolean(value):568 return isinstance(value, bool)569+570 bp.add_app_template_test(is_boolean, 'boolean')505- app = flask.Flask(__name__)571 app.register_blueprint(bp, url_prefix='/py')572 assert 'boolean' in app.jinja_env.tests.keys()573 assert app.jinja_env.tests['boolean'] == is_boolean574 assert app.jinja_env.tests['boolean'](False)575 576+511-def test_template_test_with_template():577+def test_template_test_with_template(app, client):578 bp = flask.Blueprint('bp', __name__)579+580 @bp.app_template_test()581 def boolean(value):582 return isinstance(value, bool)516- app = flask.Flask(__name__)583+584 app.register_blueprint(bp, url_prefix='/py')585+586 @app.route('/')587 def index():588 return flask.render_template('template_test.html', value=False)521- rv = app.test_client().get('/')589+590+ rv = client.get('/')591 assert b'Success!' in rv.data592 524-def test_template_test_after_route_with_template():525- app = flask.Flask(__name__)593+594+def test_template_test_after_route_with_template(app, client):595 @app.route('/')596 def index():597 return flask.render_template('template_test.html', value=False)598+599 bp = flask.Blueprint('bp', __name__)600+601 @bp.app_template_test()602 def boolean(value):603 return isinstance(value, bool)604+605 app.register_blueprint(bp, url_prefix='/py')534- rv = app.test_client().get('/')606+ rv = client.get('/')607 assert b'Success!' in rv.data608 609+537-def test_add_template_test_with_template():610+def test_add_template_test_with_template(app, client):611 bp = flask.Blueprint('bp', __name__)612+613 def boolean(value):614 return isinstance(value, bool)615+616 bp.add_app_template_test(boolean)542- app = flask.Flask(__name__)617 app.register_blueprint(bp, url_prefix='/py')618+619 @app.route('/')620 def index():621 return flask.render_template('template_test.html', value=False)547- rv = app.test_client().get('/')622+623+ rv = client.get('/')624 assert b'Success!' in rv.data625 626+550-def test_template_test_with_name_and_template():627+def test_template_test_with_name_and_template(app, client):628 bp = flask.Blueprint('bp', __name__)629+630 @bp.app_template_test('boolean')631 def is_boolean(value):632 return isinstance(value, bool)555- app = flask.Flask(__name__)633+634 app.register_blueprint(bp, url_prefix='/py')635+636 @app.route('/')637 def index():638 return flask.render_template('template_test.html', value=False)560- rv = app.test_client().get('/')639+640+ rv = client.get('/')641 assert b'Success!' in rv.data642 643+563-def test_add_template_test_with_name_and_template():644+def test_add_template_test_with_name_and_template(app, client):645 bp = flask.Blueprint('bp', __name__)646+647 def is_boolean(value):648 return isinstance(value, bool)649+650 bp.add_app_template_test(is_boolean, 'boolean')568- app = flask.Flask(__name__)651 app.register_blueprint(bp, url_prefix='/py')652+653 @app.route('/')654 def index():655 return flask.render_template('template_test.html', value=False)573- rv = app.test_client().get('/')656+657+ rv = client.get('/')658 assert b'Success!' in rv.data659+660+661+def test_context_processing(app, client):662+ answer_bp = flask.Blueprint('answer_bp', __name__)663+664+ template_string = lambda: flask.render_template_string(665+ '{% if notanswer %}{{ notanswer }} is not the answer. {% endif %}'666+ '{% if answer %}{{ answer }} is the answer.{% endif %}'667+ )668+669+ # App global context processor670+ @answer_bp.app_context_processor671+ def not_answer_context_processor():672+ return {'notanswer': 43}673+674+ # Blueprint local context processor675+ @answer_bp.context_processor676+ def answer_context_processor():677+ return {'answer': 42}678+679+ # Setup endpoints for testing680+ @answer_bp.route('/bp')681+ def bp_page():682+ return template_string()683+684+ @app.route('/')685+ def app_page():686+ return template_string()687+688+ # Register the blueprint689+ app.register_blueprint(answer_bp)690+691+ app_page_bytes = client.get('/').data692+ answer_page_bytes = client.get('/bp').data693+694+ assert b'43' in app_page_bytes695+ assert b'42' not in app_page_bytes696+697+ assert b'42' in answer_page_bytes698+ assert b'43' in answer_page_bytes699+700+701+def test_template_global(app):702+ bp = flask.Blueprint('bp', __name__)703+704+ @bp.app_template_global()705+ def get_answer():706+ return 42707+708+ # Make sure the function is not in the jinja_env already709+ assert 'get_answer' not in app.jinja_env.globals.keys()710+ app.register_blueprint(bp)711+712+ # Tests713+ assert 'get_answer' in app.jinja_env.globals.keys()714+ assert app.jinja_env.globals['get_answer'] is get_answer715+ assert app.jinja_env.globals['get_answer']() == 42716+717+ with app.app_context():718+ rv = flask.render_template_string('{{ get_answer() }}')719+ assert rv == '42'720+721+722+def test_request_processing(app, client):723+ bp = flask.Blueprint('bp', __name__)724+ evts = []725+726+ @bp.before_request727+ def before_bp():728+ evts.append('before')729+730+ @bp.after_request731+ def after_bp(response):732+ response.data += b'|after'733+ evts.append('after')734+ return response735+736+ @bp.teardown_request737+ def teardown_bp(exc):738+ evts.append('teardown')739+740+ # Setup routes for testing741+ @bp.route('/bp')742+ def bp_endpoint():743+ return 'request'744+745+ app.register_blueprint(bp)746+747+ assert evts == []748+ rv = client.get('/bp')749+ assert rv.data == b'request|after'750+ assert evts == ['before', 'after', 'teardown']751+752+753+def test_app_request_processing(app, client):754+ bp = flask.Blueprint('bp', __name__)755+ evts = []756+757+ @bp.before_app_first_request758+ def before_first_request():759+ evts.append('first')760+761+ @bp.before_app_request762+ def before_app():763+ evts.append('before')764+765+ @bp.after_app_request766+ def after_app(response):767+ response.data += b'|after'768+ evts.append('after')769+ return response770+771+ @bp.teardown_app_request772+ def teardown_app(exc):773+ evts.append('teardown')774+775+ app.register_blueprint(bp)776+777+ # Setup routes for testing778+ @app.route('/')779+ def bp_endpoint():780+ return 'request'781+782+ # before first request783+ assert evts == []784+785+ # first request786+ resp = client.get('/').data787+ assert resp == b'request|after'788+ assert evts == ['first', 'before', 'after', 'teardown']789+790+ # second request791+ resp = client.get('/').data792+ assert resp == b'request|after'793+ assert evts == ['first'] + ['before', 'after', 'teardown'] * 2794+795+796+def test_app_url_processors(app, client):797+ bp = flask.Blueprint('bp', __name__)798+799+ # Register app-wide url defaults and preprocessor on blueprint800+ @bp.app_url_defaults801+ def add_language_code(endpoint, values):802+ values.setdefault('lang_code', flask.g.lang_code)803+804+ @bp.app_url_value_preprocessor805+ def pull_lang_code(endpoint, values):806+ flask.g.lang_code = values.pop('lang_code')807+808+ # Register route rules at the app level809+ @app.route('/<lang_code>/')810+ def index():811+ return flask.url_for('about')812+813+ @app.route('/<lang_code>/about')814+ def about():815+ return flask.url_for('index')816+817+ app.register_blueprint(bp)818+819+ assert client.get('/de/').data == b'/de/about'820+ assert client.get('/de/about').data == b'/de/'modified:tests/test_cli.py+218 added-22 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, \25- find_default_import_path26+ 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.name38 39 40 def test_find_best_app(test_apps):35- """Test of find_best_app."""36- class mod:41+ """Test if `find_best_app` behaves as expected with different combinations of input."""42+ script_info = ScriptInfo()43+44+ class Module:45 app = Flask('appname')38- assert find_best_app(mod) == mod.app46 40- class mod:47+ assert find_best_app(script_info, Module) == Module.app48+49+ class Module:50 application = Flask('appname')42- assert find_best_app(mod) == mod.application51 44- class mod:45- myapp = Flask('appname')46- assert find_best_app(mod) == mod.myapp52+ assert find_best_app(script_info, Module) == Module.application53 48- class mod:54+ class Module:55 myapp = Flask('appname')56+57+ assert find_best_app(script_info, Module) == Module.myapp58+59+ class Module:60+ @staticmethod61+ def create_app():62+ return Flask('appname')63+64+ assert isinstance(find_best_app(script_info, Module), Flask)65+ assert find_best_app(script_info, Module).name == 'appname'66+67+ class Module:68+ @staticmethod69+ def create_app(foo):70+ return Flask('appname')71+72+ assert isinstance(find_best_app(script_info, Module), Flask)73+ assert find_best_app(script_info, Module).name == 'appname'74+75+ class Module:76+ @staticmethod77+ def create_app(foo=None, script_info=None):78+ return Flask('appname')79+80+ assert isinstance(find_best_app(script_info, Module), Flask)81+ assert find_best_app(script_info, Module).name == 'appname'82+83+ class Module:84+ @staticmethod85+ def make_app():86+ return Flask('appname')87+88+ assert isinstance(find_best_app(script_info, Module), Flask)89+ assert find_best_app(script_info, Module).name == 'appname'90+91+ class Module:92+ myapp = Flask('appname1')93+94+ @staticmethod95+ def create_app():96+ return Flask('appname2')97+98+ assert find_best_app(script_info, Module) == Module.myapp99+100+ class Module:101+ myapp = Flask('appname1')102+103+ @staticmethod104+ def create_app():105+ return Flask('appname2')106+107+ assert find_best_app(script_info, Module) == Module.myapp108+109+ class Module:110+ pass111+112+ pytest.raises(NoAppException, find_best_app, script_info, Module)113+114+ class Module:115+ myapp1 = Flask('appname1')116 myapp2 = Flask('appname2')117 52- pytest.raises(NoAppException, find_best_app, mod)118+ pytest.raises(NoAppException, find_best_app, script_info, Module)119 120+ class Module:121+ @staticmethod122+ def create_app(foo, bar):123+ return Flask('appname2')124 125+ pytest.raises(NoAppException, find_best_app, script_info, Module)126+127+128 def test_prepare_exec_for_file(test_apps):129 """Expect the correct path to be set and the correct module name to be returned.130 131 :func:`prepare_exec_for_file` has a side effect, where14 unmodified lines146 147 148 def test_locate_app(test_apps):149 """Test of locate_app."""77- assert locate_app("cliapp.app").name == "testapp"78- assert locate_app("cliapp.app:testapp").name == "testapp"79- assert locate_app("cliapp.multiapp:app1").name == "app1"80- pytest.raises(RuntimeError, locate_app, "cliapp.app:notanapp")150+ script_info = ScriptInfo()151+ assert locate_app(script_info, "cliapp.app").name == "testapp"152+ assert locate_app(script_info, "cliapp.app:testapp").name == "testapp"153+ assert locate_app(script_info, "cliapp.factory").name == "create_app"154+ assert locate_app(155+ script_info, "cliapp.factory").name == "create_app"156+ assert locate_app(157+ script_info, "cliapp.factory:create_app").name == "create_app"158+ assert locate_app(159+ script_info, "cliapp.factory:create_app()").name == "create_app"160+ assert locate_app(161+ script_info, "cliapp.factory:create_app2('foo', 'bar')"162+ ).name == "create_app2_foo_bar"163+ assert locate_app(164+ script_info, "cliapp.factory:create_app2('foo', 'bar', )"165+ ).name == "create_app2_foo_bar"166+ assert locate_app(167+ script_info, "cliapp.factory:create_app3('baz', 'qux')"168+ ).name == "create_app3_baz_qux"169+ assert locate_app(script_info, "cliapp.multiapp:app1").name == "app1"170+ pytest.raises(171+ NoAppException, locate_app, script_info, "notanpp.py")172+ pytest.raises(173+ NoAppException, locate_app, script_info, "cliapp/app")174+ pytest.raises(175+ RuntimeError, locate_app, script_info, "cliapp.app:notanapp")176+ pytest.raises(177+ NoAppException, locate_app,178+ script_info, "cliapp.factory:create_app2('foo')")179+ pytest.raises(180+ NoAppException, locate_app,181+ script_info, "cliapp.factory:create_app ()")182+ pytest.raises(183+ NoAppException, locate_app, script_info, "cliapp.importerrorapp")184 185 186 def test_find_default_import_path(test_apps, monkeypatch, tmpdir):187 """Test of find_default_import_path."""7 unmodified lines195 expect_rv = prepare_exec_for_file(str(tmpfile))196 assert find_default_import_path() == expect_rv197 198 199+def test_get_version(test_apps, capsys):200+ """Test of get_version."""201+ from flask import __version__ as flask_ver202+ from sys import version as py_ver203+204+ class MockCtx(object):205+ resilient_parsing = False206+ color = None207+208+ def exit(self): return209+210+ ctx = MockCtx()211+ get_version(ctx, None, "test")212+ out, err = capsys.readouterr()213+ assert flask_ver in out214+ assert py_ver in out215+216+217 def test_scriptinfo(test_apps):218 """Test of ScriptInfo."""219 obj = ScriptInfo(app_import_path="cliapp.app:testapp")220 assert obj.load_app().name == "testapp"7 unmodified lines228 assert app.name == "createapp"229 assert obj.load_app() == app230 231 111-def test_with_appcontext():232+def test_with_appcontext(runner):233 """Test of with_appcontext."""234+235 @click.command()236 @with_appcontext237 def testcmd():238 click.echo(current_app.name)239 240 obj = ScriptInfo(create_app=lambda info: Flask("testapp"))241 120- runner = CliRunner()242 result = runner.invoke(testcmd, obj=obj)243 assert result.exit_code == 0244 assert result.output == 'testapp\n'245 246 126-def test_appgroup():247+def test_appgroup(runner):248 """Test of with_appcontext."""249+250 @click.group(cls=AppGroup)251 def cli():252 pass253 10 unmodified lines264 click.echo(current_app.name)265 266 obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))267 146- runner = CliRunner()268 result = runner.invoke(cli, ['test'], obj=obj)269 assert result.exit_code == 0270 assert result.output == 'testappgroup\n'271 1 unmodified line273 assert result.exit_code == 0274 assert result.output == 'testappgroup\n'275 276 156-def test_flaskgroup():277+def test_flaskgroup(runner):278 """Test FlaskGroup."""279+280 def create_app(info):281 return Flask("flaskgroup")282 283 @click.group(cls=FlaskGroup, create_app=create_app)3 unmodified lines287 @cli.command()288 def test():289 click.echo(current_app.name)290 169- runner = CliRunner()291 result = runner.invoke(cli, ['test'])292 assert result.exit_code == 0293 assert result.output == 'flaskgroup\n'294+295+296+def test_print_exceptions(runner):297+ """Print the stacktrace if the CLI."""298+299+ def create_app(info):300+ raise Exception("oh no")301+ return Flask("flaskgroup")302+303+ @click.group(cls=FlaskGroup, create_app=create_app)304+ def cli(**params):305+ pass306+307+ result = runner.invoke(cli, ['--help'])308+ assert result.exit_code == 0309+ assert 'Exception: oh no' in result.output310+ assert 'Traceback' in result.output311+312+313+class TestRoutes:314+ @pytest.fixture315+ def invoke(self, runner):316+ def create_app(info):317+ app = Flask(__name__)318+ app.testing = True319+320+ @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])321+ def yyy_get_post(x, y):322+ pass323+324+ @app.route('/zzz_post', methods=['POST'])325+ def aaa_post():326+ pass327+328+ return app329+330+ cli = FlaskGroup(create_app=create_app)331+ return partial(runner.invoke, cli)332+333+ def expect_order(self, order, output):334+ # skip the header and match the start of each row335+ for expect, line in zip(order, output.splitlines()[2:]):336+ # do this instead of startswith for nicer pytest output337+ assert line[:len(expect)] == expect338+339+ def test_simple(self, invoke):340+ result = invoke(['routes'])341+ assert result.exit_code == 0342+ self.expect_order(343+ ['aaa_post', 'static', 'yyy_get_post'],344+ result.output345+ )346+347+ def test_sort(self, invoke):348+ default_output = invoke(['routes']).output349+ endpoint_output = invoke(['routes', '-s', 'endpoint']).output350+ assert default_output == endpoint_output351+ self.expect_order(352+ ['static', 'yyy_get_post', 'aaa_post'],353+ invoke(['routes', '-s', 'methods']).output354+ )355+ self.expect_order(356+ ['yyy_get_post', 'static', 'aaa_post'],357+ invoke(['routes', '-s', 'rule']).output358+ )359+ self.expect_order(360+ ['aaa_post', 'yyy_get_post', 'static'],361+ invoke(['routes', '-s', 'match']).output362+ )363+364+ def test_all_methods(self, invoke):365+ output = invoke(['routes']).output366+ assert 'GET, HEAD, OPTIONS, POST' not in output367+ output = invoke(['routes', '--all-methods']).output368+ 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_deprecations.py+4 added-11 removed
13 unmodified lines14 import flask15 16 17 class TestRequestDeprecation(object):18-19- def test_request_json(self, recwarn):18+ def test_request_json(self, recwarn, app, client):19 """Request.json is deprecated"""21- app = flask.Flask(__name__)22- app.testing = True20 21 @app.route('/', methods=['POST'])22 def index():23 assert flask.request.json == {'spam': 42}24 print(flask.request.json)25 return 'OK'26 30- c = app.test_client()31- c.post('/', data='{"spam": 42}', content_type='application/json')27+ client.post('/', data='{"spam": 42}', content_type='application/json')28 recwarn.pop(DeprecationWarning)29 34- def test_request_module(self, recwarn):30+ def test_request_module(self, recwarn, app, client):31 """Request.module is deprecated"""36- app = flask.Flask(__name__)37- app.testing = True32 33 @app.route('/')34 def index():35 assert flask.request.module is None36 return 'OK'37 44- c = app.test_client()45- c.get('/')38+ client.get('/')39 recwarn.pop(DeprecationWarning)modified:tests/test_ext.py+12 added-14 removed
19 unmodified lines20 from flask._compat import PY221 22 23 @pytest.fixture(autouse=True)24-def disable_extwarnings(request, recwarn):24+def disable_extwarnings(recwarn):25 from flask.exthook import ExtDeprecationWarning26 27- def inner():28- assert set(w.category for w in recwarn.list) \29- <= set([ExtDeprecationWarning])30- recwarn.clear()27+ yield28 32- request.addfinalizer(inner)29+ assert set(w.category for w in recwarn.list) \30+ <= set([ExtDeprecationWarning])31+ recwarn.clear()32 33 34 @pytest.fixture(autouse=True)36-def importhook_setup(monkeypatch, request):35+def importhook_setup(monkeypatch):36 # we clear this out for various reasons. The most important one is37 # that a real flaskext could be in there which would disable our38 # fake package. Secondly we want to make sure that the flaskext39 # import hook does not break on reloading.16 unmodified lines56 cls.__name__ == 'ExtensionImporter':57 import_hooks += 158 assert import_hooks == 159 61- def teardown():62- from flask import ext63- for key in ext.__dict__:64- assert '.' not in key60+ yield61 66- request.addfinalizer(teardown)62+ from flask import ext63+ for key in ext.__dict__:64+ assert '.' not in key65 66 67 @pytest.fixture68 def newext_simple(modules_tmpdir):107 unmodified lines176 177 def test_no_error_swallowing(flaskext_broken):178 with pytest.raises(ImportError) as excinfo:179 import flask.ext.broken182-183- assert excinfo.type is ImportError180+ # python3.6 raises a subclass of ImportError: 'ModuleNotFoundError'181+ assert issubclass(excinfo.type, ImportError)182 if PY2:183 message = 'No module named missing_module'184 else:185 message = 'No module named \'missing_module\''12 unmodified linesmodified:tests/test_helpers.py+475 added-307 removed
10 unmodified lines11 12 import pytest13 14 import os15+import uuid16 import datetime17+18 import flask19 from logging import StreamHandler20+from werkzeug.datastructures import Range21 from werkzeug.exceptions import BadRequest, NotFound22 from werkzeug.http import parse_cache_control_header, parse_options_header23 from werkzeug.http import http_date21-from flask._compat import StringIO, text_type, PY224+from flask._compat import StringIO, text_type25+from flask.helpers import get_debug_flag, make_response26 27 28 def has_encoding(name):29 try:4 unmodified lines34 return False35 36 37 class TestJSON(object):38+ def test_ignore_cached_json(self, app):39+ with app.test_request_context('/', method='POST', data='malformed',40+ content_type='application/json'):41+ assert flask.request.get_json(silent=True, cache=True) is None42+ with pytest.raises(BadRequest):43+ flask.request.get_json(silent=False, cache=False)44 35- def test_post_empty_json_adds_exception_to_response_content_in_debug(self):36- app = flask.Flask(__name__)45+ def test_post_empty_json_adds_exception_to_response_content_in_debug(self, app, client):46 app.config['DEBUG'] = True47+ app.config['TRAP_BAD_REQUEST_ERRORS'] = False48+49 @app.route('/json', methods=['POST'])50 def post_json():51 flask.request.get_json()52 return None42- c = app.test_client()43- rv = c.post('/json', data=None, content_type='application/json')53+54+ rv = client.post('/json', data=None, content_type='application/json')55 assert rv.status_code == 40056 assert b'Failed to decode JSON object' in rv.data57 47- def test_post_empty_json_wont_add_exception_to_response_if_no_debug(self):48- app = flask.Flask(__name__)58+ def test_post_empty_json_wont_add_exception_to_response_if_no_debug(self, app, client):59 app.config['DEBUG'] = False60+ app.config['TRAP_BAD_REQUEST_ERRORS'] = False61+62 @app.route('/json', methods=['POST'])63 def post_json():64 flask.request.get_json()65 return None54- c = app.test_client()55- rv = c.post('/json', data=None, content_type='application/json')66+67+ rv = client.post('/json', data=None, content_type='application/json')68 assert rv.status_code == 40069 assert b'Failed to decode JSON object' not in rv.data70 59- def test_json_bad_requests(self):60- app = flask.Flask(__name__)71+ def test_json_bad_requests(self, app, client):72+73 @app.route('/json', methods=['POST'])74 def return_json():75 return flask.jsonify(foo=text_type(flask.request.get_json()))64- c = app.test_client()65- rv = c.post('/json', data='malformed', content_type='application/json')76+77+ rv = client.post('/json', data='malformed', content_type='application/json')78 assert rv.status_code == 40079 68- def test_json_custom_mimetypes(self):69- app = flask.Flask(__name__)80+ def test_json_custom_mimetypes(self, app, client):81+82 @app.route('/json', methods=['POST'])83 def return_json():84 return flask.request.get_json()73- c = app.test_client()74- rv = c.post('/json', data='"foo"', content_type='application/x+json')85+86+ rv = client.post('/json', data='"foo"', content_type='application/x+json')87 assert rv.data == b'foo'88 77- def test_json_body_encoding(self):78- app = flask.Flask(__name__)79- app.testing = True89+ def test_json_body_encoding(self, app, client):90+91 @app.route('/')92 def index():93 return flask.request.get_json()94 84- c = app.test_client()85- resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),86- content_type='application/json; charset=iso-8859-15')95+ resp = client.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),96+ content_type='application/json; charset=iso-8859-15')97 assert resp.data == u'Hällo Wörld'.encode('utf-8')98 89- def test_json_as_unicode(self):90- app = flask.Flask(__name__)99+ @pytest.mark.parametrize('test_value,expected', [(True, '"\\u2603"'), (False, u'"\u2603"')])100+ def test_json_as_unicode(self, test_value, expected, app, app_ctx):101 92- app.config['JSON_AS_ASCII'] = True93- with app.app_context():94- rv = flask.json.dumps(u'\N{SNOWMAN}')95- assert rv == '"\\u2603"'102+ app.config['JSON_AS_ASCII'] = test_value103+ rv = flask.json.dumps(u'\N{SNOWMAN}')104+ assert rv == expected105 97- app.config['JSON_AS_ASCII'] = False98- with app.app_context():99- rv = flask.json.dumps(u'\N{SNOWMAN}')100- assert rv == u'"\u2603"'106+ def test_json_dump_to_file(self, app, app_ctx):107+ test_data = {'name': 'Flask'}108+ out = StringIO()109 110+ flask.json.dump(test_data, out)111+ out.seek(0)112+ rv = flask.json.load(out)113+ assert rv == test_data114+115+ @pytest.mark.parametrize('test_value', [0, -1, 1, 23, 3.14, 's', "longer string", True, False, None])102- def test_jsonify_basic_types(self):116+ def test_jsonify_basic_types(self, test_value, app, client):117 """Test jsonify with basic types."""104- # Should be able to use pytest parametrize on this, but I couldn't105- # figure out the correct syntax106- # https://pytest.org/latest/parametrize.html#pytest-mark-parametrize-parametrizing-test-functions107- test_data = (0, 1, 23, 3.14, 's', "longer string", True, False,)108- app = flask.Flask(__name__)109- c = app.test_client()110- for i, d in enumerate(test_data):111- url = '/jsonify_basic_types{0}'.format(i)112- app.add_url_rule(url, str(i), lambda x=d: flask.jsonify(x))113- rv = c.get(url)114- assert rv.mimetype == 'application/json'115- assert flask.json.loads(rv.data) == d118 119+ url = '/jsonify_basic_types'120+ app.add_url_rule(url, url, lambda x=test_value: flask.jsonify(x))121+ rv = client.get(url)122+ assert rv.mimetype == 'application/json'123+ assert flask.json.loads(rv.data) == test_value124+117- def test_jsonify_dicts(self):125+ def test_jsonify_dicts(self, app, client):126 """Test jsonify with dicts and kwargs unpacking."""119- d = dict(120- a=0, b=23, c=3.14, d='t', e='Hi', f=True, g=False,121- h=['test list', 10, False],122- i={'test':'dict'}123- )124- app = flask.Flask(__name__)127+ d = {'a': 0, 'b': 23, 'c': 3.14, 'd': 't',128+ 'e': 'Hi', 'f': True, 'g': False,129+ 'h': ['test list', 10, False],130+ 'i': {'test': 'dict'}}131+132 @app.route('/kw')133 def return_kwargs():134 return flask.jsonify(**d)135+136 @app.route('/dict')137 def return_dict():138 return flask.jsonify(d)131- c = app.test_client()139+140 for url in '/kw', '/dict':133- rv = c.get(url)141+ rv = client.get(url)142 assert rv.mimetype == 'application/json'143 assert flask.json.loads(rv.data) == d144 137- def test_jsonify_arrays(self):145+ def test_jsonify_arrays(self, app, client):146 """Test jsonify of lists and args unpacking."""147 l = [148 0, 42, 3.14, 't', 'hello', True, False,149 ['test list', 2, False],142- {'test':'dict'}150+ {'test': 'dict'}151 ]144- app = flask.Flask(__name__)152+153 @app.route('/args_unpack')154 def return_args_unpack():155 return flask.jsonify(*l)156+157 @app.route('/array')158 def return_array():159 return flask.jsonify(l)151- c = app.test_client()160+161 for url in '/args_unpack', '/array':153- rv = c.get(url)162+ rv = client.get(url)163 assert rv.mimetype == 'application/json'164 assert flask.json.loads(rv.data) == l165 157- def test_jsonify_date_types(self):166+ def test_jsonify_date_types(self, app, client):167 """Test jsonify with datetime.date and datetime.datetime types."""159-168 test_dates = (169 datetime.datetime(1973, 3, 11, 6, 30, 45),170 datetime.date(1975, 1, 5)171 )172 165- app = flask.Flask(__name__)166- c = app.test_client()167-173 for i, d in enumerate(test_dates):174 url = '/datetest{0}'.format(i)175 app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val))171- rv = c.get(url)176+ rv = client.get(url)177 assert rv.mimetype == 'application/json'178 assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple())179 175- def test_json_attr(self):176- app = flask.Flask(__name__)180+ def test_jsonify_uuid_types(self, app, client):181+ """Test jsonify with uuid.UUID types"""182+183+ test_uuid = uuid.UUID(bytes=b'\xDE\xAD\xBE\xEF' * 4)184+ url = '/uuid_test'185+ app.add_url_rule(url, url, lambda: flask.jsonify(x=test_uuid))186+187+ rv = client.get(url)188+189+ rv_x = flask.json.loads(rv.data)['x']190+ assert rv_x == str(test_uuid)191+ rv_uuid = uuid.UUID(rv_x)192+ assert rv_uuid == test_uuid193+194+ def test_json_attr(self, app, client):195+196 @app.route('/add', methods=['POST'])197 def add():198 json = flask.request.get_json()199 return text_type(json['a'] + json['b'])181- c = app.test_client()182- rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),183- content_type='application/json')200+201+ rv = client.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),202+ content_type='application/json')203 assert rv.data == b'3'204 186- def test_template_escaping(self):187- app = flask.Flask(__name__)205+ def test_template_escaping(self, app, req_ctx):206 render = flask.render_template_string189- with app.test_request_context():190- rv = flask.json.htmlsafe_dumps('</script>')191- assert rv == u'"\\u003c/script\\u003e"'192- assert type(rv) == text_type193- rv = render('{{ "</script>"|tojson }}')194- assert rv == '"\\u003c/script\\u003e"'195- rv = render('{{ "<\0/script>"|tojson }}')196- assert rv == '"\\u003c\\u0000/script\\u003e"'197- rv = render('{{ "<!--<script>"|tojson }}')198- assert rv == '"\\u003c!--\\u003cscript\\u003e"'199- rv = render('{{ "&"|tojson }}')200- assert rv == '"\\u0026"'201- rv = render('{{ "\'"|tojson }}')202- assert rv == '"\\u0027"'203- rv = render("<a ng-data='{{ data|tojson }}'></a>",204- data={'x': ["foo", "bar", "baz'"]})205- assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'207+ rv = flask.json.htmlsafe_dumps('</script>')208+ assert rv == u'"\\u003c/script\\u003e"'209+ assert type(rv) == text_type210+ rv = render('{{ "</script>"|tojson }}')211+ assert rv == '"\\u003c/script\\u003e"'212+ rv = render('{{ "<\0/script>"|tojson }}')213+ assert rv == '"\\u003c\\u0000/script\\u003e"'214+ rv = render('{{ "<!--<script>"|tojson }}')215+ assert rv == '"\\u003c!--\\u003cscript\\u003e"'216+ rv = render('{{ "&"|tojson }}')217+ assert rv == '"\\u0026"'218+ rv = render('{{ "\'"|tojson }}')219+ assert rv == '"\\u0027"'220+ rv = render("<a ng-data='{{ data|tojson }}'></a>",221+ data={'x': ["foo", "bar", "baz'"]})222+ assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'223 207- def test_json_customization(self):224+ def test_json_customization(self, app, client):225 class X(object):226 def __init__(self, val):227 self.val = val228+229 class MyEncoder(flask.json.JSONEncoder):230 def default(self, o):231 if isinstance(o, X):232 return '<%d>' % o.val233 return flask.json.JSONEncoder.default(self, o)234+235 class MyDecoder(flask.json.JSONDecoder):236 def __init__(self, *args, **kwargs):237 kwargs.setdefault('object_hook', self.object_hook)238 flask.json.JSONDecoder.__init__(self, *args, **kwargs)239+240 def object_hook(self, obj):241 if len(obj) == 1 and '_foo' in obj:242 return X(obj['_foo'])243 return obj224- app = flask.Flask(__name__)225- app.testing = True244+245 app.json_encoder = MyEncoder246 app.json_decoder = MyDecoder247+248 @app.route('/', methods=['POST'])249 def index():250 return flask.json.dumps(flask.request.get_json()['x'])231- c = app.test_client()232- rv = c.post('/', data=flask.json.dumps({251+252+ rv = client.post('/', data=flask.json.dumps({253 'x': {'_foo': 42}254 }), content_type='application/json')255 assert rv.data == b'"<42>"'256 257+ def test_blueprint_json_customization(self, app, client):258+ class X(object):259+ def __init__(self, val):260+ self.val = val261+262+ class MyEncoder(flask.json.JSONEncoder):263+ def default(self, o):264+ if isinstance(o, X):265+ return '<%d>' % o.val266+267+ return flask.json.JSONEncoder.default(self, o)268+269+ class MyDecoder(flask.json.JSONDecoder):270+ def __init__(self, *args, **kwargs):271+ kwargs.setdefault('object_hook', self.object_hook)272+ flask.json.JSONDecoder.__init__(self, *args, **kwargs)273+274+ def object_hook(self, obj):275+ if len(obj) == 1 and '_foo' in obj:276+ return X(obj['_foo'])277+278+ return obj279+280+ bp = flask.Blueprint('bp', __name__)281+ bp.json_encoder = MyEncoder282+ bp.json_decoder = MyDecoder283+284+ @bp.route('/bp', methods=['POST'])285+ def index():286+ return flask.json.dumps(flask.request.get_json()['x'])287+288+ app.register_blueprint(bp)289+290+ rv = client.post('/bp', data=flask.json.dumps({291+ 'x': {'_foo': 42}292+ }), content_type='application/json')293+ assert rv.data == b'"<42>"'294+237- def test_modified_url_encoding(self):295+ def test_modified_url_encoding(self, app, client):296 class ModifiedRequest(flask.Request):297 url_charset = 'euc-kr'240- app = flask.Flask(__name__)241- app.testing = True298+299 app.request_class = ModifiedRequest300 app.url_map.charset = 'euc-kr'301 302 @app.route('/')303 def index():304 return flask.request.args['foo']305 249- rv = app.test_client().get(u'/?foo=정상처리'.encode('euc-kr'))306+ rv = client.get(u'/?foo=정상처리'.encode('euc-kr'))307 assert rv.status_code == 200308 assert rv.data == u'정상처리'.encode('utf-8')309 310 if not has_encoding('euc-kr'):311 test_modified_url_encoding = None312 256- def test_json_key_sorting(self):257- app = flask.Flask(__name__)258- app.testing = True313+ def test_json_key_sorting(self, app, client):314+ app.debug = True315+316 assert app.config['JSON_SORT_KEYS'] == True317 d = dict.fromkeys(range(20), 'foo')318 319 @app.route('/')320 def index():321 return flask.jsonify(values=d)322 266- c = app.test_client()267- rv = c.get('/')323+ rv = client.get('/')324 lines = [x.strip() for x in rv.data.strip().decode('utf-8').splitlines()]325 sorted_by_str = [326 '{',327 '"values": {',51 unmodified lines379 assert lines == sorted_by_int380 except AssertionError:381 assert lines == sorted_by_str382 383+384 class TestSendfile(object):385+ def test_send_file_regular(self, app, req_ctx):386+ rv = flask.send_file('static/index.html')387+ assert rv.direct_passthrough388+ assert rv.mimetype == 'text/html'389+ with app.open_resource('static/index.html') as f:390+ rv.direct_passthrough = False391+ assert rv.data == f.read()392+ rv.close()393 329- def test_send_file_regular(self):330- app = flask.Flask(__name__)331- with app.test_request_context():332- rv = flask.send_file('static/index.html')333- assert rv.direct_passthrough334- assert rv.mimetype == 'text/html'394+ def test_send_file_xsendfile(self, app, req_ctx, catch_deprecation_warnings):395+ app.use_x_sendfile = True396+ rv = flask.send_file('static/index.html')397+ assert rv.direct_passthrough398+ assert 'x-sendfile' in rv.headers399+ assert rv.headers['x-sendfile'] == \400+ os.path.join(app.root_path, 'static/index.html')401+ assert rv.mimetype == 'text/html'402+ rv.close()403+404+ def test_send_file_last_modified(self, app, client):405+ last_modified = datetime.datetime(1999, 1, 1)406+407+ @app.route('/')408+ def index():409+ return flask.send_file(StringIO("party like it's"),410+ last_modified=last_modified,411+ mimetype='text/plain')412+413+ rv = client.get('/')414+ assert rv.last_modified == last_modified415+416+ def test_send_file_object_without_mimetype(self, app, req_ctx):417+ with pytest.raises(ValueError) as excinfo:418+ flask.send_file(StringIO("LOL"))419+ assert 'Unable to infer MIME-type' in str(excinfo)420+ assert 'no filename is available' in str(excinfo)421+422+ flask.send_file(StringIO("LOL"), attachment_filename='filename')423+424+ def test_send_file_object(self, app, req_ctx):425+ with open(os.path.join(app.root_path, 'static/index.html'), mode='rb') as f:426+ rv = flask.send_file(f, mimetype='text/html')427+ rv.direct_passthrough = False428 with app.open_resource('static/index.html') as f:336- rv.direct_passthrough = False429 assert rv.data == f.read()430+ assert rv.mimetype == 'text/html'431 rv.close()432 340- def test_send_file_xsendfile(self, catch_deprecation_warnings):341- app = flask.Flask(__name__)433 app.use_x_sendfile = True343- with app.test_request_context():344- rv = flask.send_file('static/index.html')345- assert rv.direct_passthrough346- assert 'x-sendfile' in rv.headers347- assert rv.headers['x-sendfile'] == \348- os.path.join(app.root_path, 'static/index.html')434+435+ with open(os.path.join(app.root_path, 'static/index.html')) as f:436+ rv = flask.send_file(f, mimetype='text/html')437 assert rv.mimetype == 'text/html'438+ assert 'x-sendfile' not in rv.headers439 rv.close()440 352- def test_send_file_last_modified(self):353- app = flask.Flask(__name__)354- last_modified = datetime.datetime(1999, 1, 1)441+ app.use_x_sendfile = False442+ f = StringIO('Test')443+ rv = flask.send_file(f, mimetype='application/octet-stream')444+ rv.direct_passthrough = False445+ assert rv.data == b'Test'446+ assert rv.mimetype == 'application/octet-stream'447+ rv.close()448 449+ class PyStringIO(object):450+ def __init__(self, *args, **kwargs):451+ self._io = StringIO(*args, **kwargs)452+453+ def __getattr__(self, name):454+ return getattr(self._io, name)455+456+ f = PyStringIO('Test')457+ f.name = 'test.txt'458+ rv = flask.send_file(f, attachment_filename=f.name)459+ rv.direct_passthrough = False460+ assert rv.data == b'Test'461+ assert rv.mimetype == 'text/plain'462+ rv.close()463+464+ f = StringIO('Test')465+ rv = flask.send_file(f, mimetype='text/plain')466+ rv.direct_passthrough = False467+ assert rv.data == b'Test'468+ assert rv.mimetype == 'text/plain'469+ rv.close()470+471+ app.use_x_sendfile = True472+473+ f = StringIO('Test')474+ rv = flask.send_file(f, mimetype='text/html')475+ assert 'x-sendfile' not in rv.headers476+ rv.close()477+478+ @pytest.mark.skipif(479+ not callable(getattr(Range, 'to_content_range_header', None)),480+ reason="not implement within werkzeug"481+ )482+ def test_send_file_range_request(self, app, client):483 @app.route('/')484 def index():358- return flask.send_file(StringIO("party like it's"), last_modified=last_modified)485+ return flask.send_file('static/index.html', conditional=True)486 360- c = app.test_client()361- rv = c.get('/')362- assert rv.last_modified == last_modified487+ rv = client.get('/', headers={'Range': 'bytes=4-15'})488+ assert rv.status_code == 206489+ with app.open_resource('static/index.html') as f:490+ assert rv.data == f.read()[4:16]491+ rv.close()492 364- def test_send_file_object(self):365- app = flask.Flask(__name__)493+ rv = client.get('/', headers={'Range': 'bytes=4-'})494+ assert rv.status_code == 206495+ with app.open_resource('static/index.html') as f:496+ assert rv.data == f.read()[4:]497+ rv.close()498 367- with app.test_request_context():368- with open(os.path.join(app.root_path, 'static/index.html'), mode='rb') as f:369- rv = flask.send_file(f)370- rv.direct_passthrough = False371- with app.open_resource('static/index.html') as f:372- assert rv.data == f.read()373- assert rv.mimetype == 'text/html'374- rv.close()499+ rv = client.get('/', headers={'Range': 'bytes=4-1000'})500+ assert rv.status_code == 206501+ with app.open_resource('static/index.html') as f:502+ assert rv.data == f.read()[4:]503+ rv.close()504 376- app.use_x_sendfile = True505+ rv = client.get('/', headers={'Range': 'bytes=-10'})506+ assert rv.status_code == 206507+ with app.open_resource('static/index.html') as f:508+ assert rv.data == f.read()[-10:]509+ rv.close()510 378- with app.test_request_context():379- with open(os.path.join(app.root_path, 'static/index.html')) as f:380- rv = flask.send_file(f)381- assert rv.mimetype == 'text/html'382- assert 'x-sendfile' in rv.headers383- assert rv.headers['x-sendfile'] == \384- os.path.join(app.root_path, 'static/index.html')385- rv.close()511+ rv = client.get('/', headers={'Range': 'bytes=1000-'})512+ assert rv.status_code == 416513+ rv.close()514 387- app.use_x_sendfile = False388- with app.test_request_context():389- f = StringIO('Test')390- rv = flask.send_file(f)391- rv.direct_passthrough = False392- assert rv.data == b'Test'393- assert rv.mimetype == 'application/octet-stream'394- rv.close()515+ rv = client.get('/', headers={'Range': 'bytes=-'})516+ assert rv.status_code == 416517+ rv.close()518 396- class PyStringIO(object):397- def __init__(self, *args, **kwargs):398- self._io = StringIO(*args, **kwargs)399- def __getattr__(self, name):400- return getattr(self._io, name)401- f = PyStringIO('Test')402- f.name = 'test.txt'403- rv = flask.send_file(f)404- rv.direct_passthrough = False405- assert rv.data == b'Test'406- assert rv.mimetype == 'text/plain'407- rv.close()519+ rv = client.get('/', headers={'Range': 'somethingsomething'})520+ assert rv.status_code == 416521+ rv.close()522 409- f = StringIO('Test')410- rv = flask.send_file(f, mimetype='text/plain')411- rv.direct_passthrough = False412- assert rv.data == b'Test'413- assert rv.mimetype == 'text/plain'414- rv.close()523+ last_modified = datetime.datetime.utcfromtimestamp(os.path.getmtime(524+ os.path.join(app.root_path, 'static/index.html'))).replace(525+ microsecond=0)526 416- app.use_x_sendfile = True527+ rv = client.get('/', headers={'Range': 'bytes=4-15',528+ 'If-Range': http_date(last_modified)})529+ assert rv.status_code == 206530+ rv.close()531 418- with app.test_request_context():419- f = StringIO('Test')420- rv = flask.send_file(f)421- assert 'x-sendfile' not in rv.headers422- rv.close()532+ rv = client.get('/', headers={'Range': 'bytes=4-15', 'If-Range': http_date(533+ datetime.datetime(1999, 1, 1))})534+ assert rv.status_code == 200535+ rv.close()536 424- def test_attachment(self):425- app = flask.Flask(__name__)426- with app.test_request_context():427- with open(os.path.join(app.root_path, 'static/index.html')) as f:428- rv = flask.send_file(f, as_attachment=True)429- value, options = \430- parse_options_header(rv.headers['Content-Disposition'])431- assert value == 'attachment'432- rv.close()537+ def test_attachment(self, app, req_ctx):538 434- with app.test_request_context():435- assert options['filename'] == 'index.html'436- rv = flask.send_file('static/index.html', as_attachment=True)437- value, options = parse_options_header(rv.headers['Content-Disposition'])539+ with open(os.path.join(app.root_path, 'static/index.html')) as f:540+ rv = flask.send_file(f, as_attachment=True,541+ attachment_filename='index.html')542+ value, options = \543+ parse_options_header(rv.headers['Content-Disposition'])544 assert value == 'attachment'545 assert options['filename'] == 'index.html'546+ assert 'filename*' not in rv.headers['Content-Disposition']547 rv.close()548 442- with app.test_request_context():443- rv = flask.send_file(StringIO('Test'), as_attachment=True,444- attachment_filename='index.txt',445- add_etags=False)446- assert rv.mimetype == 'text/plain'447- value, options = parse_options_header(rv.headers['Content-Disposition'])448- assert value == 'attachment'449- assert options['filename'] == 'index.txt'450- rv.close()549+ rv = flask.send_file('static/index.html', as_attachment=True)550+ value, options = parse_options_header(rv.headers['Content-Disposition'])551+ assert value == 'attachment'552+ assert options['filename'] == 'index.html'553+ rv.close()554 452- def test_static_file(self):453- app = flask.Flask(__name__)555+ rv = flask.send_file(StringIO('Test'), as_attachment=True,556+ attachment_filename='index.txt',557+ add_etags=False)558+ assert rv.mimetype == 'text/plain'559+ value, options = parse_options_header(rv.headers['Content-Disposition'])560+ assert value == 'attachment'561+ assert options['filename'] == 'index.txt'562+ rv.close()563+564+ def test_attachment_with_utf8_filename(self, app, req_ctx):565+ rv = flask.send_file('static/index.html', as_attachment=True, attachment_filename=u'Ñandú/pingüino.txt')566+ content_disposition = set(rv.headers['Content-Disposition'].split('; '))567+ assert content_disposition == set((568+ 'attachment',569+ 'filename="Nandu/pinguino.txt"',570+ "filename*=UTF-8''%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt"571+ ))572+ rv.close()573+574+ def test_static_file(self, app, req_ctx):575 # default cache timeout is 12 hours455- with app.test_request_context():456- # Test with static file handler.457- rv = app.send_static_file('index.html')458- cc = parse_cache_control_header(rv.headers['Cache-Control'])459- assert cc.max_age == 12 * 60 * 60460- rv.close()461- # Test again with direct use of send_file utility.462- rv = flask.send_file('static/index.html')463- cc = parse_cache_control_header(rv.headers['Cache-Control'])464- assert cc.max_age == 12 * 60 * 60465- rv.close()576+577+ # Test with static file handler.578+ rv = app.send_static_file('index.html')579+ cc = parse_cache_control_header(rv.headers['Cache-Control'])580+ assert cc.max_age == 12 * 60 * 60581+ rv.close()582+ # Test again with direct use of send_file utility.583+ rv = flask.send_file('static/index.html')584+ cc = parse_cache_control_header(rv.headers['Cache-Control'])585+ assert cc.max_age == 12 * 60 * 60586+ rv.close()587 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600467- with app.test_request_context():468- # Test with static file handler.469- rv = app.send_static_file('index.html')470- cc = parse_cache_control_header(rv.headers['Cache-Control'])471- assert cc.max_age == 3600472- rv.close()473- # Test again with direct use of send_file utility.474- rv = flask.send_file('static/index.html')475- cc = parse_cache_control_header(rv.headers['Cache-Control'])476- assert cc.max_age == 3600477- rv.close()588+589+ # Test with static file handler.590+ rv = app.send_static_file('index.html')591+ cc = parse_cache_control_header(rv.headers['Cache-Control'])592+ assert cc.max_age == 3600593+ rv.close()594+ # Test again with direct use of send_file utility.595+ rv = flask.send_file('static/index.html')596+ cc = parse_cache_control_header(rv.headers['Cache-Control'])597+ assert cc.max_age == 3600598+ rv.close()599+600 class StaticFileApp(flask.Flask):601 def get_send_file_max_age(self, filename):602 return 10603+604 app = StaticFileApp(__name__)605 with app.test_request_context():606 # Test with static file handler.607 rv = app.send_static_file('index.html')5 unmodified lines613 cc = parse_cache_control_header(rv.headers['Cache-Control'])614 assert cc.max_age == 10615 rv.close()616 494- def test_send_from_directory(self):495- app = flask.Flask(__name__)496- app.testing = True617+ def test_send_from_directory(self, app, req_ctx):618 app.root_path = os.path.join(os.path.dirname(__file__),619 'test_apps', 'subdomaintestmodule')499- with app.test_request_context():500- rv = flask.send_from_directory('static', 'hello.txt')501- rv.direct_passthrough = False502- assert rv.data.strip() == b'Hello Subdomain'503- rv.close()620+ rv = flask.send_from_directory('static', 'hello.txt')621+ rv.direct_passthrough = False622+ assert rv.data.strip() == b'Hello Subdomain'623+ rv.close()624 505- def test_send_from_directory_bad_request(self):506- app = flask.Flask(__name__)507- app.testing = True625+ def test_send_from_directory_bad_request(self, app, req_ctx):626 app.root_path = os.path.join(os.path.dirname(__file__),627 'test_apps', 'subdomaintestmodule')510- with app.test_request_context():511- with pytest.raises(BadRequest):512- flask.send_from_directory('static', 'bad\x00')628 514-class TestLogging(object):629+ with pytest.raises(BadRequest):630+ flask.send_from_directory('static', 'bad\x00')631 632+633+class TestLogging(object):634 def test_logger_cache(self):635 app = flask.Flask(__name__)636 logger1 = app.logger637 assert app.logger is logger1638 assert logger1.name == __name__639 app.logger_name = __name__ + '/test_logger_cache'640 assert app.logger is not logger1641 524- def test_debug_log(self, capsys):525- app = flask.Flask(__name__)642+ def test_debug_log(self, capsys, app, client):643 app.debug = True644 645 @app.route('/')646 def index():4 unmodified lines651 @app.route('/exc')652 def exc():653 1 // 0654 538- with app.test_client() as c:539- c.get('/')655+ with client:656+ client.get('/')657 out, err = capsys.readouterr()658 assert 'WARNING in test_helpers [' in err659 assert os.path.basename(__file__.rsplit('.', 1)[0] + '.py') in err660 assert 'the standard library is dead' in err661 assert 'this is a debug statement' in err662 663 with pytest.raises(ZeroDivisionError):547- c.get('/exc')664+ client.get('/exc')665 549- def test_debug_log_override(self):550- app = flask.Flask(__name__)666+ def test_debug_log_override(self, app):667 app.debug = True668 app.logger_name = 'flask_tests/test_debug_log_override'669 app.logger.level = 10670 assert app.logger.level == 10671 556- def test_exception_logging(self):672+ def test_exception_logging(self, app, client):673 out = StringIO()558- app = flask.Flask(__name__)674 app.config['LOGGER_HANDLER_POLICY'] = 'never'675 app.logger_name = 'flask_tests/test_exception_logging'676 app.logger.addHandler(StreamHandler(out))677+ app.testing = False678 679 @app.route('/')680 def index():681 1 // 0682 567- rv = app.test_client().get('/')683+ rv = client.get('/')684 assert rv.status_code == 500685 assert b'Internal Server Error' in rv.data686 687 err = out.getvalue()1 unmodified line689 assert 'Traceback (most recent call last):' in err690 assert '1 // 0' in err691 assert 'ZeroDivisionError:' in err692 577- def test_processor_exceptions(self):578- app = flask.Flask(__name__)693+ def test_processor_exceptions(self, app, client):694 app.config['LOGGER_HANDLER_POLICY'] = 'never'695+ app.testing = False696+697 @app.before_request698 def before_request():699 if trigger == 'before':700 1 // 0701+702 @app.after_request703 def after_request(response):704 if trigger == 'after':705 1 // 0706 return response707+708 @app.route('/')709 def index():710 return 'Foo'711+712 @app.errorhandler(500)713 def internal_server_error(e):714 return 'Hello Server Error', 500715+716 for trigger in 'before', 'after':596- rv = app.test_client().get('/')717+ rv = client.get('/')718 assert rv.status_code == 500719 assert rv.data == b'Hello Server Error'720 600- def test_url_for_with_anchor(self):601- app = flask.Flask(__name__)721+ def test_url_for_with_anchor(self, app, req_ctx):722+723 @app.route('/')724 def index():725 return '42'605- with app.test_request_context():606- assert flask.url_for('index', _anchor='x y') == '/#x%20y'726 608- def test_url_for_with_scheme(self):609- app = flask.Flask(__name__)727+ assert flask.url_for('index', _anchor='x y') == '/#x%20y'728+729+ def test_url_for_with_scheme(self, app, req_ctx):730+731 @app.route('/')732 def index():733 return '42'613- with app.test_request_context():614- assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'734 616- def test_url_for_with_scheme_not_external(self):617- app = flask.Flask(__name__)735+ assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'736+737+ def test_url_for_with_scheme_not_external(self, app, req_ctx):738+739 @app.route('/')740 def index():741 return '42'621- with app.test_request_context():622- pytest.raises(ValueError,623- flask.url_for,624- 'index',625- _scheme='https')742 627- def test_url_for_with_alternating_schemes(self):628- app = flask.Flask(__name__)743+ pytest.raises(ValueError,744+ flask.url_for,745+ 'index',746+ _scheme='https')747+748+ def test_url_for_with_alternating_schemes(self, app, req_ctx):749+750 @app.route('/')751 def index():752 return '42'632- with app.test_request_context():633- assert flask.url_for('index', _external=True) == 'http://localhost/'634- assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'635- assert flask.url_for('index', _external=True) == 'http://localhost/'753 754+ assert flask.url_for('index', _external=True) == 'http://localhost/'755+ assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'756+ assert flask.url_for('index', _external=True) == 'http://localhost/'757+637- def test_url_with_method(self):758+ def test_url_with_method(self, app, req_ctx):759 from flask.views import MethodView639- app = flask.Flask(__name__)760+761 class MyView(MethodView):762 def get(self, id=None):763 if id is None:764 return 'List'765 return 'Get %d' % id766+767 def post(self):768 return 'Create'769+770 myview = MyView.as_view('myview')771 app.add_url_rule('/myview/', methods=['GET'],772 view_func=myview)773 app.add_url_rule('/myview/<int:id>', methods=['GET'],774 view_func=myview)775 app.add_url_rule('/myview/create', methods=['POST'],776 view_func=myview)777 655- with app.test_request_context():656- assert flask.url_for('myview', _method='GET') == '/myview/'657- assert flask.url_for('myview', id=42, _method='GET') == '/myview/42'658- assert flask.url_for('myview', _method='POST') == '/myview/create'778+ assert flask.url_for('myview', _method='GET') == '/myview/'779+ assert flask.url_for('myview', id=42, _method='GET') == '/myview/42'780+ assert flask.url_for('myview', _method='POST') == '/myview/create'781 782 783 class TestNoImports(object):784 """Test Flasks are created without import.14 unmodified lines799 assert False, 'Flask(import_name) is importing import_name.'800 801 802 class TestStreaming(object):803+ def test_streaming_with_context(self, app, client):804 682- def test_streaming_with_context(self):683- app = flask.Flask(__name__)684- app.testing = True805 @app.route('/')806 def index():807 def generate():808 yield 'Hello '809 yield flask.request.args['name']810 yield '!'811+812 return flask.Response(flask.stream_with_context(generate()))692- c = app.test_client()693- rv = c.get('/?name=World')813+814+ rv = client.get('/?name=World')815 assert rv.data == b'Hello World!'816 696- def test_streaming_with_context_as_decorator(self):697- app = flask.Flask(__name__)698- app.testing = True817+ def test_streaming_with_context_as_decorator(self, app, client):818+819 @app.route('/')820 def index():821 @flask.stream_with_context822 def generate(hello):823 yield hello824 yield flask.request.args['name']825 yield '!'826+827 return flask.Response(generate('Hello '))707- c = app.test_client()708- rv = c.get('/?name=World')828+829+ rv = client.get('/?name=World')830 assert rv.data == b'Hello World!'831 711- def test_streaming_with_context_and_custom_close(self):712- app = flask.Flask(__name__)713- app.testing = True832+ def test_streaming_with_context_and_custom_close(self, app, client):833 called = []834+835 class Wrapper(object):836 def __init__(self, gen):837 self._gen = gen838+839 def __iter__(self):840 return self841+842 def close(self):843 called.append(42)844+845 def __next__(self):846 return next(self._gen)847+848 next = __next__849+850 @app.route('/')851 def index():852 def generate():853 yield 'Hello '854 yield flask.request.args['name']855 yield '!'856+857 return flask.Response(flask.stream_with_context(858 Wrapper(generate())))733- c = app.test_client()734- rv = c.get('/?name=World')859+860+ rv = client.get('/?name=World')861 assert rv.data == b'Hello World!'862 assert called == [42]863 864+ def test_stream_keeps_session(self, app, client):865+ @app.route('/')866+ def index():867+ flask.session['test'] = 'flask'868 739-class TestSafeJoin(object):869+ @flask.stream_with_context870+ def gen():871+ yield flask.session['test']872 873+ return flask.Response(gen())874+875+ rv = client.get('/')876+ assert rv.data == b'flask'877+878+879+class TestSafeJoin(object):880 def test_safe_join(self):881 # Valid combinations of *args and expected joined paths.882 passing = (744- (('a/b/c', ), 'a/b/c'),745- (('/', 'a/', 'b/', 'c/', ), '/a/b/c'),746- (('a', 'b', 'c', ), 'a/b/c'),747- (('/a', 'b/c', ), '/a/b/c'),748- (('a/b', 'X/../c'), 'a/b/c', ),749- (('/a/b', 'c/X/..'), '/a/b/c', ),883+ (('a/b/c',), 'a/b/c'),884+ (('/', 'a/', 'b/', 'c/'), '/a/b/c'),885+ (('a', 'b', 'c'), 'a/b/c'),886+ (('/a', 'b/c'), '/a/b/c'),887+ (('a/b', 'X/../c'), 'a/b/c'),888+ (('/a/b', 'c/X/..'), '/a/b/c'),889 # If last path is '' add a slash751- (('/a/b/c', '', ), '/a/b/c/', ),890+ (('/a/b/c', ''), '/a/b/c/'),891 # Preserve dot slash753- (('/a/b/c', './', ), '/a/b/c/.', ),754- (('a/b/c', 'X/..'), 'a/b/c/.', ),892+ (('/a/b/c', './'), '/a/b/c/.'),893+ (('a/b/c', 'X/..'), 'a/b/c/.'),894 # Base directory is always considered safe895 (('../', 'a/b/c'), '../a/b/c'),757- (('/..', ), '/..'),896+ (('/..',), '/..'),897 )898 899 for args, expected in passing:900 assert flask.safe_join(*args) == expected2 unmodified lines903 # Should raise werkzeug.exceptions.NotFound on unsafe joins.904 failing = (905 # path.isabs and ``..'' checks906 ('/a', 'b', '/c'),768- ('/a', '../b/c', ),907+ ('/a', '../b/c'),908 ('/a', '..', 'b/c'),909 # Boundaries violations after path normalization771- ('/a', 'b/../b/../../c', ),910+ ('/a', 'b/../b/../../c'),911 ('/a', 'b', 'c/../..'),773- ('/a', 'b/../../c', ),912+ ('/a', 'b/../../c'),913 )914 915 for args in failing:916 with pytest.raises(NotFound):917 print(flask.safe_join(*args))918+919+class TestHelpers(object):920+921+ @pytest.mark.parametrize('debug, expected_flag, expected_default_flag', [922+ ('', None, True),923+ ('0', False, False),924+ ('False', False, False),925+ ('No', False, False),926+ ('True', True, True)927+ ])928+ def test_get_debug_flag(self, monkeypatch, debug, expected_flag, expected_default_flag):929+ monkeypatch.setenv('FLASK_DEBUG', debug)930+ if expected_flag is None:931+ assert get_debug_flag() is None932+ else:933+ assert get_debug_flag() == expected_flag934+ assert get_debug_flag(default=True) == expected_default_flag935+936+ def test_make_response(self):937+ app = flask.Flask(__name__)938+ with app.test_request_context():939+ rv = flask.helpers.make_response()940+ assert rv.status_code == 200941+ assert rv.mimetype == 'text/html'942+943+ rv = flask.helpers.make_response('Hello')944+ assert rv.status_code == 200945+ assert rv.data == b'Hello'946+ assert rv.mimetype == 'text/html'added:tests/test_json_tag.py+65 added
1+from datetime import datetime2+from uuid import uuid43+4+import pytest5+6+from flask import Markup7+from flask.json.tag import TaggedJSONSerializer, JSONTag8+9+10+@pytest.mark.parametrize("data", (11+ {' t': (1, 2, 3)},12+ {' t__': b'a'},13+ {' di': ' di'},14+ {'x': (1, 2, 3), 'y': 4},15+ (1, 2, 3),16+ [(1, 2, 3)],17+ b'\xff',18+ Markup('<html>'),19+ uuid4(),20+ datetime.utcnow().replace(microsecond=0),21+))22+def test_dump_load_unchanged(data):23+ s = TaggedJSONSerializer()24+ assert s.loads(s.dumps(data)) == data25+26+27+def test_duplicate_tag():28+ class TagDict(JSONTag):29+ key = ' d'30+31+ s = TaggedJSONSerializer()32+ pytest.raises(KeyError, s.register, TagDict)33+ s.register(TagDict, force=True, index=0)34+ assert isinstance(s.tags[' d'], TagDict)35+ assert isinstance(s.order[0], TagDict)36+37+38+def test_custom_tag():39+ class Foo(object):40+ def __init__(self, data):41+ self.data = data42+43+ class TagFoo(JSONTag):44+ __slots__ = ()45+ key = ' f'46+47+ def check(self, value):48+ return isinstance(value, Foo)49+50+ def to_json(self, value):51+ return self.serializer.tag(value.data)52+53+ def to_python(self, value):54+ return Foo(value)55+56+ s = TaggedJSONSerializer()57+ s.register(TagFoo)58+ assert s.loads(s.dumps(Foo('bar'))).data == 'bar'59+60+61+def test_tag_interface():62+ t = JSONTag(None)63+ pytest.raises(NotImplementedError, t.check, None)64+ pytest.raises(NotImplementedError, t.to_json, None)65+ pytest.raises(NotImplementedError, t.to_python, None)modified:tests/test_regression.py+4 added-7 removed
7 unmodified lines8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12-import pytest13-14-import os12 import gc13 import sys17-import flask14 import threading15+16+import pytest17 from werkzeug.exceptions import NotFound18 19+import flask20 21 _gc_lock = threading.Lock()22 23 51 unmodified lines75 with pytest.raises(NotFound):76 safe_join('/foo', '..')77 78 80-def test_aborting():79+def test_aborting(app):80 class Foo(Exception):81 whatever = 4283- app = flask.Flask(__name__)84- app.testing = True82 83 @app.errorhandler(Foo)84 def handle_foo(e):85 return str(e.whatever)14 unmodified linesmodified:tests/test_reqctx.py+85 added-53 removed
10 unmodified lines11 12 import pytest13 14 import flask15+from flask.sessions import SessionInterface16 17 try:18 from greenlet import greenlet19 except ImportError:20 greenlet = None21 22 22-def test_teardown_on_pop():23+def test_teardown_on_pop(app):24 buffer = []24- app = flask.Flask(__name__)25+26 @app.teardown_request27 def end_of_request(exception):28 buffer.append(exception)29 2 unmodified lines32 assert buffer == []33 ctx.pop()34 assert buffer == [None]35 36+35-def test_teardown_with_previous_exception():37+def test_teardown_with_previous_exception(app):38 buffer = []37- app = flask.Flask(__name__)39+40 @app.teardown_request41 def end_of_request(exception):42 buffer.append(exception)43 5 unmodified lines49 with app.test_request_context():50 assert buffer == []51 assert buffer == [None]52 53+51-def test_teardown_with_handled_exception():54+def test_teardown_with_handled_exception(app):55 buffer = []53- app = flask.Flask(__name__)56+57 @app.teardown_request58 def end_of_request(exception):59 buffer.append(exception)60 4 unmodified lines65 except Exception:66 pass67 assert buffer == [None]68 66-def test_proper_test_request_context():67- app = flask.Flask(__name__)69+70+def test_proper_test_request_context(app):71 app.config.update(72 SERVER_NAME='localhost.localdomain:5000'73 )74 6 unmodified lines81 return None82 83 with app.test_request_context('/'):84 assert flask.url_for('index', _external=True) == \82- 'http://localhost.localdomain:5000/'85+ 'http://localhost.localdomain:5000/'86 87 with app.test_request_context('/'):88 assert flask.url_for('sub', _external=True) == \86- 'http://foo.localhost.localdomain:5000/'89+ 'http://foo.localhost.localdomain:5000/'90 91 try:92 with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}):93 pass11 unmodified lines105 app.config.update(SERVER_NAME='localhost:80')106 with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}):107 pass108 106-def test_context_binding():107- app = flask.Flask(__name__)109+110+def test_context_binding(app):111 @app.route('/')112 def index():113 return 'Hello %s!' % flask.request.args['name']114+115 @app.route('/meh')116 def meh():117 return flask.request.url118 2 unmodified lines121 with app.test_request_context('/meh'):122 assert meh() == 'http://localhost/meh'123 assert flask._request_ctx_stack.top is None124 121-def test_context_test():122- app = flask.Flask(__name__)125+126+def test_context_test(app):127 assert not flask.request128 assert not flask.has_request_context()129 ctx = app.test_request_context()130 ctx.push()2 unmodified lines133 assert flask.has_request_context()134 finally:135 ctx.pop()136 133-def test_manual_context_binding():134- app = flask.Flask(__name__)137+138+def test_manual_context_binding(app):139 @app.route('/')140 def index():141 return 'Hello %s!' % flask.request.args['name']142 3 unmodified lines146 ctx.pop()147 with pytest.raises(RuntimeError):148 index()149 150+151 @pytest.mark.skipif(greenlet is None, reason='greenlet not installed')147-def test_greenlet_context_copying():148- app = flask.Flask(__name__)149- greenlets = []152+class TestGreenletContextCopying(object):153 154+ def test_greenlet_context_copying(self, app, client):155+ greenlets = []156+157+ @app.route('/')151- @app.route('/')152- def index():153- reqctx = flask._request_ctx_stack.top.copy()154- def g():155- assert not flask.request156- assert not flask.current_app157- with reqctx:158+ def index():159+ reqctx = flask._request_ctx_stack.top.copy()160+161+ def g():162+ assert not flask.request163+ assert not flask.current_app164+ with reqctx:165+ assert flask.request166+ assert flask.current_app == app167+ assert flask.request.path == '/'168+ assert flask.request.args['foo'] == 'bar'169+ assert not flask.request170+ return 42171+172+ greenlets.append(greenlet(g))173+ return 'Hello World!'174+175+ rv = client.get('/?foo=bar')176+ assert rv.data == b'Hello World!'177+178+ result = greenlets[0].run()179+ assert result == 42180+181+ def test_greenlet_context_copying_api(self, app, client):182+ greenlets = []183+184+ @app.route('/')185+ def index():186+ reqctx = flask._request_ctx_stack.top.copy()187+188+ @flask.copy_current_request_context189+ def g():190 assert flask.request191 assert flask.current_app == app192 assert flask.request.path == '/'193 assert flask.request.args['foo'] == 'bar'162- assert not flask.request163- return 42194+ return 42164- greenlets.append(greenlet(g))165- return 'Hello World!'195 167- rv = app.test_client().get('/?foo=bar')168- assert rv.data == b'Hello World!'196+ greenlets.append(greenlet(g))197+ return 'Hello World!'198 170- result = greenlets[0].run()171- assert result == 42199+ rv = client.get('/?foo=bar')200+ assert rv.data == b'Hello World!'201 173-@pytest.mark.skipif(greenlet is None, reason='greenlet not installed')174-def test_greenlet_context_copying_api():175- app = flask.Flask(__name__)176- greenlets = []202+ result = greenlets[0].run()203+ assert result == 42204 205+206+def test_session_error_pops_context():207+ class SessionError(Exception):208+ pass209+210+ class FailingSessionInterface(SessionInterface):211+ def open_session(self, app, request):212+ raise SessionError()213+214+ class CustomFlask(flask.Flask):215+ session_interface = FailingSessionInterface()216+217+ app = CustomFlask(__name__)218+219 @app.route('/')220 def index():180- reqctx = flask._request_ctx_stack.top.copy()181- @flask.copy_current_request_context182- def g():183- assert flask.request184- assert flask.current_app == app185- assert flask.request.path == '/'186- assert flask.request.args['foo'] == 'bar'187- return 42188- greenlets.append(greenlet(g))189- return 'Hello World!'221+ # shouldn't get here222+ assert False223 191- rv = app.test_client().get('/?foo=bar')192- assert rv.data == b'Hello World!'193-194- result = greenlets[0].run()195- assert result == 42224+ response = app.test_client().get('/')225+ assert response.status_code == 500226+ assert not flask.request227+ assert not flask.current_appmodified:tests/test_signals.py+8 added-4 removed
16 unmodified lines17 blinker = None18 19 import flask20 21-21 pytestmark = pytest.mark.skipif(22 blinker is None,23 reason='Signals require the blinker library.'24 )25 27-def test_template_rendered():28- app = flask.Flask(__name__)26 27+def test_template_rendered(app, client):28 @app.route('/')29 def index():30 return flask.render_template('simple_template.html', whiskey=42)31 3 unmodified lines35 recorded.append((template, context))36 37 flask.template_rendered.connect(record, app)38 try:41- app.test_client().get('/')39+ client.get('/')40 assert len(recorded) == 141 template, context = recorded[0]42 assert template.name == 'simple_template.html'43 assert context['whiskey'] == 4244 finally:45 flask.template_rendered.disconnect(record, app)46 47+48 def test_before_render_template():49 app = flask.Flask(__name__)50 51 @app.route('/')16 unmodified lines68 assert rv.data == b'<h1>43</h1>'69 finally:70 flask.before_render_template.disconnect(record, app)71 72+73 def test_request_signals():74 app = flask.Flask(__name__)75 calls = []76 31 unmodified lines108 finally:109 flask.request_started.disconnect(before_request_signal, app)110 flask.request_finished.disconnect(after_request_signal, app)111 112+113 def test_request_exception_signal():114 app = flask.Flask(__name__)115 recorded = []116 11 unmodified lines128 assert isinstance(recorded[0], ZeroDivisionError)129 finally:130 flask.got_request_exception.disconnect(record, app)131 132+133 def test_appcontext_signals():134 app = flask.Flask(__name__)135 recorded = []136 18 unmodified lines155 finally:156 flask.appcontext_pushed.disconnect(record_push, app)157 flask.appcontext_popped.disconnect(record_pop, app)158 159+160 def test_flash_signal():161 app = flask.Flask(__name__)162 app.config['SECRET_KEY'] = 'secret'163 18 unmodified lines182 assert category == 'notice'183 finally:184 flask.message_flashed.disconnect(record, app)185 186+187 def test_appcontext_tearing_down_signal():188 app = flask.Flask(__name__)189 recorded = []190 16 unmodified linesmodified:tests/test_templating.py+128 added-86 removed
15 unmodified lines16 from jinja2 import TemplateNotFound17 import werkzeug.serving18 19 20-def test_context_processing():21- app = flask.Flask(__name__)20+def test_context_processing(app, client):21 @app.context_processor22 def context_processor():23 return {'injected_value': 42}24+25 @app.route('/')26 def index():27 return flask.render_template('context_template.html', value=23)28- rv = app.test_client().get('/')28+29+ rv = client.get('/')30 assert rv.data == b'<p>23|42'31 31-def test_original_win():32- app = flask.Flask(__name__)32+33+def test_original_win(app, client):34 @app.route('/')35 def index():36 return flask.render_template_string('{{ config }}', config=42)36- rv = app.test_client().get('/')37+38+ rv = client.get('/')39 assert rv.data == b'42'40 39-def test_request_less_rendering():40- app = flask.Flask(__name__)41+42+def test_request_less_rendering(app, app_ctx):43 app.config['WORLD_NAME'] = 'Special World'44+45 @app.context_processor46 def context_processor():47 return dict(foo=42)48 46- with app.app_context():47- rv = flask.render_template_string('Hello {{ config.WORLD_NAME }} '48- '{{ foo }}')49- assert rv == 'Hello Special World 42'49+ rv = flask.render_template_string('Hello {{ config.WORLD_NAME }} '50+ '{{ foo }}')51+ assert rv == 'Hello Special World 42'52 51-def test_standard_context():52- app = flask.Flask(__name__)53+54+def test_standard_context(app, client):55 app.secret_key = 'development key'56+57 @app.route('/')58 def index():59 flask.g.foo = 2360 flask.session['test'] = 'aha'2 unmodified lines63 {{ g.foo }}64 {{ config.DEBUG }}65 {{ session.test }}66 ''')67+64- rv = app.test_client().get('/?foo=42')68+ rv = client.get('/?foo=42')69 assert rv.data.split() == [b'42', b'23', b'False', b'aha']70 71+67-def test_escaping():72+def test_escaping(app, client):73 text = '<p>Hello World!'69- app = flask.Flask(__name__)74+75 @app.route('/')76 def index():77 return flask.render_template('escaping_template.html', text=text,78 html=flask.Markup(text))79+74- lines = app.test_client().get('/').data.splitlines()80+ lines = client.get('/').data.splitlines()81 assert lines == [82 b'<p>Hello World!',83 b'<p>Hello World!',84 b'<p>Hello World!',1 unmodified line86 b'<p>Hello World!',87 b'<p>Hello World!'88 ]89 90+84-def test_no_escaping():91+def test_no_escaping(app, client):92 text = '<p>Hello World!'86- app = flask.Flask(__name__)93+94 @app.route('/')95 def index():96 return flask.render_template('non_escaping_template.txt', text=text,97 html=flask.Markup(text))98+91- lines = app.test_client().get('/').data.splitlines()99+ lines = client.get('/').data.splitlines()100 assert lines == [101 b'<p>Hello World!',102 b'<p>Hello World!',103 b'<p>Hello World!',3 unmodified lines107 b'<p>Hello World!',108 b'<p>Hello World!'109 ]110 103-def test_escaping_without_template_filename():104- app = flask.Flask(__name__)105- with app.test_request_context():106- assert flask.render_template_string(107- '{{ foo }}', foo='<test>') == '<test>'108- assert flask.render_template('mail.txt', foo='<test>') == \109- '<test> Mail'111 111-def test_macros():112- app = flask.Flask(__name__)113- with app.test_request_context():114- macro = flask.get_template_attribute('_macro.html', 'hello')115- assert macro('World') == 'Hello World!'112+def test_escaping_without_template_filename(app, client, req_ctx):113+ assert flask.render_template_string(114+ '{{ foo }}', foo='<test>') == '<test>'115+ assert flask.render_template('mail.txt', foo='<test>') == '<test> Mail'116 117-def test_template_filter():118- app = flask.Flask(__name__)117+118+def test_macros(app, req_ctx):119+ macro = flask.get_template_attribute('_macro.html', 'hello')120+ assert macro('World') == 'Hello World!'121+122+123+def test_template_filter(app):124 @app.template_filter()125 def my_reverse(s):126 return s[::-1]127+128 assert 'my_reverse' in app.jinja_env.filters.keys()129 assert app.jinja_env.filters['my_reverse'] == my_reverse130 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'131 126-def test_add_template_filter():127- app = flask.Flask(__name__)132+133+def test_add_template_filter(app):134 def my_reverse(s):135 return s[::-1]136+137 app.add_template_filter(my_reverse)138 assert 'my_reverse' in app.jinja_env.filters.keys()139 assert app.jinja_env.filters['my_reverse'] == my_reverse140 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'141 135-def test_template_filter_with_name():136- app = flask.Flask(__name__)142+143+def test_template_filter_with_name(app):144 @app.template_filter('strrev')145 def my_reverse(s):146 return s[::-1]147+148 assert 'strrev' in app.jinja_env.filters.keys()149 assert app.jinja_env.filters['strrev'] == my_reverse150 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'151 144-def test_add_template_filter_with_name():145- app = flask.Flask(__name__)152+153+def test_add_template_filter_with_name(app):154 def my_reverse(s):155 return s[::-1]156+157 app.add_template_filter(my_reverse, 'strrev')158 assert 'strrev' in app.jinja_env.filters.keys()159 assert app.jinja_env.filters['strrev'] == my_reverse160 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'161 153-def test_template_filter_with_template():154- app = flask.Flask(__name__)162+163+def test_template_filter_with_template(app, client):164 @app.template_filter()165 def super_reverse(s):166 return s[::-1]167+168 @app.route('/')169 def index():170 return flask.render_template('template_filter.html', value='abcd')161- rv = app.test_client().get('/')171+172+ rv = client.get('/')173 assert rv.data == b'dcba'174 164-def test_add_template_filter_with_template():165- app = flask.Flask(__name__)175+176+def test_add_template_filter_with_template(app, client):177 def super_reverse(s):178 return s[::-1]179+180 app.add_template_filter(super_reverse)181+182 @app.route('/')183 def index():184 return flask.render_template('template_filter.html', value='abcd')172- rv = app.test_client().get('/')185+186+ rv = client.get('/')187 assert rv.data == b'dcba'188 175-def test_template_filter_with_name_and_template():176- app = flask.Flask(__name__)189+190+def test_template_filter_with_name_and_template(app, client):191 @app.template_filter('super_reverse')192 def my_reverse(s):193 return s[::-1]194+195 @app.route('/')196 def index():197 return flask.render_template('template_filter.html', value='abcd')183- rv = app.test_client().get('/')198+199+ rv = client.get('/')200 assert rv.data == b'dcba'201 186-def test_add_template_filter_with_name_and_template():187- app = flask.Flask(__name__)202+203+def test_add_template_filter_with_name_and_template(app, client):204 def my_reverse(s):205 return s[::-1]206+207 app.add_template_filter(my_reverse, 'super_reverse')208+209 @app.route('/')210 def index():211 return flask.render_template('template_filter.html', value='abcd')194- rv = app.test_client().get('/')212+213+ rv = client.get('/')214 assert rv.data == b'dcba'215 197-def test_template_test():198- app = flask.Flask(__name__)216+217+def test_template_test(app):218 @app.template_test()219 def boolean(value):220 return isinstance(value, bool)221+222 assert 'boolean' in app.jinja_env.tests.keys()223 assert app.jinja_env.tests['boolean'] == boolean224 assert app.jinja_env.tests['boolean'](False)225 206-def test_add_template_test():207- app = flask.Flask(__name__)226+227+def test_add_template_test(app):228 def boolean(value):229 return isinstance(value, bool)230+231 app.add_template_test(boolean)232 assert 'boolean' in app.jinja_env.tests.keys()233 assert app.jinja_env.tests['boolean'] == boolean234 assert app.jinja_env.tests['boolean'](False)235 215-def test_template_test_with_name():216- app = flask.Flask(__name__)236+237+def test_template_test_with_name(app):238 @app.template_test('boolean')239 def is_boolean(value):240 return isinstance(value, bool)241+242 assert 'boolean' in app.jinja_env.tests.keys()243 assert app.jinja_env.tests['boolean'] == is_boolean244 assert app.jinja_env.tests['boolean'](False)245 224-def test_add_template_test_with_name():225- app = flask.Flask(__name__)246+247+def test_add_template_test_with_name(app):248 def is_boolean(value):249 return isinstance(value, bool)250+251 app.add_template_test(is_boolean, 'boolean')252 assert 'boolean' in app.jinja_env.tests.keys()253 assert app.jinja_env.tests['boolean'] == is_boolean254 assert app.jinja_env.tests['boolean'](False)255 233-def test_template_test_with_template():234- app = flask.Flask(__name__)256+257+def test_template_test_with_template(app, client):258 @app.template_test()259 def boolean(value):260 return isinstance(value, bool)261+262 @app.route('/')263 def index():264 return flask.render_template('template_test.html', value=False)241- rv = app.test_client().get('/')265+266+ rv = client.get('/')267 assert b'Success!' in rv.data268 244-def test_add_template_test_with_template():245- app = flask.Flask(__name__)269+270+def test_add_template_test_with_template(app, client):271 def boolean(value):272 return isinstance(value, bool)273+274 app.add_template_test(boolean)275+276 @app.route('/')277 def index():278 return flask.render_template('template_test.html', value=False)252- rv = app.test_client().get('/')279+280+ rv = client.get('/')281 assert b'Success!' in rv.data282 255-def test_template_test_with_name_and_template():256- app = flask.Flask(__name__)283+284+def test_template_test_with_name_and_template(app, client):285 @app.template_test('boolean')286 def is_boolean(value):287 return isinstance(value, bool)288+289 @app.route('/')290 def index():291 return flask.render_template('template_test.html', value=False)263- rv = app.test_client().get('/')292+293+ rv = client.get('/')294 assert b'Success!' in rv.data295 266-def test_add_template_test_with_name_and_template():267- app = flask.Flask(__name__)296+297+def test_add_template_test_with_name_and_template(app, client):298 def is_boolean(value):299 return isinstance(value, bool)300+301 app.add_template_test(is_boolean, 'boolean')302+303 @app.route('/')304 def index():305 return flask.render_template('template_test.html', value=False)274- rv = app.test_client().get('/')306+307+ rv = client.get('/')308 assert b'Success!' in rv.data309 277-def test_add_template_global():278- app = flask.Flask(__name__)310+311+def test_add_template_global(app, app_ctx):312 @app.template_global()313 def get_stuff():314 return 42315+316 assert 'get_stuff' in app.jinja_env.globals.keys()317 assert app.jinja_env.globals['get_stuff'] == get_stuff318 assert app.jinja_env.globals['get_stuff'](), 42285- with app.app_context():286- rv = flask.render_template_string('{{ get_stuff() }}')287- assert rv == '42'319 320+ rv = flask.render_template_string('{{ get_stuff() }}')321+ assert rv == '42'322+323+289-def test_custom_template_loader():324+def test_custom_template_loader(client):325 class MyFlask(flask.Flask):326 def create_global_jinja_loader(self):327 from jinja2 import DictLoader328 return DictLoader({'index.html': 'Hello Custom World!'})329+330 app = MyFlask(__name__)331+332 @app.route('/')333 def index():334 return flask.render_template('index.html')335+336 c = app.test_client()337 rv = c.get('/')338 assert rv.data == b'Hello Custom World!'339 302-def test_iterable_loader():303- app = flask.Flask(__name__)340+341+def test_iterable_loader(app, client):342 @app.context_processor343 def context_processor():344 return {'whiskey': 'Jameson'}345+346 @app.route('/')347 def index():348 return flask.render_template(349 ['no_template.xml', # should skip this one311- 'simple_template.html', # should render this312- 'context_template.html'],350+ 'simple_template.html', # should render this351+ 'context_template.html'],352 value=23)353 315- rv = app.test_client().get('/')354+ rv = client.get('/')355 assert rv.data == b'<h1>Jameson</h1>'356 357+318-def test_templates_auto_reload():358+def test_templates_auto_reload(app):359 # debug is False, config option is None320- app = flask.Flask(__name__)360 assert app.debug is False361 assert app.config['TEMPLATES_AUTO_RELOAD'] is None362 assert app.jinja_env.auto_reload is False363 # debug is False, config option is False35 unmodified lines399 assert app.jinja_env.auto_reload is False400 app.run(debug=True)401 assert app.jinja_env.auto_reload is True402 403+404 def test_template_loader_debugging(test_apps):405 from blueprintapp import app406 407 called = []408+409 class _TestHandler(logging.Handler):410 def handle(x, record):411 called.append(True)412 text = str(record.msg)23 unmodified lines436 app.config['EXPLAIN_TEMPLATE_LOADING'] = old_load_setting437 438 assert len(called) == 1439 440+441 def test_custom_jinja_env():442 class CustomEnvironment(flask.templating.Environment):443 pass444 5 unmodified linesmodified:tests/test_testing.py+149 added-68 removed
9 unmodified lines10 """11 import pytest12 13 import flask14+import werkzeug15 16 from flask._compat import text_type17+from flask.json import jsonify18 19 18-def test_environ_defaults_from_config():19- app = flask.Flask(__name__)20- app.testing = True20+def test_environ_defaults_from_config(app, client):21 app.config['SERVER_NAME'] = 'example.com:1234'22 app.config['APPLICATION_ROOT'] = '/foo'23+24 @app.route('/')25 def index():26 return flask.request.url27 28 ctx = app.test_request_context()29 assert ctx.request.url == 'http://example.com:1234/foo/'29- with app.test_client() as c:30- rv = c.get('/')31- assert rv.data == b'http://example.com:1234/foo/'30 33-def test_environ_defaults():34- app = flask.Flask(__name__)35- app.testing = True31+ rv = client.get('/')32+ assert rv.data == b'http://example.com:1234/foo/'33+34+35+def test_environ_defaults(app, client, app_ctx, req_ctx):36 @app.route('/')37 def index():38 return flask.request.url39 40 ctx = app.test_request_context()41 assert ctx.request.url == 'http://localhost/'42- with app.test_client() as c:43- rv = c.get('/')42+ with client:43+ rv = client.get('/')44 assert rv.data == b'http://localhost/'45 46-def test_redirect_keep_session():47- app = flask.Flask(__name__)46+47+def test_environ_base_default(app, client, app_ctx):48+ @app.route('/')49+ def index():50+ flask.g.user_agent = flask.request.headers["User-Agent"]51+ return flask.request.remote_addr52+53+ rv = client.get('/')54+ assert rv.data == b'127.0.0.1'55+ assert flask.g.user_agent == 'werkzeug/' + werkzeug.__version__56+57+58+def test_environ_base_modified(app, client, app_ctx):59+ @app.route('/')60+ def index():61+ flask.g.user_agent = flask.request.headers["User-Agent"]62+ return flask.request.remote_addr63+64+ client.environ_base['REMOTE_ADDR'] = '0.0.0.0'65+ client.environ_base['HTTP_USER_AGENT'] = 'Foo'66+ rv = client.get('/')67+ assert rv.data == b'0.0.0.0'68+ assert flask.g.user_agent == 'Foo'69+70+ client.environ_base['REMOTE_ADDR'] = '0.0.0.1'71+ client.environ_base['HTTP_USER_AGENT'] = 'Bar'72+ rv = client.get('/')73+ assert rv.data == b'0.0.0.1'74+ assert flask.g.user_agent == 'Bar'75+76+77+def test_specify_url_scheme(app, client):78+ @app.route('/')79+ def index():80+ return flask.request.url81+82+ ctx = app.test_request_context(url_scheme='https')83+ assert ctx.request.url == 'https://localhost/'84+85+ rv = client.get('/', url_scheme='https')86+ assert rv.data == b'https://localhost/'87+88+89+def test_blueprint_with_subdomain(app, client):90+ app.config['SERVER_NAME'] = 'example.com:1234'91+ app.config['APPLICATION_ROOT'] = '/foo'92+93+ bp = flask.Blueprint('company', __name__, subdomain='xxx')94+95+ @bp.route('/')96+ def index():97+ return flask.request.url98+99+ app.register_blueprint(bp)100+101+ ctx = app.test_request_context('/', subdomain='xxx')102+ assert ctx.request.url == 'http://xxx.example.com:1234/foo/'103+ assert ctx.request.blueprint == bp.name104+105+ rv = client.get('/', subdomain='xxx')106+ assert rv.data == b'http://xxx.example.com:1234/foo/'107+108+109+def test_redirect_keep_session(app, client, app_ctx):110 app.secret_key = 'testing'111 112 @app.route('/', methods=['GET', 'POST'])113 def index():5 unmodified lines119 @app.route('/getsession')120 def get_session():121 return flask.session.get('data', '<missing>')122 61- with app.test_client() as c:62- rv = c.get('/getsession')123+ with client:124+ rv = client.get('/getsession')125 assert rv.data == b'<missing>'126 65- rv = c.get('/')127+ rv = client.get('/')128 assert rv.data == b'index'129 assert flask.session.get('data') == 'foo'68- rv = c.post('/', data={}, follow_redirects=True)130+ rv = client.post('/', data={}, follow_redirects=True)131 assert rv.data == b'foo'132 133 # This support requires a new Werkzeug version72- if not hasattr(c, 'redirect_client'):134+ if not hasattr(client, 'redirect_client'):135 assert flask.session.get('data') == 'foo'136 75- rv = c.get('/getsession')137+ rv = client.get('/getsession')138 assert rv.data == b'foo'139 78-def test_session_transactions():79- app = flask.Flask(__name__)80- app.testing = True140+141+def test_session_transactions(app, client):142 app.secret_key = 'testing'143 144 @app.route('/')145 def index():146 return text_type(flask.session['foo'])147 87- with app.test_client() as c:88- with c.session_transaction() as sess:148+ with client:149+ with client.session_transaction() as sess:150 assert len(sess) == 0151 sess['foo'] = [42]152 assert len(sess) == 192- rv = c.get('/')153+ rv = client.get('/')154 assert rv.data == b'[42]'94- with c.session_transaction() as sess:155+ with client.session_transaction() as sess:156 assert len(sess) == 1157 assert sess['foo'] == [42]158 159+160 def test_session_transactions_no_null_sessions():161 app = flask.Flask(__name__)162 app.testing = True163 2 unmodified lines166 with c.session_transaction() as sess:167 pass168 assert 'Session backend did not open a session' in str(e.value)169 108-def test_session_transactions_keep_context():109- app = flask.Flask(__name__)110- app.testing = True170+171+def test_session_transactions_keep_context(app, client, req_ctx):172 app.secret_key = 'testing'173 113- with app.test_client() as c:114- rv = c.get('/')115- req = flask.request._get_current_object()116- assert req is not None117- with c.session_transaction():118- assert req is flask.request._get_current_object()174+ rv = client.get('/')175+ req = flask.request._get_current_object()176+ assert req is not None177+ with client.session_transaction():178+ assert req is flask.request._get_current_object()179 120-def test_session_transaction_needs_cookies():121- app = flask.Flask(__name__)122- app.testing = True180+181+def test_session_transaction_needs_cookies(app):182 c = app.test_client(use_cookies=False)183 with pytest.raises(RuntimeError) as e:184 with c.session_transaction() as s:185 pass186 assert 'cookies' in str(e.value)187 129-def test_test_client_context_binding():130- app = flask.Flask(__name__)188+189+def test_test_client_context_binding(app, client):190 app.config['LOGGER_HANDLER_POLICY'] = 'never'191+ app.testing = False192+193 @app.route('/')194 def index():195 flask.g.value = 42196 return 'Hello World!'1 unmodified line198 @app.route('/other')199 def other():200 1 // 0201 141- with app.test_client() as c:142- resp = c.get('/')202+ with client:203+ resp = client.get('/')204 assert flask.g.value == 42205 assert resp.data == b'Hello World!'206 assert resp.status_code == 200207 147- resp = c.get('/other')208+ resp = client.get('/other')209 assert not hasattr(flask.g, 'value')210 assert b'Internal Server Error' in resp.data211 assert resp.status_code == 500212 flask.g.value = 234 unmodified lines217 pass218 else:219 raise AssertionError('some kind of exception expected')220 160-def test_reuse_client():161- app = flask.Flask(__name__)162- c = app.test_client()221 222+def test_reuse_client(client):223+ c = client224+225 with c:165- assert c.get('/').status_code == 404226+ assert client.get('/').status_code == 404227 228 with c:168- assert c.get('/').status_code == 404229+ assert client.get('/').status_code == 404230 170-def test_test_client_calls_teardown_handlers():171- app = flask.Flask(__name__)231+232+def test_test_client_calls_teardown_handlers(app, client):233 called = []234+235 @app.teardown_request236 def remember(error):237 called.append(error)238 177- with app.test_client() as c:239+ with client:240 assert called == []179- c.get('/')241+ client.get('/')242 assert called == []243 assert called == [None]244 245 del called[:]184- with app.test_client() as c:246+ with client:247 assert called == []186- c.get('/')248+ client.get('/')249 assert called == []188- c.get('/')250+ client.get('/')251 assert called == [None]252 assert called == [None, None]253 192-def test_full_url_request():193- app = flask.Flask(__name__)194- app.testing = True254 255+def test_full_url_request(app, client):256 @app.route('/action', methods=['POST'])257 def action():258 return 'x'259 200- with app.test_client() as c:201- rv = c.post('http://domain.com/action?vodka=42', data={'gin': 43})260+ with client:261+ rv = client.post('http://domain.com/action?vodka=42', data={'gin': 43})262 assert rv.status_code == 200263 assert 'gin' in flask.request.form264 assert 'vodka' in flask.request.args265 206-def test_subdomain():207- app = flask.Flask(__name__)266+267+def test_json_request_and_response(app, client):268+ @app.route('/echo', methods=['POST'])269+ def echo():270+ return jsonify(flask.request.get_json())271+272+ with client:273+ json_data = {'drink': {'gin': 1, 'tonic': True}, 'price': 10}274+ rv = client.post('/echo', json=json_data)275+276+ # Request should be in JSON277+ assert flask.request.is_json278+ assert flask.request.get_json() == json_data279+280+ # Response should be in JSON281+ assert rv.status_code == 200282+ assert rv.is_json283+ assert rv.get_json() == json_data284+285+286+def test_subdomain(app, client):287 app.config['SERVER_NAME'] = 'example.com'288+289 @app.route('/', subdomain='<company_id>')290 def view(company_id):291 return company_id292 293 with app.test_request_context():294 url = flask.url_for('view', company_id='xxx')295 216- with app.test_client() as c:217- response = c.get(url)296+ with client:297+ response = client.get(url)298 299 assert 200 == response.status_code300 assert b'xxx' == response.data301 222-def test_nosubdomain():223- app = flask.Flask(__name__)302+303+def test_nosubdomain(app, client):304 app.config['SERVER_NAME'] = 'example.com'305+306 @app.route('/<company_id>')307 def view(company_id):308 return company_id309 310 with app.test_request_context():311 url = flask.url_for('view', company_id='xxx')312 232- with app.test_client() as c:233- response = c.get(url)313+ with client:314+ response = client.get(url)315 316 assert 200 == response.status_code317 assert b'xxx' == response.datamodified:tests/test_user_error_handler.py+63 added-16 removed
1 # -*- coding: utf-8 -*-2-from werkzeug.exceptions import Forbidden, InternalServerError2+from werkzeug.exceptions import (3+ Forbidden,4+ InternalServerError,5+ HTTPException,6+ NotFound7+ )8 import flask9 10 6-def test_error_handler_no_match():7- app = flask.Flask(__name__)11+def test_error_handler_no_match(app, client):12 13 class CustomException(Exception):14 pass15 13 unmodified lines29 @app.route('/keyerror')30 def key_error():31 raise KeyError()32 29- c = app.test_client()33+ app.testing = False34+ assert client.get('/custom').data == b'custom'35+ assert client.get('/keyerror').data == b'KeyError'36 31- assert c.get('/custom').data == b'custom'32- assert c.get('/keyerror').data == b'KeyError'37 34-35-def test_error_handler_subclass():38+def test_error_handler_subclass(app):36- app = flask.Flask(__name__)37-39 class ParentException(Exception):40 pass41 42 class ChildExceptionUnregistered(ParentException):30 unmodified lines73 assert c.get('/child-unregistered').data == b'parent'74 assert c.get('/child-registered').data == b'child-registered'75 76 76-def test_error_handler_http_subclass():77- app = flask.Flask(__name__)78-77+def test_error_handler_http_subclass(app):78 class ForbiddenSubclassRegistered(Forbidden):79 pass80 81 class ForbiddenSubclassUnregistered(Forbidden):27 unmodified lines109 assert c.get('/forbidden-unregistered').data == b'forbidden'110 assert c.get('/forbidden-registered').data == b'forbidden-registered'111 112 114-def test_error_handler_blueprint():113+def test_error_handler_blueprint(app):114 bp = flask.Blueprint('bp', __name__)115 116 @bp.errorhandler(500)117 def bp_exception_handler(e):2 unmodified lines120 @bp.route('/error')121 def bp_test():122 raise InternalServerError()123 125- app = flask.Flask(__name__)126-124 @app.errorhandler(500)125 def app_exception_handler(e):126 return 'app-error'127 6 unmodified lines134 c = app.test_client()135 136 assert c.get('/error').data == b'app-error'137 assert c.get('/bp/error').data == b'bp-error'138+139+140+def test_default_error_handler():141+ bp = flask.Blueprint('bp', __name__)142+143+ @bp.errorhandler(HTTPException)144+ def bp_exception_handler(e):145+ assert isinstance(e, HTTPException)146+ assert isinstance(e, NotFound)147+ return 'bp-default'148+149+ @bp.errorhandler(Forbidden)150+ def bp_exception_handler(e):151+ assert isinstance(e, Forbidden)152+ return 'bp-forbidden'153+154+ @bp.route('/undefined')155+ def bp_registered_test():156+ raise NotFound()157+158+ @bp.route('/forbidden')159+ def bp_forbidden_test():160+ raise Forbidden()161+162+ app = flask.Flask(__name__)163+164+ @app.errorhandler(HTTPException)165+ def catchall_errorhandler(e):166+ assert isinstance(e, HTTPException)167+ assert isinstance(e, NotFound)168+ return 'default'169+170+ @app.errorhandler(Forbidden)171+ def catchall_errorhandler(e):172+ assert isinstance(e, Forbidden)173+ return 'forbidden'174+175+ @app.route('/forbidden')176+ def forbidden():177+ raise Forbidden()178+179+ app.register_blueprint(bp, url_prefix='/bp')180+181+ c = app.test_client()182+ assert c.get('/bp/undefined').data == b'bp-default'183+ assert c.get('/bp/forbidden').data == b'bp-forbidden'184+ assert c.get('/undefined').data == b'default'185+ assert c.get('/forbidden').data == b'forbidden'186+187+modified:tests/test_views.py+102 added-25 removed
14 unmodified lines15 import flask.views16 17 from werkzeug.http import parse_set_header18 19+20 def common_test(app):21 c = app.test_client()22 23 assert c.get('/').data == b'GET'1 unmodified line25 assert c.put('/').status_code == 40526 meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])27 assert sorted(meths) == ['GET', 'HEAD', 'OPTIONS', 'POST']28 28-def test_basic_view():29- app = flask.Flask(__name__)29 30+def test_basic_view(app):31 class Index(flask.views.View):32 methods = ['GET', 'POST']33+34 def dispatch_request(self):35 return flask.request.method36 37 app.add_url_rule('/', view_func=Index.as_view('index'))38 common_test(app)39 39-def test_method_based_view():40- app = flask.Flask(__name__)40 41+def test_method_based_view(app):42 class Index(flask.views.MethodView):43 def get(self):44 return 'GET'45+46 def post(self):47 return 'POST'48 49 app.add_url_rule('/', view_func=Index.as_view('index'))50 51 common_test(app)52 52-def test_view_patching():53- app = flask.Flask(__name__)53 54+def test_view_patching(app):55 class Index(flask.views.MethodView):56 def get(self):57 1 // 058+59 def post(self):60 1 // 061 62 class Other(Index):63 def get(self):64 return 'GET'65+66 def post(self):67 return 'POST'68 69 view = Index.as_view('index')70 view.view_class = Other71 app.add_url_rule('/', view_func=view)72 common_test(app)73 72-def test_view_inheritance():73- app = flask.Flask(__name__)74 75+def test_view_inheritance(app, client):76 class Index(flask.views.MethodView):77 def get(self):78 return 'GET'79+80 def post(self):81 return 'POST'82 83 class BetterIndex(Index):84 def delete(self):85 return 'DELETE'86 87 app.add_url_rule('/', view_func=BetterIndex.as_view('index'))86- c = app.test_client()88 88- meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])89+ meths = parse_set_header(client.open('/', method='OPTIONS').headers['Allow'])90 assert sorted(meths) == ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST']91 91-def test_view_decorators():92- app = flask.Flask(__name__)92 93+def test_view_decorators(app, client):94 def add_x_parachute(f):95 def new_function(*args, **kwargs):96 resp = flask.make_response(f(*args, **kwargs))97 resp.headers['X-Parachute'] = 'awesome'98 return resp99+100 return new_function101 102 class Index(flask.views.View):103 decorators = [add_x_parachute]104+105 def dispatch_request(self):106 return 'Awesome'107 108 app.add_url_rule('/', view_func=Index.as_view('index'))107- c = app.test_client()108- rv = c.get('/')109+ rv = client.get('/')110 assert rv.headers['X-Parachute'] == 'awesome'111 assert rv.data == b'Awesome'112 112-def test_implicit_head():113+114+def test_view_provide_automatic_options_attr():115 app = flask.Flask(__name__)116 117+ class Index1(flask.views.View):118+ provide_automatic_options = False119+120+ def dispatch_request(self):121+ return 'Hello World!'122+123+ app.add_url_rule('/', view_func=Index1.as_view('index'))124+ c = app.test_client()125+ rv = c.open('/', method='OPTIONS')126+ assert rv.status_code == 405127+128+ app = flask.Flask(__name__)129+130+ class Index2(flask.views.View):131+ methods = ['OPTIONS']132+ provide_automatic_options = True133+134+ def dispatch_request(self):135+ return 'Hello World!'136+137+ app.add_url_rule('/', view_func=Index2.as_view('index'))138+ c = app.test_client()139+ rv = c.open('/', method='OPTIONS')140+ assert sorted(rv.allow) == ['OPTIONS']141+142+ app = flask.Flask(__name__)143+144+ class Index3(flask.views.View):145+ def dispatch_request(self):146+ return 'Hello World!'147+148+ app.add_url_rule('/', view_func=Index3.as_view('index'))149+ c = app.test_client()150+ rv = c.open('/', method='OPTIONS')151+ assert 'OPTIONS' in rv.allow152+153+154+def test_implicit_head(app, client):155 class Index(flask.views.MethodView):156 def get(self):157 return flask.Response('Blub', headers={158 'X-Method': flask.request.method159 })160 161 app.add_url_rule('/', view_func=Index.as_view('index'))122- c = app.test_client()123- rv = c.get('/')162+ rv = client.get('/')163 assert rv.data == b'Blub'164 assert rv.headers['X-Method'] == 'GET'126- rv = c.head('/')165+ rv = client.head('/')166 assert rv.data == b''167 assert rv.headers['X-Method'] == 'HEAD'168 130-def test_explicit_head():131- app = flask.Flask(__name__)169 170+def test_explicit_head(app, client):171 class Index(flask.views.MethodView):172 def get(self):173 return 'GET'174+175 def head(self):176 return flask.Response('', headers={'X-Method': 'HEAD'})177 178 app.add_url_rule('/', view_func=Index.as_view('index'))140- c = app.test_client()141- rv = c.get('/')179+ rv = client.get('/')180 assert rv.data == b'GET'143- rv = c.head('/')181+ rv = client.head('/')182 assert rv.data == b''183 assert rv.headers['X-Method'] == 'HEAD'184 147-def test_endpoint_override():148- app = flask.Flask(__name__)185+186+def test_endpoint_override(app):187 app.debug = True188 189 class Index(flask.views.View):190 methods = ['GET', 'POST']191+192 def dispatch_request(self):193 return flask.request.method194 195 app.add_url_rule('/', view_func=Index.as_view('index'))2 unmodified lines198 app.add_url_rule('/', view_func=Index.as_view('index'))199 200 # But these tests should still pass. We just log a warning.201 common_test(app)202+203+204+def test_multiple_inheritance(app, client):205+ class GetView(flask.views.MethodView):206+ def get(self):207+ return 'GET'208+209+ class DeleteView(flask.views.MethodView):210+ def delete(self):211+ return 'DELETE'212+213+ class GetDeleteView(GetView, DeleteView):214+ pass215+216+ app.add_url_rule('/', view_func=GetDeleteView.as_view('index'))217+218+ assert client.get('/').data == b'GET'219+ assert client.delete('/').data == b'DELETE'220+ assert sorted(GetDeleteView.methods) == ['DELETE', 'GET']221+222+223+def test_remove_method_from_parent(app, client):224+ class GetView(flask.views.MethodView):225+ def get(self):226+ return 'GET'227+228+ class OtherView(flask.views.MethodView):229+ def post(self):230+ return 'POST'231+232+ class View(GetView, OtherView):233+ methods = ['GET']234+235+ app.add_url_rule('/', view_func=View.as_view('index'))236+237+ assert client.get('/').data == b'GET'238+ assert client.post('/').status_code == 405239+ assert sorted(View.methods) == ['GET']added:.coveragerc+11 added
1+[run]2+branch = True3+source =4+ flask5+ tests6+7+[paths]8+source =9+ flask10+ .tox/*/lib/python*/site-packages/flask11+ .tox/pypy/site-packages/flaskadded:.gitattributes+1 added
1+CHANGES merge=unionmodified:.gitignore+6 added
9 unmodified lines10 _mailinglist11 .tox12 .cache/13 .idea/14+15+# Coverage reports16+htmlcov17+.coverage18+.coverage.*19+*,coverdeleted:.gitmodules-3 removed
1-[submodule "docs/_themes"]2- path = docs/_themes3- url = https://github.com/mitsuhiko/flask-sphinx-themes.gitmodified:.travis.yml+25 added-36 removed
1 sudo: false2 language: python3 4-python:5- - "2.6"6- - "2.7"7- - "pypy"8- - "3.3"9- - "3.4"10- - "3.5"11-12-env:13- - REQUIREMENTS=lowest14- - REQUIREMENTS=lowest-simplejson15- - REQUIREMENTS=release16- - REQUIREMENTS=release-simplejson17- - REQUIREMENTS=devel18- - REQUIREMENTS=devel-simplejson19-4 matrix:21- exclude:22- # Python 3 support currently does not work with lowest requirements23- - python: "3.3"24- env: REQUIREMENTS=lowest25- - python: "3.3"26- env: REQUIREMENTS=lowest-simplejson27- - python: "3.4"28- env: REQUIREMENTS=lowest29- - python: "3.4"30- env: REQUIREMENTS=lowest-simplejson31- - python: "3.5"32- env: REQUIREMENTS=lowest33- - python: "3.5"34- env: REQUIREMENTS=lowest-simplejson5+ include:6+ - python: 3.67+ env: TOXENV=py,codecov8+ - python: 3.59+ env: TOXENV=py,codecov10+ - python: 3.411+ env: TOXENV=py,codecov12+ - python: 3.313+ env: TOXENV=py,codecov14+ - python: 2.715+ env: TOXENV=py,codecov16+ - python: 2.617+ env: TOXENV=py,codecov18+ - python: pypy19+ env: TOXENV=py,codecov20+ - python: nightly21+ env: TOXENV=py22+ - python: 3.623+ env: TOXENV=docs-html24+ - python: 3.625+ env: TOXENV=py-simplejson,codecov26 36-27 install:38- - pip install tox28+ - pip install tox29 30 script:41- - tox -e py-$REQUIREMENTS31+ - tox32 43-branches:44- except:45- - website33+cache:34+ - pip35 36 notifications:37 email: false38 irc:6 unmodified linesmodified:AUTHORS+2 added
7 unmodified lines8 9 Patches and Suggestions10 ```````````````````````11 12+- Adam Byrtek13 - Adam Zapletal14 - Ali Afshar15 - Chris Edgemon16 - Chris Grindstaff4 unmodified lines21 - Edmond Burnett22 - Florent Xicluna23 - Georg Brandl24 - Jeff Widman @jeffwidman25+- Joshua Bronson @jab26 - Justin Quick27 - Kenneth Reitz28 - Keyan Pishdadian29 - Marian Sigler10 unmodified linesmodified:CHANGES+139 added-3 removed
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+- Minimum Werkzeug version bumped to 0.9, but please use the latest version.12+- Minimum Click version bumped to 4, but please use the latest version.13+- Make ``app.run()`` into a noop if a Flask application is run from the14+ development server on the command line. This avoids some behavior that15+ was confusing to debug for newcomers.16+- Change default configuration ``JSONIFY_PRETTYPRINT_REGULAR=False``.17+ ``jsonify()`` method returns compressed response by default, and pretty18+ response in debug mode. (`#2193`_)19+- Change ``Flask.__init__`` to accept two new keyword arguments,20+ ``host_matching`` and ``static_host``. This enables ``host_matching`` to be21+ set properly by the time the constructor adds the static route, and enables22+ the static route to be properly associated with the required host.23+ (``#1559``)24+- ``send_file`` supports Unicode in ``attachment_filename``. (`#2223`_)25+- Pass ``_scheme`` argument from ``url_for`` to ``handle_build_error``.26+ (`#2017`_)27+- Add support for ``provide_automatic_options`` in ``add_url_rule`` to disable28+ adding OPTIONS method when the ``view_func`` argument is not a class.29+ (`#1489`_).30+- ``MethodView`` can inherit method handlers from base classes. (`#1936`_)31+- Errors caused while opening the session at the beginning of the request are32+ handled by the app's error handlers. (`#2254`_)33+- Blueprints gained ``json_encoder`` and ``json_decoder`` attributes to34+ override the app's encoder and decoder. (`#1898`_)35+- ``Flask.make_response`` raises ``TypeError`` instead of ``ValueError`` for36+ bad response types. The error messages have been improved to describe why the37+ type is invalid. (`#2256`_)38+- Add ``routes`` CLI command to output routes registered on the application.39+ (`#2259`_)40+- Show warning when session cookie domain is a bare hostname or an IP41+ address, as these may not behave properly in some browsers, such as Chrome.42+ (`#2282`_)43+- Allow IP address as exact session cookie domain. (`#2282`_)44+- ``SESSION_COOKIE_DOMAIN`` is set if it is detected through ``SERVER_NAME``.45+ (`#2282`_)46+- Auto-detect zero-argument app factory called ``create_app`` or ``make_app``47+ from ``FLASK_APP``. (`#2297`_)48+- Factory functions are not required to take a ``script_info`` parameter to49+ work with the ``flask`` command. If they take a single parameter or a50+ parameter named ``script_info``, the ``ScriptInfo`` object will be passed.51+ (`#2319`_)52+- FLASK_APP=myproject.app:create_app('dev') support.53+- ``FLASK_APP`` can be set to an app factory, with arguments if needed, for54+ example ``FLASK_APP=myproject.app:create_app('dev')``. (`#2326`_)55+- ``View.provide_automatic_options = True`` is set on the view function from56+ ``View.as_view``, to be detected in ``app.add_url_rule``. (`#2316`_)57+- Error handling will try handlers registered for ``blueprint, code``,58+ ``app, code``, ``blueprint, exception``, ``app, exception``. (`#2314`_)59+- ``Cookie`` is added to the response's ``Vary`` header if the session is60+ accessed at all during the request (and it wasn't deleted). (`#2288`_)61+- ``app.test_request_context()`` take ``subdomain`` and ``url_scheme``62+ parameters for use when building base URL. (`#1621`_)63+- Set ``APPLICATION_ROOT = '/'`` by default. This was already the implicit64+ default when it was set to ``None``.65+- ``TRAP_BAD_REQUEST_ERRORS`` is enabled by default in debug mode.66+ ``BadRequestKeyError`` has a message with the bad key in debug mode instead67+ of the generic bad request message. (`#2348`_)68+- Allow registering new tags with ``TaggedJSONSerializer`` to support69+ storing other types in the session cookie. (`#2352`_)70+- Only open the session if the request has not been pushed onto the context71+ stack yet. This allows ``stream_with_context`` generators to access the same72+ session that the containing view uses. (`#2354`_)73+- Add ``json`` keyword argument for the test client request methods. This will74+ dump the given object as JSON and set the appropriate content type.75+ (`#2358`_)76+- Extract JSON handling to a mixin applied to both the request and response77+ classes used by Flask. This adds the ``is_json`` and ``get_json`` methods to78+ the response to make testing JSON response much easier. (`#2358`_)79+- Removed error handler caching because it caused unexpected results for some80+ exception inheritance hierarchies. Register handlers explicitly for each81+ exception if you don't want to traverse the MRO. (`#2362`_)82+83+.. _#1489: https://github.com/pallets/flask/pull/148984+.. _#1621: https://github.com/pallets/flask/pull/162185+.. _#1898: https://github.com/pallets/flask/pull/189886+.. _#1936: https://github.com/pallets/flask/pull/193687+.. _#2017: https://github.com/pallets/flask/pull/201788+.. _#2193: https://github.com/pallets/flask/pull/219389+.. _#2223: https://github.com/pallets/flask/pull/222390+.. _#2254: https://github.com/pallets/flask/pull/225491+.. _#2256: https://github.com/pallets/flask/pull/225692+.. _#2259: https://github.com/pallets/flask/pull/225993+.. _#2282: https://github.com/pallets/flask/pull/228294+.. _#2288: https://github.com/pallets/flask/pull/228895+.. _#2297: https://github.com/pallets/flask/pull/229796+.. _#2314: https://github.com/pallets/flask/pull/231497+.. _#2316: https://github.com/pallets/flask/pull/231698+.. _#2319: https://github.com/pallets/flask/pull/231999+.. _#2326: https://github.com/pallets/flask/pull/2326100+.. _#2348: https://github.com/pallets/flask/pull/2348101+.. _#2352: https://github.com/pallets/flask/pull/2352102+.. _#2354: https://github.com/pallets/flask/pull/2354103+.. _#2358: https://github.com/pallets/flask/pull/2358104+.. _#2362: https://github.com/pallets/flask/pull/2362105+106+Version 0.12.2107+--------------108+109+Released on May 16 2017110+111+- Fix a bug in `safe_join` on Windows.112+113+Version 0.12.1114+--------------115+116+Bugfix release, released on March 31st 2017117+118+- Prevent `flask run` from showing a NoAppException when an ImportError occurs119+ within the imported application module.120+- Fix encoding behavior of ``app.config.from_pyfile`` for Python 3. Fix121+ ``#2118``.122+- Use the ``SERVER_NAME`` config if it is present as default values for123+ ``app.run``. ``#2109``, ``#2152``124+- Call `ctx.auto_pop` with the exception object instead of `None`, in the125+ event that a `BaseException` such as `KeyboardInterrupt` is raised in a126+ request handler.127+128 Version 0.12129 ------------130 131+Released on December 21st 2016, codename Punsch.132+133 - the cli command now responds to `--version`.10-- Mimetype guessing for ``send_file`` has been removed, as per issue ``#104``.11- See pull request ``#1849``.134+- Mimetype guessing and ETag generation for file-like objects in ``send_file``135+ has been removed, as per issue ``#104``. See pull request ``#1849``.136+- Mimetype guessing in ``send_file`` now fails loudly and doesn't fall back to137+ ``application/octet-stream``. See pull request ``#1988``.138 - Make ``flask.safe_join`` able to join multiple paths like ``os.path.join``139 (pull request ``#1730``).140+- Revert a behavior change that made the dev server crash instead of returning141+ a Internal Server Error (pull request ``#2006``).142+- Correctly invoke response handlers for both regular request dispatching as143+ well as error handlers.144+- Disable logger propagation by default for the app logger.145+- Add support for range requests in ``send_file``.146+- ``app.test_client`` includes preset default environment, which can now be147+ directly set, instead of per ``client.get``.148 149 Version 0.11.2150 --------------151 75 unmodified lines227 ``#1326``).228 - Don't leak exception info of already catched exceptions to context teardown229 handlers (pull request ``#1393``).230 - Allow custom Jinja environment subclasses (pull request ``#1422``).231+- Updated extension dev guidelines.232+233 - ``flask.g`` now has ``pop()`` and ``setdefault`` methods.234 - Turn on autoescape for ``flask.templating.render_template_string`` by default235 (pull request ``#1515``).236 - ``flask.ext`` is now deprecated (pull request ``#1484``).223 unmodified lines460 error if not handled. This is a backwards incompatible change.461 - Applications now not only have a root path where the resources and modules462 are located but also an instance path which is the designated place to463 drop files that are modified at runtime (uploads etc.). Also this is328- conceptionally only instance depending and outside version control so it's464+ conceptually only instance depending and outside version control so it's465 the perfect place to put configuration files etc. For more information466 see :ref:`instance-folders`.467 - Added the ``APPLICATION_ROOT`` configuration variable.468 - Implemented :meth:`~flask.testing.TestClient.session_transaction` to257 unmodified linesmodified:CONTRIBUTING.rst+125 added-48 removed
1-==========================1 How to contribute to Flask2 ==========================3 5-Thanks for considering contributing to Flask.4+Thank you for considering contributing to Flask!5 6 Support questions8-=================7+-----------------8 10-Please, don't use the issue tracker for this. Check whether the ``#pocoo`` IRC11-channel on Freenode can help with your issue. If your problem is not strictly12-Werkzeug or Flask specific, ``#python`` is generally more active.13-`Stack Overflow <https://stackoverflow.com/>`_ is also worth considering.9+Please, don't use the issue tracker for this. Use one of the following10+resources for questions about your own code:11 12+* The IRC channel ``#pocoo`` on FreeNode.13+* The IRC channel ``#python`` on FreeNode for more general questions.14+* The mailing list flask@python.org for long term discussion or larger issues.15+* Ask on `Stack Overflow`_. Search with Google first using:16+ ``site:stackoverflow.com flask {search term, exception message, etc.}``17+18+.. _Stack Overflow: https://stackoverflow.com/questions/tagged/flask?sort=linked19+20 Reporting issues16-================21+----------------22 18-- Under which versions of Python does this happen? This is even more important19- if your issue is encoding related.23+- Describe what you expected to happen.24+- If possible, include a `minimal, complete, and verifiable example`_ to help25+ us identify the issue. This also helps check that the issue is not with your26+ own code.27+- Describe what actually happened. Include the full traceback if there was an28+ exception.29+- List your Python, Flask, and Werkzeug versions. If possible, check if this30+ issue is already fixed in the repository.31 21-- Under which versions of Werkzeug does this happen? Check if this issue is22- fixed in the repository.32+.. _minimal, complete, and verifiable example: https://stackoverflow.com/help/mcve33 34 Submitting patches25-==================35+------------------36 37 - Include tests if your patch is supposed to solve a bug, and explain38 clearly under which circumstances the bug happens. Make sure the test fails39 without your patch.40+- Try to follow `PEP8`_, but you may ignore the line length limit if following41+ it would make the code uglier.42 31-- Try to follow `PEP8 <http://legacy.python.org/dev/peps/pep-0008/>`_, but you32- may ignore the line-length-limit if following it would make the code uglier.43+First time setup44+~~~~~~~~~~~~~~~~45 46+- Download and install the `latest version of git`_.47+- Configure git with your `username`_ and `email`_::48 35-Running the testsuite36----------------------49+ git config --global user.name 'your name'50+ git config --global user.email 'your email'51 38-You probably want to set up a `virtualenv39-<https://virtualenv.readthedocs.io/en/latest/index.html>`_.52+- Make sure you have a `GitHub account`_.53+- Fork Flask to your GitHub account by clicking the `Fork`_ button.54+- `Clone`_ your GitHub fork locally::55 41-The minimal requirement for running the testsuite is ``py.test``. You can42-install it with::56+ git clone https://github.com/{username}/flask57+ cd flask58 44- pip install pytest59+- Add the main repository as a remote to update later::60 46-Clone this repository::61+ git remote add pallets https://github.com/pallets/flask62+ git fetch pallets63 48- git clone https://github.com/pallets/flask.git64+- Create a virtualenv::65 50-Install Flask as an editable package using the current source::66+ python3 -m venv env67+ . env/bin/activate68+ # or "env\Scripts\activate" on Windows69 52- cd flask53- pip install --editable .70+- Install Flask in editable mode with development dependencies::71 55-Then you can run the testsuite with::72+ pip install -e ".[dev]"73 57- py.test74+.. _GitHub account: https://github.com/join75+.. _latest version of git: https://git-scm.com/downloads76+.. _username: https://help.github.com/articles/setting-your-username-in-git/77+.. _email: https://help.github.com/articles/setting-your-email-in-git/78+.. _Fork: https://github.com/pallets/flask/pull/2305#fork-destination-box79+.. _Clone: https://help.github.com/articles/fork-a-repo/#step-2-create-a-local-clone-of-your-fork80 59-With only py.test 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.81+Start coding82+~~~~~~~~~~~~83 64-If you really want to test everything, you will have to install ``tox`` instead65-of ``pytest``. You can install it with::84+- Create a branch to identify the issue you would like to work on (e.g.85+ ``2287-dry-test-suite``)86+- Using your favorite editor, make your changes, `committing as you go`_.87+- Try to follow `PEP8`_, but you may ignore the line length limit if following88+ it would make the code uglier.89+- Include tests that cover any code changes you make. Make sure the test fails90+ without your patch. `Run the tests. <contributing-testsuite_>`_.91+- Push your commits to GitHub and `create a pull request`_.92+- Celebrate 🎉93 67- pip install tox94+.. _committing as you go: http://dont-be-afraid-to-commit.readthedocs.io/en/latest/git/commandlinegit.html#commit-your-changes95+.. _PEP8: https://pep8.org/96+.. _create a pull request: https://help.github.com/articles/creating-a-pull-request/97 69-The ``tox`` command will then run all tests against multiple combinations70-Python versions and dependency versions.98+.. _contributing-testsuite:99 100+Running the tests101+~~~~~~~~~~~~~~~~~102+103+Run the basic test suite with::104+105+ pytest106+107+This only runs the tests for the current environment. Whether this is relevant108+depends on which part of Flask you're working on. Travis-CI will run the full109+suite when you submit your pull request.110+111+The full test suite takes a long time to run because it tests multiple112+combinations of Python and dependencies. You need to have Python 2.6, 2.7, 3.3,113+3.4, 3.5 3.6, and PyPy 2.7 installed to run all of the environments. Then run::114+115+ tox116+117 Running test coverage73----------------------74-Generating a report of lines that do not have unit test coverage can indicate where75-to start contributing. ``pytest`` integrates with ``coverage.py``, using the ``pytest-cov``76-plugin. This assumes you have already run the testsuite (see previous section)::118+~~~~~~~~~~~~~~~~~~~~~119 78- pip install pytest-cov120+Generating a report of lines that do not have test coverage can indicate121+where to start contributing. Run ``pytest`` using ``coverage`` and generate a122+report on the terminal and as an interactive HTML document::123 80-After this has been installed, you can output a report to the command line using this command::124+ coverage run -m pytest125+ coverage report126+ coverage html127+ # then open htmlcov/index.html128 82- py.test --cov=flask tests/129+Read more about `coverage <https://coverage.readthedocs.io>`_.130 84-Generate a HTML report can be done using this command::131+Running the full test suite with ``tox`` will combine the coverage reports132+from all runs.133 86- py.test --cov-report html --cov=flask tests/134+``make`` targets135+~~~~~~~~~~~~~~~~136 88-Full docs on ``coverage.py`` are here: https://coverage.readthedocs.io137+Flask provides a ``Makefile`` with various shortcuts. They will ensure that138+all dependencies are installed.139 140+- ``make test`` runs the basic test suite with ``pytest``141+- ``make cov`` runs the basic test suite with ``coverage``142+- ``make test-all`` runs the full test suite with ``tox``143+- ``make docs`` builds the HTML documentation144+145+Caution: zero-padded file modes146+-------------------------------147+148+This repository contains several zero-padded file modes that may cause issues149+when pushing this repository to git hosts other than GitHub. Fixing this is150+destructive to the commit history, so we suggest ignoring these warnings. If it151+fails to push and you're using a self-hosted git service like GitLab, you can152+turn off repository checks in the admin panel.153+154+These files can also cause issues while cloning. If you have ::155+156+ [fetch]157+ fsckobjects = true158+159+or ::160+161+ [receive]162+ fsckObjects = true163+164+set in your git configuration file, cloning this repository will fail. The only165+solution is to set both of the above settings to false while cloning, and then166+setting them back to true after the cloning is finished.modified:Makefile+21 added-12 removed
1-.PHONY: clean-pyc ext-test test tox-test test-with-mem upload-docs docs audit1+.PHONY: all install-dev test coverage cov test-all tox docs audit release clean-pyc upload-docs ebook2 3-all: clean-pyc test3+all: test4 5-test:6- pip install -r test-requirements.txt -q7- FLASK_DEBUG= py.test tests examples5+install-dev:6+ pip install -q -e .[dev]7 9-tox-test:8+test: clean-pyc install-dev9+ pytest10+11+coverage: clean-pyc install-dev12+ pip install -q -e .[test]13+ coverage run -m pytest14+ coverage report15+ coverage html16+17+cov: coverage18+19+test-all: install-dev20 tox21 22+tox: test-all23+24+docs: clean-pyc install-dev25+ $(MAKE) -C docs html26+27 audit:28 python setup.py audit29 30 release:31 python scripts/make-release.py32 18-ext-test:19- python tests/flaskext_test.py --browse20-33 clean-pyc:34 find . -name '*.pyc' -exec rm -f {} +35 find . -name '*.pyo' -exec rm -f {} +36 find . -name '*~' -exec rm -f {} +13 unmodified lines50 @echo 'Command `ebook-covert` is provided by calibre package.'51 @echo 'Requires X-forwarding for Qt features used in conversion (ssh -X).'52 @echo 'Do not mind "Invalid value for ..." CSS errors if .mobi renders.'53 ssh -X pocoo.org ebook-convert /var/www/flask.pocoo.org/docs/flask-docs.epub /var/www/flask.pocoo.org/docs/flask-docs.mobi --cover http://flask.pocoo.org/docs/_images/logo-full.png --authors 'Armin Ronacher'42-43-docs:44- $(MAKE) -C docs htmlmodified: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+7 added-3 removed
1 [aliases]2 release = egg_info -RDb ''3 4-[wheel]4+[bdist_wheel]5 universal = 16 7-[pytest]8-norecursedirs = .* *.egg *.egg-info env* artwork docs7+[metadata]8+license_file = LICENSE9+10+[tool:pytest]11+minversion = 3.012+testpaths = testsmodified:setup.py+17 added-7 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 ast49 from setuptools import setup50 51-51 _version_re = re.compile(r'__version__\s+=\s+(.*)')52 53 with open('flask/__init__.py', 'rb') as f:54 version = str(ast.literal_eval(_version_re.search(55 f.read().decode('utf-8')).group(1)))56 58-57 setup(58 name='Flask',59 version=version,62- url='http://github.com/pallets/flask/',60+ url='https://github.com/pallets/flask/',61 license='BSD',62 author='Armin Ronacher',63 author_email='armin.ronacher@active-4.com',64 description='A microframework based on Werkzeug, Jinja2 '65 'and good intentions',66 long_description=__doc__,69- packages=['flask', 'flask.ext'],67+ packages=['flask', 'flask.ext', 'flask.json'],68 include_package_data=True,69 zip_safe=False,70 platforms='any',71 install_requires=[74- 'Werkzeug>=0.7',72+ 'Werkzeug>=0.9',73 'Jinja2>=2.4',74 'itsdangerous>=0.21',77- 'click>=2.0',75+ 'click>=4.0',76 ],77+ extras_require={78+ 'dev': [79+ 'blinker',80+ 'greenlet',81+ 'pytest>=3',82+ 'coverage',83+ 'tox',84+ 'sphinx',85+ 'sphinxcontrib-log-cabinet'86+ ],87+ },88 classifiers=[89 'Development Status :: 4 - Beta',90 'Environment :: Web Environment',91 'Intended Audience :: Developers',6 unmodified lines98 'Programming Language :: Python :: 3',99 'Programming Language :: Python :: 3.3',100 'Programming Language :: Python :: 3.4',101 'Programming Language :: Python :: 3.5',102+ 'Programming Language :: Python :: 3.6',103 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',104 'Topic :: Software Development :: Libraries :: Python Modules'105 ],106 entry_points='''4 unmodified linesmodified:test-requirements.txt+2 added
1+tox2 pytest3+pytest-covmodified:tox.ini+59 added-17 removed
1 [tox]2-envlist = {py26,py27,pypy}-{lowest,release,devel}{,-simplejson}, {py33,py34,py35}-{release,devel}{,-simplejson}2+envlist =3+ py{36,35,34,33,27,26,py}4+ py{36,27,py}-simplejson5+ py{36,33,27,26,py}-devel6+ py{36,33,27,26,py}-lowest7+ docs-html8+ coverage-report9 4-5-10 [testenv]7-commands =8- py.test []9-10-deps=11- pytest11+passenv = LANG12+usedevelop = true13+deps =14+ pytest>=315+ coverage16 greenlet13- redbaron17+ blinker18 15- lowest: Werkzeug==0.719+ lowest: Werkzeug==0.920 lowest: Jinja2==2.421 lowest: itsdangerous==0.2118- lowest: blinker==1.019- release: blinker20- devel: git+https://github.com/pallets/werkzeug.git21- devel: git+https://github.com/pallets/jinja.git22- devel: git+https://github.com/pallets/itsdangerous.git23- devel: git+https://github.com/jek/blinker.git22+ lowest: Click==4.023+24+ devel: https://github.com/pallets/werkzeug/archive/master.tar.gz25+ devel: https://github.com/pallets/markupsafe/archive/master.tar.gz26+ devel: https://github.com/pallets/jinja/archive/master.tar.gz27+ devel: https://github.com/pallets/itsdangerous/archive/master.tar.gz28+ devel: https://github.com/pallets/click/archive/master.tar.gz29+30 simplejson: simplejson31+commands =32+ # the examples need to be installed to test successfully33+ pip install -e examples/flaskr -q34+ pip install -e examples/minitwit -q35+ pip install -e examples/patterns/largerapp -q36 37+ # pytest-cov doesn't seem to play nice with -p38+ coverage run -p -m pytest tests examples39+26-[testenv:docs]40+[testenv:docs-html]41 deps = sphinx42+commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs docs/_build/html43+44+[testenv:docs-linkcheck]45+deps = sphinx46 commands = sphinx-build -W -b linkcheck -d {envtmpdir}/doctrees docs docs/_build/linkcheck47+48+[testenv:coverage-report]49+deps = coverage50+skip_install = true51+commands =52+ coverage combine53+ coverage report54+ coverage html55+56+[testenv:codecov]57+passenv = CI TRAVIS TRAVIS_*58+deps = codecov59+skip_install = true60+commands =61+ coverage combine62+ coverage report63+ codecov64+65+[testenv:detox]66+skip_install = true67+deps = detox68+commands =69+ detox -e py{36,35,34,33,27,26,py},py{36,27,py}-simplejson,py{36,33,27,26,py}-devel,py{36,33,27,26,py}-lowest,docs-html70+ tox -e coverage-report