Merge branch 'master' into AvivC-improve-docs-in-Flask.preprocess_request
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 826d747, 970a800 · Browse files · 171 files·+4297 added−3029 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
171 files+4297 added−3029 removed
- tests:+1357 added−250 removed
- other:+2940 added−2779 removed
Provenance
- Commit
bc7dae3- Tree
58178d1- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
826d747- Parent 2
970a800
171 files changed+4297 added−3029 removed
added:.github/ISSUE_TEMPLATE.rst+2 added
1+The issue tracker is a tool to address bugs.2+Please use the #pocoo IRC channel on freenode or Stack Overflow for questions.modified:docs/_templates/sidebarintro.html+3 added-3 removed
14 unmodified lines151617181920211920212214 unmodified lines</ul><h3>Useful Links</h3><ul> <li><a href="http://flask.pocoo.org/">The Flask Website</a></li> <li><a href="http://pypi.python.org/pypi/Flask">Flask @ PyPI</a></li> <li><a href="http://github.com/mitsuhiko/flask">Flask @ GitHub</a></li> <li><a href="http://github.com/mitsuhiko/flask/issues">Issue Tracker</a></li> <li><a href="https://pypi.python.org/pypi/Flask">Flask @ PyPI</a></li> <li><a href="https://github.com/pallets/flask">Flask @ GitHub</a></li> <li><a href="https://github.com/pallets/flask/issues">Issue Tracker</a></li></ul>modified:docs/deploying/fastcgi.rst+4 added-4 removed
142 unmodified lines143 ))144 )145 146 alias.url = (147- "/static/" => "/path/to/your/static"147+ "/static/" => "/path/to/your/static/"148 )149 150 url.rewrite-once = (151 "^(/static($|/.*))$" => "$1",6 unmodified lines158 :class:`~werkzeug.contrib.fixers.LighttpdCGIRootFix` middleware.159 160 Make sure to apply it only if you are mounting the application the URL161 root. Also, see the Lighty docs for more information on `FastCGI and Python162-<http://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModFastCGI>`_ (note that162+<https://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModFastCGI>`_ (note that163 explicitly passing a socket to run() is no longer necessary).164 165 Configuring nginx166 -----------------66 unmodified lines233 - The code depending on environment variables that are not set by the234 web server.235 - Different python interpreters being used.236 237-.. _nginx: http://nginx.org/238-.. _lighttpd: http://www.lighttpd.net/237+.. _nginx: https://nginx.org/238+.. _lighttpd: https://www.lighttpd.net/239 .. _cherokee: http://cherokee-project.com/240 .. _flup: https://pypi.python.org/pypi/flupmodified:docs/deploying/index.rst+2 added-2 removed
17 unmodified lines18 --------------19 20 - `Deploying Flask on Heroku <https://devcenter.heroku.com/articles/getting-started-with-python>`_21 - `Deploying Flask on OpenShift <https://developers.openshift.com/en/python-flask.html>`_22-- `Deploying WSGI on dotCloud <http://docs.dotcloud.com/services/python/>`_23- with `Flask-specific notes <http://flask.pocoo.org/snippets/48/>`_22 - `Deploying Flask on Webfaction <http://flask.pocoo.org/snippets/65/>`_23 - `Deploying Flask on Google App Engine <https://github.com/kamalgill/flask-appengine-template>`_24+- `Deploying Flask on AWS Elastic Beanstalk <https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-flask.html>`_25 - `Sharing your Localhost Server with Localtunnel <http://flask.pocoo.org/snippets/89/>`_26 - `Deploying on Azure (IIS) <https://azure.microsoft.com/documentation/articles/web-sites-python-configure/>`_27+- `Deploying on PythonAnywhere <https://help.pythonanywhere.com/pages/Flask/>`_28 29 Self-hosted options30 -------------------31 8 unmodified linesmodified:docs/deploying/mod_wsgi.rst+7 added-7 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 143 If your application does not run, follow this guide to troubleshoot:144 145 **Problem:** application does not run, errorlog shows SystemExit ignored146- You have a ``app.run()`` call in your application file that is not146+ You have an ``app.run()`` call in your application file that is not147 guarded by an ``if __name__ == '__main__':`` condition. Either148 remove that :meth:`~flask.Flask.run` call from the file and move it149 into a separate :file:`run.py` file or put it into such an if block.150 67 unmodified linesmodified:docs/deploying/uwsgi.rst+11 added-15 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-Or, if you prefer: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``.37+If your application is accessible at root level, you can use a single ``/``38+instead of ``/yourapplication``. ``myapp`` refers to the name of the file of39+your flask application (without extension) or the module which provides ``app``.40+``app`` is the callable inside of your application (usually the line reads41+``app = Flask(__name__)``.42 36-.. sourcecode:: text37-38- $ uwsgi -s /tmp/uwsgi.sock --manage-script-name --mount /yourapplication=myapp:app39-40-The ``--manage-script-name`` will move the handling of ``SCRIPT_NAME`` to41-uwsgi, since its smarter about that. It is used together with the ``--mount``42-directive which will make requests to ``/yourapplication`` be directed to43-``myapp:app``, where ``myapp`` refers to the name of the file of your flask44-application (without extension). ``app`` is the callable inside of your45-application (usually the line reads ``app = Flask(__name__)``.46-43 If you want to deploy your flask application inside of a virtual environment,44 you need to also add ``--virtualenv /path/to/virtual/environment``. You might45 also need to add ``--plugin python`` or ``--plugin python3`` depending on which46 python version you use for your project.18 unmodified lines65 include uwsgi_params;66 uwsgi_pass unix:/tmp/yourapplication.sock;67 }68 73-.. _nginx: http://nginx.org/74-.. _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+6 added-5 removed
23 unmodified lines24 gunicorn -w 4 -b 127.0.0.1:4000 myproject:app25 26 .. _Gunicorn: http://gunicorn.org/27 .. _eventlet: http://eventlet.net/28-.. _greenlet: http://greenlet.readthedocs.org/en/latest/28+.. _greenlet: https://greenlet.readthedocs.io/en/latest/29 30 Gevent31 -------32 7 unmodified lines40 http_server = WSGIServer(('', 5000), app)41 http_server.serve_forever()42 43 .. _Gevent: http://www.gevent.org/44-.. _greenlet: http://greenlet.readthedocs.org/en/latest/44+.. _greenlet: https://greenlet.readthedocs.io/en/latest/45 .. _libev: http://software.schmorp.de/pkg/libev.html46 47 Twisted Web48 -----------47 unmodified lines96 location / {97 proxy_pass http://127.0.0.1:8000/;98 proxy_redirect off;99 100- proxy_set_header Host $host;101- proxy_set_header X-Real-IP $remote_addr;102- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;100+ proxy_set_header Host $host;101+ proxy_set_header X-Real-IP $remote_addr;102+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;103+ proxy_set_header X-Forwarded-Proto $scheme;104 }105 }106 107 If your httpd is not providing these headers, the most common setup invokes the27 unmodified linesmodified:docs/patterns/apierrors.rst+1 added-1 removed
1 Implementing API Exceptions2 ===========================3 4 It's very common to implement RESTful APIs on top of Flask. One of the5-first thing that developers run into is the realization that the builtin5+first things that developers run into is the realization that the builtin6 exceptions are not expressive enough for APIs and that the content type of7 :mimetype:`text/html` they are emitting is not very useful for API consumers.8 9 The better solution than using ``abort`` to signal errors for invalid API54 unmodified linesmodified:docs/patterns/appdispatch.rst+7 added-7 removed
2 unmodified lines3 Application Dispatching4 =======================5 6 Application dispatching is the process of combining multiple Flask7-applications on the WSGI level. You can not only combine Flask8-applications into something larger but any WSGI application. This would9-even allow you to run a Django and a Flask application in the same10-interpreter side by side if you want. The usefulness of this depends on11-how the applications work internally.7+applications on the WSGI level. You can combine not only Flask8+applications but any WSGI application. This would allow you to run a9+Django and a Flask application in the same interpreter side by side if10+you want. The usefulness of this depends on how the applications work11+internally.12 13 The fundamental difference from the :ref:`module approach14 <larger-applications>` is that in this case you are running the same or15 different Flask applications that are entirely isolated from each other.14 unmodified lines30 Note that :func:`run_simple <werkzeug.serving.run_simple>` is not intended for31 use in production. Use a :ref:`full-blown WSGI server <deployment>`.32 33 In order to use the interactive debugger, debugging must be enabled both on34-the application and the simple server, here is the "hello world" example with34+the application and the simple server. Here is the "hello world" example with35 debugging and :func:`run_simple <werkzeug.serving.run_simple>`::36 37 from flask import Flask38 from werkzeug.serving import run_simple16 unmodified lines55 If you have entirely separated applications and you want them to work next56 to each other in the same Python interpreter process you can take57 advantage of the :class:`werkzeug.wsgi.DispatcherMiddleware`. The idea58 here is that each Flask application is a valid WSGI application and they59-are combined by the dispatcher middleware into a larger one that59+are combined by the dispatcher middleware into a larger one that is60 dispatched based on prefix.61 62 For example you could have your main application run on ``/`` and your63 backend interface on ``/backend``::125 unmodified linesmodified:docs/patterns/appfactories.rst+4 added-3 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__)30 unmodified lines98 app = create_app('/path/to/config.cfg')99 100 It can then be used with the :command:`flask` command::101 102- flask --app=exampleapp run102+ export FLASK_APP=exampleapp103+ flask run104 105 Factory Improvements106 --------------------107 9 unmodified linesmodified:docs/patterns/celery.rst+1 added-1 removed
34 unmodified lines35 36 from celery import Celery37 38 def make_celery(app):39- celery = Celery(app.import_name, backend=app.config['CELERY_BACKEND'],39+ celery = Celery(app.import_name, backend=app.config['CELERY_RESULT_BACKEND'],40 broker=app.config['CELERY_BROKER_URL'])41 celery.conf.update(app.config)42 TaskBase = celery.Task43 class ContextTask(TaskBase):50 unmodified linesmodified:docs/patterns/deferredcallbacks.rst+3 added-3 removed
54 unmodified lines55 56 A Practical Example57 -------------------58 59-Now we can easily at any point in time register a function to be called at60-the end of this particular request. For example you can remember the61-current language of the user in a cookie in the before-request function::59+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::62 63 from flask import request64 65 @app.before_request8 unmodified linesmodified:docs/patterns/distribute.rst+56 added-45 removed
1 .. _distribute-deployment:2 3-Deploying with Distribute3+Deploying with Setuptools4 =========================5 6-`distribute`_, formerly setuptools, is an extension library that is7-commonly used to (like the name says) distribute Python libraries and8-extensions. It extends distutils, a basic module installation system9-shipped with Python to also support various more complex constructs that10-make larger applications easier to distribute:6+`Setuptools`_, is an extension library that is commonly used to7+distribute Python libraries and extensions. It extends distutils, a basic8+module installation system shipped with Python to also support various more9+complex constructs that make larger applications easier to distribute:10 11 - **support for dependencies**: a library or application can declare a12 list of other libraries it depends on which will be installed13 automatically for you.14 - **package registry**: setuptools registers your package with your15 Python installation. This makes it possible to query information16 provided by one package from another package. The best known feature of17 this system is the entry point support which allows one package to19- declare an "entry point" another package can hook into to extend the18+ declare an "entry point" that another package can hook into to extend the19 other package.21-- **installation manager**: :command:`easy_install`, which comes with distribute22- can install other libraries for you. You can also use `pip`_ which23- sooner or later will replace :command:`easy_install` which does more than just24- installing packages for you.20+- **installation manager**: :command:`pip` can install other libraries for you.21 26-Flask itself, and all the libraries you can find on the cheeseshop27-are distributed with either distribute, the older setuptools or distutils.22+If you have Python 2 (>=2.7.9) or Python 3 (>=3.4) installed from python.org,23+you will already have pip and setuptools on your system. Otherwise, you24+will need to install them yourself.25 26+Flask itself, and all the libraries you can find on PyPI are distributed with27+either setuptools or distutils.28+29 In this case we assume your application is called30 :file:`yourapplication.py` and you are not using a module, but a :ref:`package31-<larger-applications>`. Distributing resources with standard modules is32-not supported by `distribute`_ so we will not bother with it. If you have33-not yet converted your application into a package, head over to the34-:ref:`larger-applications` pattern to see how this can be done.31+<larger-applications>`. If you have not yet converted your application into32+a package, head over to the :ref:`larger-applications` pattern to see33+how this can be done.34 36-A working deployment with distribute is the first step into more complex35+A working deployment with setuptools is the first step into more complex36 and more automated deployment scenarios. If you want to fully automate37 the process, also read the :ref:`fabric-deployment` chapter.38 39 Basic Setup Script40 ------------------41 43-Because you have Flask running, you either have setuptools or distribute44-available on your system anyways. If you do not, fear not, there is a45-script to install it for you: `distribute_setup.py`_. Just download and46-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 48 Your setup code always goes into a file named :file:`setup.py` next to your49 application. The name of the file is only convention, but because50 everybody will look for a file with that name, you better not change it.51 55-Yes, even if you are using `distribute`, you are importing from a package56-called `setuptools`. `distribute` is fully backwards compatible with57-`setuptools`, so it also uses the same import name.58-52 A basic :file:`setup.py` file for a Flask application looks like this::53 54 from setuptools import setup55 7 unmodified lines63 install_requires=['Flask']64 )65 66 Please keep in mind that you have to list subpackages explicitly. If you74-want distribute to lookup the packages for you automatically, you can use75-the `find_packages` function::67+want setuptools to lookup the packages for you automatically, you can use68+the ``find_packages`` function::69 70 from setuptools import setup, find_packages71 72 setup(73 ...74 packages=find_packages()75 )76 84-Most parameters to the `setup` function should be self explanatory,85-`include_package_data` and `zip_safe` might not be.86-`include_package_data` tells distribute 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 module89-(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 87 88+Tagging Builds89+--------------90+91+It is useful to distinguish between release and development builds. Add a92+:file:`setup.cfg` file to configure these options.93+94+ [egg_info]95+ tag_build = .dev96+ tag_date = 197+98+ [aliases]99+ release = egg_info -RDb ''100+101+Running ``python setup.py sdist`` will create a development package102+with ".dev" and the current date appended: ``flaskr-1.0.dev20160314.tar.gz``.103+Running ``python setup.py release sdist`` will create a release package104+with only the version: ``flaskr-1.0.tar.gz``.105+106+107 .. _distributing-resources:108 109 Distributing Resources110 ----------------------111 112 If you try to install the package you just created, you will notice that113 folders like :file:`static` or :file:`templates` are not installed for you. The102-reason for this is that distribute does not know which files to add for114+reason for this is that setuptools does not know which files to add for115 you. What you should do, is to create a :file:`MANIFEST.in` file next to your116 :file:`setup.py` file. This file lists all the files that should be added to117 your tarball::118 1 unmodified line120 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`112-parameter of the `setup` function to ``True``!124+parameter of the ``setup`` function to ``True``!125 126 127 Declaring Dependencies128 ----------------------129 118-Dependencies are declared in the `install_requires` parameter as 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::3 unmodified lines138 'SQLAlchemy>=0.6',139 'BrokenPackage>=0.7,<=1.0'140 ]141 130-I mentioned earlier that dependencies are pulled from PyPI. What if you142+As mentioned earlier, dependencies are pulled from PyPI. What if you143 want to depend on a package that cannot be found on PyPI and won't be144 because it is an internal package you don't want to share with anyone?133-Just still do as if there was a PyPI entry for it and provide a list of134-alternative locations where distribute should look for tarballs::145+Just do it as if there was a PyPI entry and provide a list of146+alternative locations where setuptools should look for tarballs::147 148 dependency_links=['http://example.com/yourfiles']149 150 Make sure that page has a directory listing and the links on the page are151 pointing to the actual tarballs with their correct filenames as this is140-how distribute will find the files. If you have an internal company141-server that contains the packages, provide the URL to that server there.152+how setuptools will find the files. If you have an internal company153+server that contains the packages, provide the URL to that server.154 155 156 Installing / Developing157 -----------------------158 159 To install your application (ideally into a virtualenv) just run the148-: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 be155-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 on161-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 164-.. _distribute: https://pypi.python.org/pypi/distribute176 .. _pip: https://pypi.python.org/pypi/pip166-.. _distribute_setup.py: http://python-distribute.org/distribute_setup.py177+.. _Setuptools: https://pypi.python.org/pypi/setuptoolsmodified:docs/patterns/fabric.rst+14 added-24 removed
41 unmodified lines42 # the servers where the commands are executed43 env.hosts = ['server1.example.com', 'server2.example.com']44 45 def pack():46- # create a new source distribution as tarball46+ # build the package47 local('python setup.py sdist --formats=gztar', capture=False)48 49 def deploy():50- # figure out the release name and version50+ # figure out the package name and version51 dist = local('python setup.py --fullname', capture=True).strip()52- # upload the source tarball to the temporary folder on the server53- put('dist/%s.tar.gz' % dist, '/tmp/yourapplication.tar.gz')54- # create a place where we can unzip the tarball, then enter55- # that directory and unzip it56- run('mkdir /tmp/yourapplication')57- with cd('/tmp/yourapplication'):58- run('tar xzf /tmp/yourapplication.tar.gz')59- # now setup the package with our virtual environment's60- # python interpreter61- run('/var/www/yourapplication/env/bin/python setup.py install')62- # now that all is set up, delete the folder again63- run('rm -rf /tmp/yourapplication /tmp/yourapplication.tar.gz')64- # and finally touch the .wsgi file so that mod_wsgi triggers65- # a reload of the application66- run('touch /var/www/yourapplication.wsgi')52+ filename = '%s.tar.gz' % dist53 68-The example above is well documented and should be straightforward. Here69-a recap of the most common commands fabric provides:54+ # upload the package to the temporary folder on the server55+ put('dist/%s' % filename, '/tmp/%s' % filename)56 71-- `run` - executes a command on a remote server72-- `local` - executes a command on the local machine73-- `put` - uploads a file to the remote server74-- `cd` - changes the directory on the serverside. This has to be used75- in combination with the ``with`` statement.57+ # install the package in the application's virtualenv with pip58+ run('/var/www/yourapplication/env/bin/pip install /tmp/%s' % filename)59 60+ # remove the uploaded package61+ run('rm -r /tmp/%s' % filename)62+63+ # touch the .wsgi file to trigger a reload in mod_wsgi64+ run('touch /var/www/yourapplication.wsgi')65+66 Running Fabfiles67 ----------------68 69 Now how do you execute that fabfile? You use the `fab` command. To74 unmodified lines144 145 Either way, in our case here we only expect one or two servers and we can146 upload them ahead of time by hand.147 148+149 First Deployment150 ----------------151 152 Now we can do our first deployment. We have set up the servers so that34 unmodified linesmodified: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+11 added-11 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'])10 unmodified lines39 your users to be able to upload everything there if the server is directly40 sending out the data to the client. That way you can make sure that users41 are not able to upload HTML files that would cause XSS problems (see42 :ref:`xss`). Also make sure to disallow ``.php`` files if the server43-executes them, but who has PHP installed on his server, right? :)43+executes them, but who has PHP installed on their server, right? :)44 45 Next the functions that check if an extension is valid and that uploads46 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+4 added-2 removed
7 unmodified lines8 application. Flask provides a really simple way to give feedback to a9 user with the flashing system. The flashing system basically makes it10 possible to record a message at the end of a request and access it next11 request and only next request. This is usually combined with a layout12-template that does this.12+template that does this. Note that browsers and sometimes web servers enforce13+a limit on cookie sizes. This means that flashing messages that are too14+large for session cookies causes message flashing to fail silently.15 16 Simple Flashing17 ---------------18 58 unmodified lines77 <h1>Login</h1>78 {% if error %}79 <p class=error><strong>Error:</strong> {{ error }}80 {% endif %}79- <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/index.rst+1 added
39 unmodified lines40 deferredcallbacks41 methodoverrides42 requestchecksum43 celery44+ subclassingmodified:docs/patterns/jquery.rst+1 added-1 removed
162 unmodified lines163 we set earlier.164 165 If you don't get the whole picture, download the `sourcecode166 for this example167-<https://github.com/mitsuhiko/flask/tree/master/examples/jqueryexample>`_167+<https://github.com/pallets/flask/tree/master/examples/jqueryexample>`_168 from GitHub.modified: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 linesadded:docs/patterns/subclassing.rst+17 added
1+Subclassing Flask2+=================3+4+The :class:`~flask.Flask` class is designed for subclassing.5+6+For example, you may want to override how request parameters are handled to preserve their order::7+8+ from flask import Flask, Request9+ from werkzeug.datastructures import ImmutableOrderedMultiDict10+ class MyRequest(Request):11+ """Request subclass to override request parameter storage"""12+ parameter_storage_class = ImmutableOrderedMultiDict13+ class MyFlask(Flask):14+ """Flask subclass using the custom request class"""15+ request_class = MyRequest16+17+This is the recommended approach for overriding or augmenting Flask's internal functionality.modified:docs/patterns/viewdecorators.rst+17 added-10 removed
14 unmodified lines15 Login Required Decorator16 ------------------------17 18 So let's implement such a decorator. A decorator is a function that19-returns a function. Pretty simple actually. The only thing you have to20-keep in mind when implementing something like this is to update the21-`__name__`, `__module__` and some other attributes of a function. This is22-often forgotten, but you don't have to do that by hand, there is a23-function for that that is used like a decorator (:func:`functools.wraps`).19+wraps and replaces another function. Since the original function is20+replaced, you need to remember to copy the original function's information21+to the new function. Use :func:`functools.wraps` to handle this for you.22 23 This example assumes that the login page is called ``'login'`` and that26-the current user is stored as `g.user` and ``None`` if there is no-one27-logged in::24+the current user is stored in ``g.user`` and is ``None`` if there is no-one25+logged in. ::26 27 from functools import wraps28 from flask import g, request, redirect, url_for29 4 unmodified lines34 return redirect(url_for('login', next=request.url))35 return f(*args, **kwargs)36 return decorated_function37 40-So how would you use that decorator now? Apply it as innermost decorator41-to a view function. When applying further decorators, always remember42-that the :meth:`~flask.Flask.route` decorator is the outermost::38+To use the decorator, apply it as innermost decorator to a view function.39+When applying further decorators, always remember40+that the :meth:`~flask.Flask.route` decorator is the outermost. ::41 42 @app.route('/secret_page')43 @login_required44 def secret_page():45 pass46 47+.. note::48+ The ``next`` value will exist in ``request.args`` after a ``GET`` request for49+ the login page. You'll have to pass it along when sending the ``POST`` request50+ from the login form. You can do this with a hidden input tag, then retrieve it51+ from ``request.form`` when logging the user in. ::52+53+ <input type="hidden" value="{{ request.args.get('next', '') }}"/>54+55+56 Caching Decorator57 -----------------58 59 Imagine you have a view function that does an expensive calculation and113 unmodified linesmodified:docs/patterns/wtforms.rst+6 added-6 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 4 unmodified lines31 class RegistrationForm(Form):32 username = StringField('Username', [validators.Length(min=4, max=25)])33 email = StringField('Email Address', [validators.Length(min=6, max=35)])34 password = PasswordField('New Password', [35- validators.Required(),35+ validators.DataRequired(),36 validators.EqualTo('confirm', message='Passwords must match')37 ])38 confirm = PasswordField('Repeat Password')39- accept_tos = BooleanField('I accept the TOS', [validators.Required()])39+ accept_tos = BooleanField('I accept the TOS', [validators.DataRequired()])40 41 In the View42 -----------43 63 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) }}5 unmodified lines121 122 For more information about WTForms, head over to the `WTForms123 website`_.124 125-.. _WTForms: http://wtforms.readthedocs.org/126-.. _WTForms website: http://wtforms.readthedocs.org/125+.. _WTForms: https://wtforms.readthedocs.io/126+.. _WTForms website: https://wtforms.readthedocs.io/modified: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+14 added-17 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+You currently have a function for establishing a database connection with7+`connect_db`, but by itself, it is not particularly useful. Creating and8+closing database connections all the time is very inefficient, so you will9+need to keep it around for longer. Because database connections10+encapsulate a transaction, you will need to make sure that only one11+request at a time uses the connection. An elegant way to do this is by12+utilizing the *application context*.13 13-This is where the application context comes into play, so let's start14-there.15-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 there14+Flask provides two contexts: the *application context* and the15+*request context*. For the time being, all you have to know is that there16 are special variables that use these. For instance, the17 :data:`~flask.request` variable is the request object associated with18 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.19+variable associated with the current application context. The tutorial20+will cover some more details of this later on.21 22 For the time being, all you have to know is that you can store information23 safely on the :data:`~flask.g` object.24 9 unmodified lines34 if not hasattr(g, 'sqlite_db'):35 g.sqlite_db = connect_db()36 return g.sqlite_db37 40-41-So now we know how to connect, but how do we properly disconnect? For38+Now you know how to connect, but how can you properly disconnect? For39 that, Flask provides us with the :meth:`~flask.Flask.teardown_appcontext`40 decorator. It's executed every time the application context tears down::41 42 @app.teardown_appcontext28 unmodified lines71 into a single Python module. You don't have to, and if your app :ref:`grows72 larger <larger-applications>`, it's a good idea not to.73 74 .. _example source:78- https://github.com/mitsuhiko/flask/tree/master/examples/flaskr/75+ https://github.com/pallets/flask/tree/master/examples/flaskr/modified:docs/tutorial/dbinit.rst+17 added-16 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. Such7 unmodified lines15 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 introduce19+requires that you 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.21+for you, to the application.22 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`::23+To do this, you can create a function and hook it into a :command:`flask`24+command that initializes the database. For now just take a look at the25+code segment below. A good place to add this function, and command, is26+just below the `connect_db` function in :file:`flaskr.py`::27 28 def init_db():29 db = get_db()30 with app.open_resource('schema.sql', mode='r') as f:3 unmodified lines34 @app.cli.command('initdb')35 def initdb_command():36 """Initializes the database."""37 init_db()37- print 'Initialized the database.'38+ print('Initialized the database.')39 40 The ``app.cli.command()`` decorator registers a new command with the41 :command:`flask` script. When the command executes, Flask will automatically41-create a 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 down42+create an application context which is bound to the right application.43+Within the function, you can then access :attr:`flask.g` and other things as44+you might expect. When the script ends, the application context tears down45 and the database connection is released.46 46-We want to keep an actual functions around that initializes the database,47+You will want to keep an actual function around that initializes the database,48 though, so that we can easily create databases in unit tests later on. (For49 more information see :ref:`testing`.)50 51 The :func:`~flask.Flask.open_resource` method of the application object52 is a convenient helper function that will open a resource that the53 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.54+location (the :file:`flaskr/flaskr` folder) and allows you to read from it.55+It is used in this example to execute a script on the database connection.56 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, we57+The connection object provided by SQLite can give you a cursor object.58+On that cursor, there is a method to execute a complete script. Finally, you59 only have to commit the changes. SQLite3 and other transactional60 databases will not commit unless you explicitly tell it to.61 62 Now, it is possible to create a database with the :command:`flask` script::63 63- flask --app=flaskr initdb64+ flask initdb65 Initialized the database.66 67 .. admonition:: Troubleshooting68 5 unmodified linesmodified:docs/tutorial/folders.rst+15 added-11 removed
1 unmodified line2 3 Step 0: Creating The Folders4 ============================5 6-Before we get started, let's create the folders needed for this6+Before getting started, you will need to create the folders needed for this7 application::8 9 /flaskr10+ /flaskr10- /static11- /templates11+ /static12+ /templates13 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.14+The application will be installed and run as Python package. This is the15+recommended way to install and run Flask applications. You will see exactly16+how to run ``flaskr`` later on in this tutorial. For now go ahead and create17+the applications directory structure. In the next few steps you will be18+creating the database schema as well as the main module.19 21-Continue with :ref:`tutorial-schema`.20+As a quick side note, the files inside of the :file:`static` folder are21+available to users of the application via HTTP. This is the place where CSS and22+JavaScript files go. Inside the :file:`templates` folder, Flask will look for23+`Jinja2`_ templates. You will see examples of this later on.24 25+For now you should continue with :ref:`tutorial-schema`.26+27 .. _Jinja2: http://jinja.pocoo.org/modified:docs/tutorial/index.rst+2 added-1 removed
13 unmodified lines14 If you want the full source code in advance or for comparison, check out15 the `example source`_.16 17 .. _example source:18- https://github.com/mitsuhiko/flask/tree/master/examples/flaskr/18+ 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+6 added-5 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.6 unmodified lines30 :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+108 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 involves 13+creating two new files; :file:`setup.py` and :file:`MANIFEST.in` in the 14+projects root directory. You also need to add an :file:`__init__.py` 15+file to make the :file:`flaskr/flaskr` directory a package. After these 16+changes, your code structure should be::17+18+ /flaskr19+ /flaskr20+ __init__.py21+ /static22+ /templates23+ flaskr.py24+ schema.sql25+ setup.py26+ MANIFEST.in27+28+The content of the ``setup.py`` file for ``flaskr`` is:29+30+.. sourcecode:: python31+32+ from setuptools import setup33+34+ setup(35+ name='flaskr',36+ packages=['flaskr'],37+ include_package_data=True,38+ install_requires=[39+ 'flask',40+ ],41+ )42+43+When using setuptools, it is also necessary to specify any special files44+that should be included in your package (in the :file:`MANIFEST.in`).45+In this case, the static and templates directories need to be included,46+as well as the schema. Create the :file:`MANIFEST.in` and add the47+following lines::48+49+ graft flaskr/templates50+ graft flaskr/static51+ include flaskr/schema.sql52+53+To simplify locating the application, add the following import statement 54+into this file, :file:`flaskr/__init__.py`:55+56+.. sourcecode:: python57+58+ from .flaskr import app59+60+This import statement brings the application instance into the top-level 61+of the application package. When it is time to run the application, the 62+Flask development server needs the location of the app instance. This 63+import statement simplifies the location process. Without it the export 64+statement a few steps below would need to be 65+``export FLASK_APP=flaskr.flaskr``.66+67+At this point you should be able to install the application. As usual, it68+is recommended to install your Flask application within a `virtualenv`_.69+With that said, go ahead and install the application with::70+71+ pip install --editable .72+73+The above installation command assumes that it is run within the projects 74+root directory, `flaskr/`. The `editable` flag allows editing 75+source code without having to reinstall the Flask app each time you make 76+changes. The flaskr app is now installed in your virtualenv (see output 77+of ``pip freeze``).78+79+With that out of the way, you should be able to start up the application.80+Do this with the following commands::81+82+ export FLASK_APP=flaskr83+ export FLASK_DEBUG=true84+ flask run85+86+(In case you are on Windows you need to use `set` instead of `export`).87+The :envvar:`FLASK_DEBUG` flag enables or disables the interactive debugger.88+*Never leave debug mode activated in a production system*, because it will89+allow users to execute code on the server!90+91+You will see a message telling you that server has started along with92+the address at which you can access it.93+94+When you head over to the server in your browser, you will get a 404 error95+because we don't have any views yet. That will be addressed a little later,96+but first, you should get the database working.97+98+.. admonition:: Externally Visible Server99+100+ Want your server to be publicly available? Check out the101+ :ref:`externally visible server <public-server>` section for more102+ information.103+104+Continue with :ref:`tutorial-dbcon`.105+106+.. _Click: http://click.pocoo.org107+.. _Python Packaging Guide: https://packaging.python.org108+.. _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+26 added-44 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+Now that the schema is in place, you can create the application module,7+:file:`flaskr.py`. This file should be placed inside of the8+:file:`flaskr/flaskr` folder. The first several lines of code in the9+application module are the needed import statements. After that there will be a10+few lines of configuration code. For small applications like ``flaskr``, it is11+possible to drop the configuration directly into the module. However, a cleaner12+solution is to create a separate ``.ini`` or ``.py`` file, load that, and13+import the values from there.14 14-First, we add the imports in :file:`flaskr.py`::15+Here are the import statements (in :file:`flaskr.py`)::16 17 # all the imports18 import os19 import sqlite320 from flask import Flask, request, session, g, redirect, url_for, abort, \21 render_template, flash22 22-Next, we can create our actual application and initialize it with the23-config from the same file in :file:`flaskr.py`::23+The next couple lines will create the actual application instance and24+initialize it with the config from the same file in :file:`flaskr.py`:25 25- # create our little application :)26- app = Flask(__name__)27- app.config.from_object(__name__)26+.. sourcecode:: python27 28+ app = Flask(__name__) # create the application instance :)29+ app.config.from_object(__name__) # load config from this file , flaskr.py30+31 # Load default config and override config from an environment variable32 app.config.update(dict(33 DATABASE=os.path.join(app.root_path, 'flaskr.db'),34 SECRET_KEY='development key',1 unmodified line36 PASSWORD='default'37 ))38 app.config.from_envvar('FLASKR_SETTINGS', silent=True)39 38-The :class:`~flask.Config` object works similarly to a dictionary so we39-can update it with new values.40+The :class:`~flask.Config` object works similarly to a dictionary, so it can be41+updated with new values.42 43 .. admonition:: Database Path44 45 Operating systems know the concept of a current working directory for10 unmodified lines56 :ref:`instance-folders` instead.57 58 Usually, it is a good idea to load a separate, environment-specific59 configuration file. Flask allows you to import multiple configurations and it58-will use the setting defined in the last import. This enables robust60+will use the setting defined in the last import. This enables robust61 configuration setups. :meth:`~flask.Config.from_envvar` can help achieve this.62 61-.. code-block:: python63+.. sourcecode:: python64 65 app.config.from_envvar('FLASKR_SETTINGS', silent=True)66 67 Simply define the environment variable :envvar:`FLASKR_SETTINGS` that points to7 unmodified lines75 76 The ``SECRET_KEY`` is needed to keep the client-side sessions secure.77 Choose that key wisely and as hard to guess and complex as possible.78 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+Lastly, you will add a method that allows for easy connections to the80+specified database. This can be used to open a connection on request and81 also from the interactive Python shell or a script. This will come in80-handy later. We create a simple database connection through SQLite and82+handy later. You can create a simple database connection through SQLite and83 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 of84+This allows the rows to be treated as if they were dictionaries instead of85 tuples.86 85-::87+.. sourcecode:: python88 89 def connect_db():90 """Connects to the specific database."""91 rv = sqlite3.connect(app.config['DATABASE'])92 rv.row_factory = sqlite3.Row93 return rv94 93-With that out of the way, you should be able to start up the application94-without problems. Do this with the following command::95+In the next section you will see how to run the application.96 96- flask --app=flaskr --debug run97-98-The :option:`--debug` flag enables or disables the interactive debugger. *Never99-leave debug mode activated in a production system*, because it will allow100-users to execute code on the server!101-102-You will see a message telling you that server has started along with103-the address at which you can access it.104-105-When you head over to the server in your browser, you will get a 404 error106-because we don't have any views yet. We will focus on that a little later,107-but first, we should get the database working.108-109-.. admonition:: Externally Visible Server110-111- Want your server to be publicly available? Check out the112- :ref:`externally visible server <public-server>` section for more113- information.114-115-Continue with :ref:`tutorial-dbcon`.97+Continue with :ref:`tutorial-packaging`.modified:docs/tutorial/templates.rst+10 added-9 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.43 unmodified lines57 -----------------58 59 This template extends the :file:`layout.html` template from above to display the60 messages. Note that the ``for`` loop iterates over the messages we 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:61+in with the :func:`~flask.render_template` function. Notice that the form is62+configured to submit to the `add_entry` view function and use ``POST`` as63+HTTP method:64 65 .. sourcecode:: html+jinja66 67 {% extends "layout.html" %}10 unmodified lines78 </form>79 {% endif %}80 <ul class=entries>81 {% for entry in entries %}81- <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}82+ <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}</li>83 {% else %}83- <li><em>Unbelievable. No entries here so far</em>84+ <li><em>Unbelievable. No entries here so far</em></li>85 {% endfor %}86 </ul>87 {% endblock %}88 24 unmodified linesmodified:docs/tutorial/testing.rst+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+31 added-12 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:8 9 Show Entries10 ------------11 12 This view shows all the entries stored in the database. It listens on the13 root of the application and will select title and text from the database.14 The one with the highest id (the newest entry) will be on top. The rows15-returned from the cursor look a bit like tuples because we are using15+returned from the cursor look a bit like dictionaries because we are using16 the :class:`sqlite3.Row` row factory.17 18-The view function will pass the entries as dictionaries to the19-:file:`show_entries.html` template and return the rendered one::18+The view function will pass the entries to the :file:`show_entries.html`19+template and return the rendered one::20 21 @app.route('/')22 def show_entries():23 db = get_db()5 unmodified lines29 -------------30 31 This view lets the user add new entries if they are logged in. This only32 responds to ``POST`` requests; the actual form is shown on the33-`show_entries` page. If everything worked out well, we will33+`show_entries` page. If everything worked out well, it will34 :func:`~flask.flash` an information message to the next request and35 redirect back to the `show_entries` page::36 37 @app.route('/add', methods=['POST'])6 unmodified lines44 db.commit()45 flash('New entry was successfully posted')46 return redirect(url_for('show_entries'))47 48-Note that we check that the user is logged in here (the `logged_in` key is49-present in the session and ``True``).48+Note that this view checks that the user is logged in (that is, if the49+`logged_in` key is present in the session and ``True``).50 51 .. admonition:: Security Note52 53 Be sure to use question marks when building SQL statements, as done in the26 unmodified lines80 return redirect(url_for('show_entries'))81 return render_template('login.html', error=error)82 83 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` method84+again. There is a neat trick here: if you use the :meth:`~dict.pop` method85 of the dict and pass a second parameter to it (the default), the method86 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.87+key is not in there. This is helpful because now it is not necessary to88+check if the user was logged in.89 90 ::91 92 @app.route('/logout')1 unmodified line94 session.pop('logged_in', None)95 flash('You were logged out')96 return redirect(url_for('show_entries'))97 98+.. admonition:: Security Note99+100+ Passwords should never be stored in plain text in a production101+ system. This tutorial uses plain text passwords for simplicity. If you102+ 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 a104+ database or file.105+106+ Fortunately, there are Flask extensions for the purpose of107+ hashing passwords and verifying passwords against hashes, so adding108+ this functionality is fairly straight forward. There are also109+ many general python libraries that can be used for hashing.110+111+ You can find a list of recommended Flask extensions112+ `here <http://flask.pocoo.org/extensions/>`_113+114+115 Continue with :ref:`tutorial-templates`.116+117+.. _hashed and salted: https://blog.codinghorror.com/youre-probably-storing-passwords-incorrectly/modified:docs/advanced_foreword.rst+4 added-18 removed
44 unmodified lines45 46 Flask is no different from any other framework in that you the developer must47 build with caution, watching for exploits when building to your requirements.48 49-The Status of Python 350-----------------------49+Python 3 Support in Flask50+-------------------------51 52-Currently the Python community is in the process of improving libraries to53-support the new iteration of the Python programming language. While the54-situation is greatly improving there are still some issues that make it55-hard for users to switch over to Python 3 just now. These problems are56-partially caused by changes in the language that went unreviewed for too57-long, partially also because we have not quite worked out how the lower-58-level API should change to account for the Unicode differences in Python 3.52+Flask, its dependencies, and most Flask extensions all support Python 3.53+If you want to use Flask with Python 3 have a look at the :ref:`python3-support` page.54 60-We strongly recommend using Python 2.7 with activated Python 361-warnings during development. If you plan on upgrading to Python 3 in the62-near future we strongly recommend that you read `How to write forwards63-compatible Python code64-<http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/>`_.65-66-If you do want to dive into Python 3 already have a look at the67-:ref:`python3-support` page.68-55 Continue to :ref:`installation` or the :ref:`quickstart`.modified:docs/api.rst+6 added-73 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 you157 unmodified lines232 233 It's now also possible to use the ``in`` operator on it to see if an234 attribute is defined and it yields all keys on iteration.235 292- As of 1.0 you can use :meth:`pop` and :meth:`setdefault` in the same236+ As of 0.11 you can use :meth:`pop` and :meth:`setdefault` in the same237 way you would use them on a dictionary.238 239 This is a proxy. See :ref:`notes-on-proxies` for more information.240 18 unmodified lines259 .. autofunction:: has_app_context260 261 .. autofunction:: url_for262 319-.. function:: abort(code)263+.. autofunction:: abort264 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-265 .. autofunction:: redirect266 267 .. autofunction:: make_response268 419 unmodified lines688 `string` accepts any text without a slash (the default)689 `int` accepts integers690 `float` like `int` but for floating point values691 `path` like the default but also accepts slashes692+`any` matches one of the items provided693+`uuid` accepts UUID strings694 =========== ===============================================695 696 Custom converters can be defined using :attr:`flask.Flask.url_map`.697 131 unmodified lines829 830 Marks a function so that an instance of :class:`ScriptInfo` is passed831 as first argument to the click callback.832 893-.. autofunction:: script_info_option894-895- A special decorator that informs a click callback to be passed the896- script info object as first argument. This is normally not useful897- unless you implement very special commands like the run command which898- does not want the application to be loaded yet.899-833 .. autodata:: run_command834 835 .. autodata:: shell_commandmodified:docs/appcontext.rst+7 added-2 removed
24 unmodified lines25 - any code can get hold of these objects at any time.26 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 an29+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.33 34 The application context is what powers the :data:`~flask.current_app`38 unmodified lines73 The application context is also used by the :func:`~flask.url_for`74 function in case a ``SERVER_NAME`` was configured. This allows you to75 generate URLs even in the absence of a request.76 77+If no request context has been pushed and an application context has78+not been explicitly set, a ``RuntimeError`` will be raised. ::79+80+ RuntimeError: Working outside of application context.81+82 Locality of the Context83 -----------------------84 85 The application context is created and destroyed as necessary. It never53 unmodified linesmodified:docs/becomingbig.rst+2 added-2 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 14 unmodified lines34 35 The :class:`~flask.Flask` class has many methods designed for subclassing. You36 can quickly add or customize behavior by subclassing :class:`~flask.Flask` (see37 the linked method docs) and using that subclass wherever you instantiate an38-application class. This works well with :ref:`app-factories`.38+application class. This works well with :ref:`app-factories`. See :doc:`/patterns/subclassing` for an example.39 40 Wrap with middleware.41 ---------------------42 59 unmodified linesmodified:docs/blueprints.rst+15 added-6 removed
174 unmodified lines175 the `template_folder` parameter to the :class:`Blueprint` constructor::176 177 admin = Blueprint('admin', __name__, template_folder='templates')178 179-As for static files, the path can be absolute or relative to the blueprint180-resource folder. The template folder is added to the searchpath of181-templates but with a lower priority than the actual application's template182-folder. That way you can easily override templates that a blueprint183-provides in the actual application.179+For static files, the path can be absolute or relative to the blueprint180+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. 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.189+190+191 So if you have a blueprint in the folder ``yourapplication/admin`` and you192 want to render the template ``'admin/index.html'`` and you have provided193 ``templates`` as a `template_folder` you will have to create a file like188-this: :file:`yourapplication/admin/templates/admin/index.html`.194+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. 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::47 unmodified linesmodified:docs/cli.rst+91 added-90 removed
1 unmodified line2 3 Command Line Interface4 ======================5 6-.. versionadded:: 1.06+.. versionadded:: 0.117 8 .. currentmodule:: flask9 10-One of the nice new features in Flask 1.0 is the built-in integration of10+One of the nice new features in Flask 0.11 is the built-in integration of11 the `click <http://click.pocoo.org/>`_ command line interface. This12 enables a wide range of new features for the Flask ecosystem and your own13 applications.14 15 Basic Usage16 -----------17 18-After installation of Flask you will now find a :command:`flask` script installed19-into your virtualenv. If you don't want to install Flask or you have a20-special use-case you can also use ``python -m flask`` to accomplish exactly21-the same.18+After installation of Flask you will now find a :command:`flask` script19+installed into your virtualenv. If you don't want to install Flask or you20+have a special use-case you can also use ``python -m flask`` to accomplish21+exactly the same.22 23 The way this script works is by providing access to all the commands on24 your Flask application's :attr:`Flask.cli` instance as well as some25 built-in commands that are always there. Flask extensions can also26 register more commands there if they desire so.27 28-For the :command:`flask` script to work, an application needs to be discovered.29-The two most common ways are either an environment variable30-(``FLASK_APP``) or the :option:`--app` / :option:`-a` parameter. It should be the31-import path for your application or the path to a Python file. In the32-latter case Flask will attempt to setup the Python path for you33-automatically and discover the module name but that might not always work.28+For the :command:`flask` script to work, an application needs to be29+discovered. This is achieved by exporting the ``FLASK_APP`` environment30+variable. It can be either set to an import path or to a filename of a31+Python module that contains a Flask application.32 33 In that imported file the name of the app needs to be called ``app`` or36-optionally be specified after a colon.34+optionally be specified after a colon. For instance35+``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`` this is39-how it can be run.38+Given a :file:`hello.py` file with the application in it named ``app``39+this is how it can be run.40 41 Environment variables (On Windows use ``set`` instead of ``export``)::42 43 export FLASK_APP=hello44 flask run45 46-Parameters::46+Or with a filename::47 48- flask --app=hello run48+ export FLASK_APP=/path/to/hello.py49+ flask run50 50-File names::51-52- flask --app=hello.py run53-51 Virtualenv Integration52 ----------------------53 54 If you are constantly working with a virtualenv you can also put the55 ``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 65-The :command:`flask` script can be run with :option:`--debug` or :option:`--no-debug` to66-automatically flip the debug flag of the application. This can also be67-configured by setting ``FLASK_DEBUG`` to ``1`` or ``0``.74+The :command:`flask` script can also be instructed to enable the debug75+mode of the application automatically by exporting ``FLASK_DEBUG``. If76+set to ``1`` debug is enabled or ``0`` disables it::77 78+ export FLASK_DEBUG=179+80 Running a Shell81 ---------------82 83 To run an interactive Python shell you can use the ``shell`` command::84 74- flask --app=hello shell85+ flask shell86 87 This will start up an interactive Python shell, setup the correct88 application context and setup the local variables in the shell. This is89 done by invoking the :meth:`Flask.make_shell_context` method of the6 unmodified lines96 easily. Flask uses `click`_ for the command interface which makes97 creating custom commands very easy. For instance if you want a shell98 command to initialize the database you can do this::99 100+ import click101 from flask import Flask102 103 app = Flask(__name__)104 105 @app.cli.command()106 def initdb():107 """Initialize the database."""96- print 'Init the db'108+ click.echo('Init the db')109 110 The command will then show up on the command line::111 100- $ flask -a hello.py initdb112+ $ flask initdb113 Init the db114 115 Application Context116 -------------------16 unmodified lines133 Factory Functions134 -----------------135 136 In case you are using factory functions to create your application (see125-:ref:`app-factories`) you will discover that the :command:`flask` command cannot126-work with them directly. Flask won't be able to figure out how to137+:ref:`app-factories`) you will discover that the :command:`flask` command138+cannot work with them directly. Flask won't be able to figure out how to139 instantiate your application properly by itself. Because of this reason140 the recommendation is to create a separate file that instantiates129-applications. This is by far not the only way to make this work. Another130-is the :ref:`custom-scripts` support.141+applications. This is not the only way to make this work. Another is the142+:ref:`custom-scripts` support.143 144 For instance if you have a factory function that creates an application145 from a filename you could make a separate file that creates such an146 application from an environment variable.3 unmodified lines150 import os151 from yourapplication import create_app152 app = create_app(os.environ['YOURAPPLICATION_CONFIG'])153 142-Once this has happened you can make the flask command automatically pick143-it up::154+Once this has happened you can make the :command:`flask` command automatically155+pick it up::156 157 export YOURAPPLICATION_CONFIG=/path/to/config.cfg158 export FLASK_APP=/path/to/autoapp.py159 3 unmodified lines163 164 Custom Scripts165 --------------166 155-While the most common way is to use the :command:`flask` command, you can also156-make your own "driver scripts". Since Flask uses click for the scripts157-there is no reason you cannot hook these scripts into any click167+While the most common way is to use the :command:`flask` command, you can168+also make your own "driver scripts". Since Flask uses click for the169+scripts there is no reason you cannot hook these scripts into any click170 application. There is one big caveat and that is, that commands171 registered to :attr:`Flask.cli` will expect to be (indirectly at least)172 launched from a :class:`flask.cli.FlaskGroup` click group. This is173 necessary so that the commands know which Flask application they have to174 work with.175 176 To understand why you might want custom scripts you need to understand how165-click finds and executes the Flask application. If you use the :command:`flask`166-script you specify the application to work with on the command line or167-environment variable as an import name. This is simple but it has some168-limitations. Primarily it does not work with application factory169-functions (see :ref:`app-factories`).177+click finds and executes the Flask application. If you use the178+:command:`flask` script you specify the application to work with on the179+command line or environment variable as an import name. This is simple180+but it has some limitations. Primarily it does not work with application181+factory functions (see :ref:`app-factories`).182 183 With a custom script you don't have this problem as you can fully184 customize how the application will be created. This is very useful if you185 write reusable applications that you want to ship to users and they should186 be presented with a custom management script.187 176-If you are used to writing click applications this will look familiar but177-at the same time, slightly different because of how commands are loaded.178-We won't go into detail now about the differences but if you are curious179-you can have a look at the :ref:`script-info-object` section to learn all180-about it.181-188 To explain all of this, here is an example :file:`manage.py` script that189 manages a hypothetical wiki application. We will go through the details190 afterwards::191 192+ import os193 import click187- from flask.cli import FlaskGroup, script_info_option194+ from flask.cli import FlaskGroup195 196 def create_wiki_app(info):197 from yourwiki import create_app191- config = info.data.get('config') or 'wikiconfig.py'192- return create_app(config=config)198+ return create_app(199+ config=os.environ.get('WIKI_CONFIG', 'wikiconfig.py'))200 201 @click.group(cls=FlaskGroup, create_app=create_wiki_app)195- @script_info_option('--config', script_info_key='config')196- def cli(**params):202+ def cli():203 """This is a management script for the wiki application."""204 205 if __name__ == '__main__':206 cli()2 unmodified lines209 step.210 211 1. First we import the ``click`` library as well as the click extensions212 from the ``flask.cli`` package. Primarily we are here interested207- in the :class:`~flask.cli.FlaskGroup` click group and the208- :func:`~flask.cli.script_info_option` decorator.213+ in the :class:`~flask.cli.FlaskGroup` click group.214 2. The next thing we do is defining a function that is invoked with the210- script info object (:ref:`script-info-object`) from Flask and its215+ script info object (:class:`~flask.cli.ScriptInfo`) from Flask and its216 purpose is to fully import and create the application. This can217 either directly import an application object or create it (see213- :ref:`app-factories`).214-215- What is ``info.data``? It's a dictionary of arbitrary data on the216- script info that can be filled by options or through other means. We217- will come back to this later.218+ :ref:`app-factories`). In this case we load the config from an219+ environment variable.220 3. Next step is to create a :class:`FlaskGroup`. In this case we just221 make an empty function with a help doc string that just does nothing222 and then pass the ``create_wiki_app`` function as a factory function.223 224 Whenever click now needs to operate on a Flask application it will225 call that function with the script info and ask for it to be created.224-4. In step 2 you could see that the config is passed to the actual225- creation function. This config comes from the :func:`script_info_option`226- decorator for the main script. It accepts a :option:`--config` option and227- then stores it in the script info so we can use it to create the228- application.229-5. All is rounded up by invoking the script.226+4. All is rounded up by invoking the script.227 231-.. _script-info-object:228+CLI Plugins229+-----------230 233-The Script Info234----------------231+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 plugins233+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 236-The Flask script integration might be confusing at first, but there is a reason237-why it's done this way. The reason for this is that Flask wants to238-both provide custom commands to click as well as not loading your239-application unless it has to. The reason for this is added flexibility.237+Example :file:`setup.py`::238 241-This way an application can provide custom commands, but even in the242-absence of an application the :command:`flask` script is still operational on a243-basic level. In addition to that it means that the individual commands244-have the option to avoid creating an instance of the Flask application245-unless required. This is very useful as it allows the server commands for246-instance to load the application on a first request instead of247-immediately, therefore giving a better debug experience.239+ from setuptools import setup240 249-All of this is provided through the :class:`flask.cli.ScriptInfo` object250-and some helper utilities around. The basic way it operates is that when251-the :class:`flask.cli.FlaskGroup` executes as a script it creates a script252-info and keeps it around. From that point onwards modifications on the253-script info can be done through click options. To simplify this pattern254-the :func:`flask.cli.script_info_option` decorator was added.241+ setup(242+ name='flask-my-extension',243+ ...244+ entry_points='''245+ [flask.commands]246+ my-command=mypackage.commands:cli247+ ''',248+ )249 256-Once Flask actually needs the individual Flask application it will invoke257-the :meth:`flask.cli.ScriptInfo.load_app` method. This happens when the258-server starts, when the shell is launched or when the script looks for an259-application-provided click command.250+Inside :file:`mypackage/commands.py` you can then export a Click object::251+252+ import click253+254+ @click.command()255+ def cli():256+ """This is an example command."""257+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.modified:docs/conf.py+59 added-49 removed
8 unmodified lines9 # autogenerated file.10 #11 # All configuration values have a default; values that are commented out12 # serve to show the default.13+from __future__ import print_function14+import os15+import sys16+import pkg_resources17+import time18+import datetime19 14-import sys, os20+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.join(os.path.dirname(__file__), '_themes'))26+sys.path.append(os.path.dirname(__file__))27 28 # -- General configuration -----------------------------------------------------29 30 # If your documentation needs a minimal Sphinx version, state it here.31 #needs_sphinx = '1.0'32 33 # Add any Sphinx extension module names here, as strings. They can be extensions34 # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.35+extensions = [36+ 'sphinx.ext.autodoc',29-extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx',30- 'flaskdocext']37+ 'sphinx.ext.intersphinx',38+ 'flaskdocext'39+]40 41 # Add any paths that contain templates here, relative to this directory.42 templates_path = ['_templates']43 7 unmodified lines51 master_doc = 'index'52 53 # General information about the project.54 project = u'Flask'46-copyright = u'2015, Armin Ronacher'55+copyright = u'2010 - {0}, Armin Ronacher'.format(BUILD_DATE.year)56 57 # The version info for the project you're documenting, acts as replacement for58 # |version| and |release|, also used in various other places throughout the59 # built documents.51-import pkg_resources60 try:61 release = pkg_resources.get_distribution('Flask').version62 except pkg_resources.DistributionNotFound:55- print 'To build the documentation, The distribution information of Flask'56- print 'Has to be available. Either install the package into your'57- print 'development environment or run "setup.py develop" to setup the'58- print 'metadata. A virtualenv is recommended!'63+ print('Flask must be installed to build the documentation.')64+ print('Install from source using `pip install -e .` in a virtualenv.')65 sys.exit(1)60-del pkg_resources66 67 if 'dev' in release:63- release = release.split('dev')[0] + 'dev'68+ release = ''.join(release.partition('dev')[:2])69+70 version = '.'.join(release.split('.')[:2])71 72 # The language for content autogenerated by Sphinx. Refer to documentation73 # for a list of supported languages.30 unmodified lines104 # -- Options for HTML output ---------------------------------------------------105 106 # The theme to use for HTML and HTML Help pages. Major themes that come with107 # Sphinx are currently 'default' and 'sphinxdoc'.102-html_theme = 'flask'108+# html_theme = 'default'109 110 # Theme options are theme-specific and customize the look and feel of a theme111 # further. For a list of options available for each theme, see the112 # documentation.107-html_theme_options = {108- 'touch_icon': 'touch-icon.png'109-}113+# html_theme_options = {}114 115 # Add any paths that contain custom themes here, relative to this directory.116 html_theme_path = ['_themes']117 10 unmodified lines128 129 # The name of an image file (within the static path) to use as favicon of the130 # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32131 # pixels large.128-html_favicon = "flask-favicon.ico"132+html_favicon = '_static/flask-favicon.ico'133 134 # Add any paths that contain custom static files (such as style sheets) here,135 # relative to this directory. They are copied after the builtin static files,136 # so a file named "default.css" will overwrite the builtin "default.css".8 unmodified lines145 #html_use_smartypants = True146 147 # Custom sidebar templates, maps document names to template names.148 html_sidebars = {145- 'index': ['sidebarintro.html', 'sourcelink.html', 'searchbox.html'],146- '**': ['sidebarlogo.html', 'localtoc.html', 'relations.html',147- 'sourcelink.html', 'searchbox.html']149+ 'index': [150+ 'sidebarintro.html',151+ 'sourcelink.html',152+ 'searchbox.html'153+ ],154+ '**': [155+ 'sidebarlogo.html',156+ 'localtoc.html',157+ 'relations.html',158+ 'sourcelink.html',159+ 'searchbox.html'160+ ]161 }162 163 # Additional templates that should be rendered to pages, maps page names to164 # template names.33 unmodified lines198 199 # Grouping the document tree into LaTeX files. List of tuples200 # (source start file, target name, title, author, documentclass [howto/manual]).201 latex_documents = [189- ('latexindex', 'Flask.tex', u'Flask Documentation',190- u'Armin Ronacher', 'manual'),202+ ('latexindex', 'Flask.tex', u'Flask Documentation', u'Armin Ronacher', 'manual'),203 ]204 205 # Documents to append as an appendix to all manuals.206 #latex_appendices = []1 unmodified line208 # If false, no module index is generated.209 latex_use_modindex = False210 211 latex_elements = {200- 'fontpkg': r'\usepackage{mathpazo}',201- 'papersize': 'a4paper',202- 'pointsize': '12pt',203- 'preamble': r'\usepackage{flaskstyle}'212+ 'fontpkg': r'\usepackage{mathpazo}',213+ 'papersize': 'a4paper',214+ 'pointsize': '12pt',215+ 'preamble': r'\usepackage{flaskstyle}'216 }217 latex_use_parts = True218 219 latex_additional_files = ['flaskstyle.sty', 'logo.pdf']13 unmodified lines233 234 # The scheme of the identifier. Typical schemes are ISBN or URL.235 #epub_scheme = ''236 225-# The unique identifier of the text. This can be a ISBN number237+# The unique identifier of the text. This can be an ISBN number238 # or the project homepage.239 #epub_identifier = ''240 241 # A unique identification for the text.13 unmodified lines255 # The depth of the table of contents in toc.ncx.256 #epub_tocdepth = 3257 258 intersphinx_mapping = {247- 'https://docs.python.org/dev': None,248- 'http://werkzeug.pocoo.org/docs/': None,249- 'http://click.pocoo.org/': None,250- 'http://jinja.pocoo.org/docs/': None,251- 'http://www.sqlalchemy.org/docs/': None,252- 'https://wtforms.readthedocs.org/en/latest/': None,253- 'https://pythonhosted.org/blinker/': None259+ 'python': ('https://docs.python.org/3/', None),260+ 'werkzeug': ('http://werkzeug.pocoo.org/docs/', None),261+ 'click': ('http://click.pocoo.org/', None),262+ 'jinja': ('http://jinja.pocoo.org/docs/', None),263+ 'sqlalchemy': ('https://docs.sqlalchemy.org/en/latest/', None),264+ 'wtforms': ('https://wtforms.readthedocs.io/en/latest/', None),265+ 'blinker': ('https://pythonhosted.org/blinker/', None)266 }267 256-pygments_style = 'flask_theme_support.FlaskyStyle'257-258-# fall back if theme is not there268 try:269 __import__('flask_theme_support')261-except ImportError, e:262- print '-' * 74263- print 'Warning: Flask themes unavailable. Building with default theme'264- print 'If you want the Flask themes, run this command and build again:'265- print266- print ' git submodule update --init'267- print '-' * 74270+ pygments_style = 'flask_theme_support.FlaskyStyle'271+ html_theme = 'flask'272+ html_theme_options = {273+ 'touch_icon': 'touch-icon.png'274+ }275+except ImportError:276+ print('-' * 74)277+ print('Warning: Flask themes unavailable. Building with default theme')278+ print('If you want the Flask themes, run this command and build again:')279+ print()280+ print(' git submodule update --init')281+ print('-' * 74)282 269- pygments_style = 'tango'270- html_theme = 'default'271- html_theme_options = {}283 273-284 # unwrap decorators285 def unwrap_decorators():286 import sphinx.util.inspect as inspect287 import functools15 unmodified linesmodified:docs/config.rst+26 added-10 removed
42 unmodified lines43 DEBUG=True,44 SECRET_KEY='...'45 )46 47+.. admonition:: Debug Mode with the ``flask`` Script48+49+ If you use the :command:`flask` script to start a local development50+ server, to enable the debug mode, you need to export the ``FLASK_DEBUG``51+ environment variable before running the server::52+53+ $ export FLASK_DEBUG=154+ $ flask run55+56+ (On Windows you need to use ``set`` instead of ``export``).57+ 58+ ``app.debug`` and ``app.config['DEBUG']`` are not compatible with 59+ the :command:`flask` script. They only worked when using ``Flask.run()``60+ method.61+ 62 Builtin Configuration Values63 ----------------------------64 65 The following configuration values are used internally by Flask:66 67 .. tabularcolumns:: |p{6.5cm}|p{8.5cm}|68 69 ================================= =========================================55-``DEBUG`` enable/disable debug mode70+``DEBUG`` enable/disable debug mode when using 71+ ``Flask.run()`` method to start server72 ``TESTING`` enable/disable testing mode73 ``PROPAGATE_EXCEPTIONS`` explicitly enable or disable the74 propagation of exceptions. If not set or75 explicitly set to ``None`` this is116 unmodified lines192 caches. You can override the default193 behavior by changing this variable.194 This is not recommended but might give195 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)196+ cost of cacheability.197+``JSONIFY_PRETTYPRINT_REGULAR`` If this is set to ``True`` or the Flask app198+ is running in debug mode, jsonify responses199+ will be pretty printed.200+``JSONIFY_MIMETYPE`` MIME type used for jsonify responses.201 ``TEMPLATES_AUTO_RELOAD`` Whether to check for modifications of202 the template source and reload it203 automatically. By default the value is204 ``None`` which means that Flask checks49 unmodified lines254 255 .. versionadded:: 0.10256 ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_PRETTYPRINT_REGULAR``257 243-.. versionadded:: 1.0258+.. versionadded:: 0.11259 ``SESSION_REFRESH_EACH_REQUEST``, ``TEMPLATES_AUTO_RELOAD``,260 ``LOGGER_HANDLER_POLICY``, ``EXPLAIN_TEMPLATE_LOADING``261 262 Configuring from Files12 unmodified lines275 app.config.from_envvar('YOURAPPLICATION_SETTINGS')276 277 This first loads the configuration from the278 `yourapplication.default_settings` module and then overrides the values264-with the contents of the file the :envvar:``YOURAPPLICATION_SETTINGS``279+with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS`280 environment variable points to. This environment variable can be set on281 Linux or OS X with the export command in the shell before starting the282 server::283 39 unmodified lines323 2. Do not write code that needs the configuration at import time. If you324 limit yourself to request-only accesses to the configuration you can325 reconfigure the object later on as needed.326 327+.. _config-dev-prod:328 329 Development / Production330 ------------------------331 13 unmodified lines345 there are alternative ways as well. For example you could use imports or346 subclassing.347 348 What is very popular in the Django world is to make the import explicit in333-the config file by adding an ``from yourapplication.default_settings349+the config file by adding ``from yourapplication.default_settings350 import *`` to the top of the file and then overriding the changes by hand.351 You could also inspect an environment variable like352 ``YOURAPPLICATION_MODE`` and set that to `production`, `development` etc353 and import different hardcoded files based on that.126 unmodified linesmodified:docs/errorhandling.rst+55 added-13 removed
26 unmodified lines27 28 But there is more you can do, and we will cover some better setups to deal29 with errors.30 31+Error Logging Tools32+-------------------33+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+<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 local42+variables for debugging, and sends you mails based on new errors or43+frequency thresholds.44+45+To use Sentry you need to install the `raven` client::46+47+ $ pip install raven48+49+And then add this to your Flask app::50+51+ from raven.contrib.flask import Sentry52+ sentry = Sentry(app, dsn='YOUR_DSN_HERE')53+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+59+ def create_app():60+ app = Flask(__name__)61+ sentry.init_app(app)62+ ...63+ return app64+65+The `YOUR_DSN_HERE` value needs to be replaced with the DSN value you get66+from your Sentry installation.67+68+Afterwards failures are automatically reported to Sentry and from there69+you can receive error notifications.70+71 .. _error-handlers:72 73 Error handlers74 --------------1 unmodified line76 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 for40-routes they are registered for exceptions that are rised while trying to80+routes, they are registered for exceptions that are raised while trying to81 do something else.82 83 Registering84 ```````````3 unmodified lines88 89 @app.errorhandler(werkzeug.exceptions.BadRequest)90 def handle_bad_request(e):91 return 'bad request!'52- 92+93 app.register_error_handler(400, lambda e: 'bad request!')94 95 Those two ways are equivalent, but the first one is more clear and leaves96 you with a function to call on your whim (and in tests). Note that97 :exc:`werkzeug.exceptions.HTTPException` subclasses like98 :exc:`~werkzeug.exceptions.BadRequest` from the example and their HTTP codes59-are interchangable when handed to the registration methods or decorator99+are interchangeable when handed to the registration methods or decorator100 (``BadRequest.code == 400``).101 62-You are however not limited to a :exc:`~werkzeug.exceptions.HTTPException`63-or its code but can register a handler for every exception class you like.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.105 65-.. versionchanged:: 1.0106+.. versionchanged:: 0.11107 67- Errorhandlers are now prioritized by specifity instead of the order they're68- registered in.108+ Errorhandlers are now prioritized by specificity of the exception classes109+ they are registered for instead of the order they are registered in.110 111 Handling112 ````````113 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.117 77-E.g. if a instance of :exc:`ConnectionRefusedError` is raised, and a handler118+E.g. if an instance of :exc:`ConnectionRefusedError` is raised, and a handler119 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.122 47 unmodified lines170 -----------------171 172 Even if you get mails, you probably also want to log warnings. It's a173 good idea to keep as much information around that might be required to133-debug a problem. By default as of Flask 1.0, errors are logged to your174+debug a problem. By default as of Flask 0.11, errors are logged to your175 webserver's log automatically. Warnings however are not. Please note176 that Flask itself will not issue any warnings in the core system, so it's177 your responsibility to warn in the code if something seems odd.178 36 unmodified lines215 A formatter can be instantiated with a format string. Note that216 tracebacks are appended to the log entry automatically. You don't have to217 do that in the log formatter format string.218 178-Here some example setups:219+Here are some example setups:220 221 Email222 `````223 51 unmodified lines275 +------------------+----------------------------------------------------+276 | ``%(lineno)d`` | Source line number where the logging call was |277 | | issued (if available). |278 +------------------+----------------------------------------------------+238-| ``%(asctime)s`` | Human-readable time when the LogRecord` was |239-| | created. By default this is of the form |279+| ``%(asctime)s`` | Human-readable time when the |280+| | :class:`~logging.LogRecord` was created. |281+| | By default this is of the form |282 | | ``"2003-07-08 16:49:45,896"`` (the numbers after |283 | | the comma are millisecond portion of the time). |284 | | This can be changed by subclassing the formatter |285 | | and overriding the |109 unmodified linesmodified:docs/extensiondev.rst+14 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-38-But how do extensions look like themselves? An extension has to ensure32+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 aid36 unittests and to support multiple configurations. Because of that it is316 unmodified lines353 extension author would like to move beyond the project, the project should354 find a new maintainer including full source hosting transition and PyPI355 access. If no maintainer is available, give access to the Flask core team.356 1. An approved Flask extension must provide exactly one package or module363- named ``flask_extensionname``. They might also reside inside a364- ``flaskext`` namespace packages though this is discouraged now.357+ named ``flask_extensionname``.358 2. It must ship a testing suite that can either be invoked with ``make test``359 or ``python setup.py test``. For test suites invoked with ``make360 test`` the extension has to ensure that all dependencies for the test361 are installed automatically. If tests are invoked with ``python setup.py24 unmodified lines386 10. An extension currently has to support Python 2.6 as well as387 Python 2.7388 389 397-.. _ext-import-transition:398-390 Extension Import Transition391 ---------------------------392 402-For a while we recommended using namespace packages for Flask extensions.403-This turned out to be problematic in practice because many different404-competing namespace package systems exist and pip would automatically405-switch between different systems and this caused a lot of problems for406-users.393+In early versions of Flask we recommended using namespace packages for Flask394+extensions, of the form ``flaskext.foo``. This turned out to be problematic in395+practice because it meant that multiple ``flaskext`` packages coexist.396+Consequently we have recommended to name extensions ``flask_foo`` over397+``flaskext.foo`` for a long time.398 408-Instead we now recommend naming packages ``flask_foo`` instead of the now409-deprecated ``flaskext.foo``. Flask 0.8 introduces a redirect import410-system that lets uses import from ``flask.ext.foo`` and it will try411-``flask_foo`` first and if that fails ``flaskext.foo``.399+Flask 0.8 introduced a redirect import system as a compatibility aid for app400+developers: Importing ``flask.ext.foo`` would try ``flask_foo`` and401+``flaskext.foo`` in that order.402 413-Flask extensions should urge users to import from ``flask.ext.foo``414-instead of ``flask_foo`` or ``flaskext_foo`` so that extensions can415-transition to the new package name without affecting users.403+As of Flask 0.11, most Flask extensions have transitioned to the new naming404+schema. The ``flask.ext.foo`` compatibility alias is still in Flask 0.11 but is405+now deprecated -- you should use ``flask_foo``.406 407 418-.. _OAuth extension: http://pythonhosted.org/Flask-OAuth/408+.. _OAuth extension: https://pythonhosted.org/Flask-OAuth/409 .. _mailinglist: http://flask.pocoo.org/mailinglist/410 .. _IRC channel: http://flask.pocoo.org/community/irc/modified:docs/extensions.rst+14 added-4 removed
1+.. _extensions:2+3 Flask Extensions4 ================5 6 Flask extensions extend the functionality of Flask in various different12 unmodified lines19 20 Extensions typically have documentation that goes along that shows how to21 use it. There are no general rules in how extensions are supposed to22 behave but they are imported from common locations. If you have an21-extension called ``Flask-Foo`` or ``Foo-Flask`` it will be always22-importable from ``flask.ext.foo``::23+extension called ``Flask-Foo`` or ``Foo-Flask`` it should be always24+importable from ``flask_foo``::25 24- from flask.ext import foo26+ import flask_foo27 28+Building Extensions29+-------------------30+31+While `Flask Extension Registry`_ contains many Flask extensions, you may not find32+an extension that fits your need. If this is the case, you can always create your own. 33+Consider reading :ref:`extension-dev` to develop your own Flask extension.34+35 Flask Before 0.836 ----------------37 38 If you are using Flask 0.7 or earlier the :data:`flask.ext` package will not13 unmodified lines52 53 Once the ``flaskext_compat`` module is activated the :data:`flask.ext` will54 exist and you can start importing from there.55 56+57 .. _Flask Extension Registry: http://flask.pocoo.org/extensions/48-.. _flaskext_compat.py: https://raw.githubusercontent.com/mitsuhiko/flask/master/scripts/flaskext_compat.py58+.. _flaskext_compat.py: https://raw.githubusercontent.com/pallets/flask/master/scripts/flaskext_compat.pymodified:docs/htmlfaq.rst+1 added-1 removed
28 unmodified lines29 the (X)HTML generation on the web is based on non-XML template engines30 (such as Jinja, the one used in Flask) which do not protect you from31 accidentally creating invalid XHTML. There are XML based template engines,32 such as Kid and the popular Genshi, but they often come with a larger33-runtime overhead and, are not as straightforward to use because they have33+runtime overhead and are not as straightforward to use because they have34 to obey XML rules.35 36 The majority of users, however, assumed they were properly using XHTML.37 They wrote an XHTML doctype at the top of the document and self-closed all170 unmodified linesmodified:docs/installation.rst+22 added-33 removed
38 unmodified lines39 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.42 43-If you are on Mac OS X or Linux, chances are that one of the following two44-commands will work for you::43+If you are on Mac OS X or Linux, chances are that the following44+command will work for you::45 46- $ sudo easy_install virtualenv47-48-or even better::49-46 $ sudo pip install virtualenv47 52-One of these will probably install virtualenv on your system. Maybe it's even48+It will probably install virtualenv on your system. Maybe it's even49 in your package manager. If you use Ubuntu, try::50 51 $ sudo apt-get install python-virtualenv52 57-If you are on Windows and don't have the :command:`easy_install` command, you must53+If you are on Windows and don't have the ``easy_install`` command, you must54 install it first. Check the :ref:`windows-easy-install` section for more55 information about how to do that. Once you have it installed, run the same60-commands as above, but without the :command:`sudo` prefix.56+commands as above, but without the ``sudo`` prefix.57 58 Once you have virtualenv installed, just fire up a shell and create59 your own environment. I usually create a project folder and a :file:`venv`60 folder within::10 unmodified lines71 $ . venv/bin/activate72 73 If you are a Windows user, the following command is for you::74 79- $ venv\scripts\activate75+ $ venv\Scripts\activate76 77 Either way, you should now be using your virtualenv (notice how the prompt of78 your shell has changed to show the active environment).79 14 unmodified lines94 System-Wide Installation95 ------------------------96 97 This is possible as well, though I do not recommend it. Just run102-:command:`pip` with root privileges::98+``pip`` with root privileges::99 100 $ sudo pip install Flask101 102 (On Windows systems, run it in a command-prompt window with administrator107-privileges, and leave out :command:`sudo`.)103+privileges, and leave out ``sudo``.)104 105 106 Living on the Edge107 ------------------108 109 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 tell110+can either let ``pip`` pull in the development version, or you can tell111 it to operate on a git checkout. Either way, virtualenv is recommended.112 113 Get the git checkout in a new virtualenv and run in development mode::114 119- $ git clone http://github.com/mitsuhiko/flask.git115+ $ git clone https://github.com/pallets/flask.git116 Initialized empty Git repository in ~/dev/flask/.git/117 $ cd flask118 $ virtualenv venv119 New python executable in venv/bin/python6 unmodified lines126 This will pull in the dependencies and activate the git head as the current127 version inside the virtualenv. Then all you have to do is run ``git pull128 origin`` to update to the latest version.129 134-130 .. _windows-easy-install:131 132 `pip` and `setuptools` on Windows133 ---------------------------------134 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.135+Sometimes getting the standard "Python packaging tools" like ``pip``, ``setuptools``136+and ``virtualenv`` can be a little trickier, but nothing very hard. The crucial137+package you will need is pip - this will let you install138+anything else (like virtualenv). Fortunately there is a "bootstrap script"139+you can run to install.140 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).141+If you don't currently have ``pip``, then `get-pip.py` will install it for you.142 143 `get-pip.py`_144 151-To install the latest setuptools, you can use its bootstrap file:152-153-`ez_setup.py`_154-155-Either should be double-clickable once you download them. If you already have pip,145+It should be double-clickable once you download it. If you already have ``pip``,146 you can upgrade them by running::147 148 > pip install --upgrade pip setuptools149 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 happen150+Most often, once you pull up a command prompt you want to be able to type ``pip``151+and ``python`` which will run those things, but this might not automatically happen152 on Windows, because it doesn't know where those executables are (give either a try!).153 154 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 the155+(e.g :file:`C:\Python27`), then go to :file:`Tools`, then :file:`Scripts`, then find the156 :file:`win_add2path.py` file and run that. Open a **new** Command Prompt and167-check that you can now just type :command:`python` to bring up the interpreter.157+check that you can now just type ``python`` to bring up the interpreter.158 159 Finally, to install `virtualenv`_, you can simply run::160 161 > pip install virtualenv162 163 Then you can be off on your way following the installation instructions above.164 175-.. _get-pip.py: https://raw.githubusercontent.com/pypa/pip/master/contrib/get-pip.py176-.. _ez_setup.py: https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py165+.. _get-pip.py: https://bootstrap.pypa.io/get-pip.pymodified:docs/python3.rst+14 added-25 removed
1 unmodified line2 3 Python 3 Support4 ================5 6-Flask and all of its dependencies support Python 3 so you can in theory7-start working on it already. There are however a few things you should be8-aware of before you start using Python 3 for your next project.6+Flask, its dependencies, and most Flask extensions support Python 3.7+You should start using Python 3 for your next project,8+but there are a few things to be aware of.9 10-If you want to use Flask with Python 3 you will need to use Python 3.3 or11-higher. 3.2 and older are *not* supported.10+You need to use Python 3.3 or higher. 3.2 and older are *not* supported.11 13-In addition to that you need to use the latest and greatest versions of14-`itsdangerous`, `Jinja2` and `Werkzeug`. Flask 0.10 and Werkzeug 0.9 were15-the first versions to introduce Python 3 support.12+You should use the latest versions of all Flask-related packages.13+Flask 0.10 and Werkzeug 0.9 were the first versions to introduce Python 3 support.14 17-Some of the decisions made in regards to unicode and byte utilization on18-Python 3 make it hard to write low level code. This mainly affects WSGI19-middlewares and interacting with the WSGI provided information. Werkzeug20-wraps all that information in high-level helpers but some of those were21-specifically added for the Python 3 support and are quite new.15+Python 3 changed how unicode and bytes are handled, which complicates how low16+level code handles HTTP data. This mainly affects WSGI middleware interacting17+with the WSGI ``environ`` data. Werkzeug wraps that information in high-level18+helpers, so encoding issues should not affect you.19 23-Unless you require absolute compatibility, you should be fine with Python 324-nowadays. Most libraries and Flask extensions have been ported by now and25-using Flask with Python 3 is generally a smooth ride. However, keep in mind26-that most libraries (including Werkzeug and Flask) might not quite as stable27-on Python 3 yet. You might therefore sometimes run into bugs that are28-usually encoding-related.29-30-The majority of the upgrade pain is in the lower-level libraries like31-Flask and Werkzeug and not in the actual high-level application code. For32-instance all of the Flask examples that are in the Flask repository work33-out of the box on both 2.x and 3.x and did not require a single line of34-code changed.20+The majority of the upgrade work is in the lower-level libraries like21+Flask and Werkzeug, not the high-level application code.22+For example, all of the examples in the Flask repository work on both Python 2 and 323+and did not require a single line of code changed.modified:docs/quickstart.rst+90 added-89 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.2 unmodified lines36 4. The function is given a name which is also used to generate URLs for that37 particular function, and returns the message we want to display in the38 user's browser.39 40-Just save it as :file:`hello.py` (or something similar) and run it with your Python41-interpreter. Make sure to not call your application :file:`flask.py` because this42-would conflict with Flask itself.40+Just save it as :file:`hello.py` or something similar. Make sure to not call41+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::45+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::48 49+ $ export FLASK_APP=hello.py47- $ flask -a hello run50+ $ flask run51 * Running on http://127.0.0.1:5000/52 50-or alternatively::53+If you are on Windows you need to use ``set`` instead of ``export``.54 55+Alternatively you can use :command:`python -m flask`::56+57+ $ export FLASK_APP=hello.py52- $ python -m flask -a hello run58+ $ python -m flask run59 * Running on http://127.0.0.1:5000/60 61 This launches a very simple builtin server, which is good enough for testing62 but probably not what you want to use in production. For deployment options see14 unmodified lines77 If you have the debugger disabled or trust the users on your network,78 you can make the server publicly available simply by adding79 ``--host=0.0.0.0`` to the command line::80 75- flask -a hello run --host=0.0.0.081+ flask run --host=0.0.0.082 83 This tells your operating system to listen on all public IPs.84 85 86 What to do if the Server does not Start87 ---------------------------------------88 83-In case the ``python -m flask`` fails or :command:`flask` does not exist,89+In case the :command:`python -m flask` fails or :command:`flask` does not exist,90 there are multiple reasons this might be the case. First of all you need91 to look at the error message.92 93 Old Version of Flask94 ````````````````````95 90-Versions of Flask older than 1.0 use to have different ways to start the96+Versions of Flask older than 0.11 use to have different ways to start the97 application. In short, the :command:`flask` command did not exist, and92-neither did ``python -m flask``. In that case you have two options:98+neither did :command:`python -m flask`. In that case you have two options:99 either upgrade to newer Flask versions or have a look at the :ref:`server`100 docs to see the alternative method for running a server.101 96-Python older 2.797-````````````````98-99-In case you have a version of Python older than 2.7 ``python -m flask``100-does not work. You can either use :command:`flask` or ``python -m101-flask.cli`` as an alternative. This is because Python before 2.7 does no102-permit packages to act as executable modules. For more information see103-:ref:`cli`.104-102 Invalid Import Name103 ```````````````````104 108-The :option:`-a` argument to :command:`flask` is the name of the module to import. In109-case that module is incorrectly named you will get an import error upon110-start (or if debug is enabled when you navigate to the application). It111-will tell you what it tried to import and why it failed.105+The ``FLASK_APP`` environment variable is the name of the module to import at106+:command:`flask run`. In case that module is incorrectly named you will get an107+import error upon start (or if debug is enabled when you navigate to the108+application). It will tell you what it tried to import and why it failed.109 110 The most common reason is a typo or because you did not actually create an111 ``app`` object.112 9 unmodified lines122 That is not very nice and Flask can do better. If you enable debug123 support the server will reload itself on code changes, and it will also124 provide you with a helpful debugger if things go wrong.125 129-There are different ways to enable the debug mode. The most obvious one130-is the :option:`--debug` parameter to the :command:`flask` command::126+To enable debug mode you can export the ``FLASK_DEBUG`` environment variable127+before running the server::128 132- flask --debug -a hello run129+ $ export FLASK_DEBUG=1130+ $ flask run131 132+(On Windows you need to use ``set`` instead of ``export``).133+134 This does the following things:135 136 1. it activates the debugger137 2. it activates the automatic reloader63 unmodified lines201 202 =========== ===============================================203 `string` accepts any text without a slash (the default)204 `int` accepts integers205-`float` like `int` but for floating point values205+`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 =========== ===============================================210 211 .. admonition:: Unique URLs / Redirection Behavior212 12 unmodified lines225 return 'The about page'226 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 the227- `projects` endpoint has a trailing slash. In that sense, it is similar to229+ ``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.232 233 In the second case, however, the URL is defined without a trailing slash,15 unmodified lines249 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 are251-some examples:253+some examples::254 253->>> from flask import Flask, url_for254->>> app = Flask(__name__)255->>> @app.route('/')256-... def index(): pass257-...258->>> @app.route('/login')259-... def login(): pass260-...261->>> @app.route('/user/<username>')262-... def profile(username): pass263-...264->>> with app.test_request_context():265-... print url_for('index')266-... print url_for('login')267-... print url_for('login', next='/')268-... print url_for('profile', username='John Doe')269-...270-/271-/login272-/login?next=/273-/user/John%20Doe255+ >>> 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 the7 unmodified lines287 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.289-3. If your application is placed outside the URL root (say, in290- ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will handle291+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.294 295 296 HTTP Methods297 ````````````298 299 HTTP (the protocol web applications are speaking) knows different methods for300 accessing URLs. By default, a route only answers to ``GET`` requests, but that299-can be changed by providing the `methods` argument to the301+can be changed by providing the ``methods`` argument to the302 :meth:`~flask.Flask.route` decorator. Here are some examples::303 304 from flask import request305 306 @app.route('/login', methods=['GET', 'POST'])307 def login():308 if request.method == 'POST':307- do_the_login()309+ return do_the_login()310 else:309- show_the_login_form()311+ return show_the_login_form()312 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 HTTP4 unmodified lines320 You have no idea what an HTTP method is? Worry not, here is a quick321 introduction to HTTP methods and why they matter:322 323 The HTTP method (also often called "the verb") tells the server what the322-clients wants to *do* with the requested page. The following methods are324+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 on37 unmodified lines366 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 368-.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt370+.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt371 372 Static Files373 ------------374 70 unmodified lines445 know how that works, head over to the :ref:`template-inheritance` pattern446 documentation. Basically template inheritance makes it possible to keep447 certain elements on each page (like header, navigation and footer).448 447-Automatic escaping is enabled, so if `name` contains HTML it will be escaped449+Automatic escaping is enabled, so if ``name`` contains HTML it will be escaped450 automatically. If you can trust a variable and you know that it will be451 safe HTML (for example because it came from a module that converts wiki452 markup to HTML) you can mark it as safe by using the453 :class:`~jinja2.Markup` class or by using the ``|safe`` filter in the454 template. Head over to the Jinja 2 documentation for more examples.455 454-Here is a basic introduction to how the :class:`~jinja2.Markup` class works:456+Here is a basic introduction to how the :class:`~jinja2.Markup` class works::457 456->>> from flask import Markup457->>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'458-Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')459->>> Markup.escape('<blink>hacker</blink>')460-Markup(u'<blink>hacker</blink>')461->>> Markup('<em>Marked up</em> » HTML').striptags()462-u'Marked up \xbb HTML'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'465 466 .. versionchanged:: 0.5467 468 Autoescaping is no longer enabled for all templates. The following68 unmodified lines537 The Request Object538 ``````````````````539 540 The request object is documented in the API section and we will not cover539-it here in detail (see :class:`~flask.request`). Here is a broad overview of541+it here in detail (see :class:`~flask.Request`). Here is a broad overview of542 some of the most common operations. First of all you have to import it from541-the `flask` module::543+the ``flask`` module::544 545 from flask import request546 547 The current request method is available by using the546-:attr:`~flask.request.method` attribute. To access form data (data548+:attr:`~flask.Request.method` attribute. To access form data (data549 transmitted in a ``POST`` or ``PUT`` request) you can use the548-:attr:`~flask.request.form` attribute. Here is a full example of the two550+:attr:`~flask.Request.form` attribute. Here is a full example of the two551 attributes mentioned above::552 553 @app.route('/login', methods=['POST', 'GET'])554 def login():7 unmodified lines562 # the code below is executed if the request method563 # was GET or the credentials were invalid564 return render_template('login.html', error=error)565 564-What happens if the key does not exist in the `form` attribute? In that566+What happens if the key does not exist in the ``form`` attribute? In that567 case a special :exc:`KeyError` is raised. You can catch it like a568 standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request569 error page is shown instead. So for many situations you don't have to570 deal with that problem.571 572 To access parameters submitted in the URL (``?key=value``) you can use the571-:attr:`~flask.request.args` attribute::573+:attr:`~flask.Request.args` attribute::574 575 searchword = request.args.get('key', '')576 577 We recommend accessing URL parameters with `get` or by catching the578 :exc:`KeyError` because users might change the URL and presenting them a 400579 bad request page in that case is not user friendly.580 581 For a full list of methods and attributes of the request object, head over580-to the :class:`~flask.request` documentation.582+to the :class:`~flask.Request` documentation.583 584 585 File Uploads586 ````````````137 unmodified lines724 default parameters.725 3. If a tuple is returned the items in the tuple can provide extra726 information. Such tuples have to be in the form ``(response, status,727 headers)`` or ``(response, headers)`` where at least one item has726- to be in the tuple. The `status` value will override the status code727- and `headers` can be a list or dictionary of additional header values.728+ 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.730 4. If none of that works, Flask will assume the return value is a731 valid WSGI application and convert that into a response object.732 733 If you want to get hold of the resulting response object inside the view734 you can use the :func:`~flask.make_response` function.735 734-Imagine you have a view like this:736+Imagine you have a view like this::737 736-.. sourcecode:: python737-738 @app.errorhandler(404)739 def not_found(error):740 return render_template('error.html'), 404741 742 You just need to wrap the return expression with743 :func:`~flask.make_response` and get the response object to modify it, then744-return it:744+return it::745 746-.. sourcecode:: python747-746 @app.errorhandler(404)747 def not_found(error):748 resp = make_response(render_template('error.html'), 404)749 resp.headers['X-Something'] = 'A value'29 unmodified lines779 if request.method == 'POST':780 session['username'] = request.form['username']781 return redirect(url_for('index'))782 return '''785- <form action="" method="post">783+ <form method="post">784 <p><input type=text name=username>785 <p><input type=submit value=Login>786 </form>787 '''14 unmodified lines802 803 The problem with random is that it's hard to judge what is truly random. And804 a secret key should be as random as possible. Your operating system805 has ways to generate pretty random stuff based on a cryptographic808- random generator which can be used to get such a key:806+ random generator which can be used to get such a key::807 810- >>> import os811- >>> os.urandom(24)812- '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'808+ >>> import os809+ >>> os.urandom(24)810+ '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'811 814- Just take that thing and copy/paste it into your code and you're done.812+ Just take that thing and copy/paste it into your code and you're done.813 814 A note on cookie-based sessions: Flask will take the values you put into the815 session object and serialize them into a cookie. If you are finding some816 values do not persist across requests, cookies are indeed enabled, and you are817 not getting a clear error message, check the size of the cookie in your page818 responses compared to the size supported by web browsers.819 820+Besides the default client-side based sessions, if you want to handle821+sessions on the server-side instead, there are several822+Flask extensions that support this.823 824 Message Flashing825 ----------------826 67 unmodified linesmodified:docs/reqcontext.rst+1 added-1 removed
67 unmodified lines68 def wsgi_app(self, environ):69 with self.request_context(environ):70 try:71 response = self.full_dispatch_request()72- except Exception, e:72+ except Exception as e:73 response = self.make_response(self.handle_exception(e))74 return response(environ, start_response)75 76 The method :meth:`~Flask.request_context` returns a new147 unmodified linesmodified:docs/security.rst+10 added-79 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 be49 unmodified lines72 73 Say you have a specific URL that, when you sent ``POST`` requests to will74 delete a user's profile (say ``http://example.com/user/delete``). If an75 attacker now creates a page that sends a post request to that page with76-some JavaScript they just has to trick some users to load that page and76+some JavaScript they just have to trick some users to load that page and77 their profiles will end up being deleted.78 79 Imagine you were to run Facebook with millions of concurrent users and80 someone would send out links to images of little kittens. When users13 unmodified lines94 95 JSON Security96 -------------97 98-.. admonition:: ECMAScript 5 Changes98+In Flask 0.10 and lower, :func:`~flask.jsonify` did not serialize top-level99+arrays to JSON. This was because of a security vulnerability in ECMAScript 4.100 100- Starting with ECMAScript 5 the behavior of literals changed. Now they101- are not constructed with the constructor of ``Array`` and others, but102- with the builtin constructor of ``Array`` which closes this particular103- attack vector.104-105-JSON itself is a high-level serialization format, so there is barely106-anything that could cause security problems, right? You can't declare107-recursive structures that could cause problems and the only thing that108-could possibly break are very large responses that can cause some kind of109-denial of service at the receiver's side.110-111-However there is a catch. Due to how browsers work the CSRF issue comes112-up with JSON unfortunately. Fortunately there is also a weird part of the113-JavaScript specification that can be used to solve that problem easily and114-Flask is kinda doing that for you by preventing you from doing dangerous115-stuff. Unfortunately that protection is only there for116-:func:`~flask.jsonify` so you are still at risk when using other ways to117-generate JSON.118-119-So what is the issue and how to avoid it? The problem are arrays at120-top-level in JSON. Imagine you send the following data out in a JSON121-request. Say that's exporting the names and email addresses of all your122-friends for a part of the user interface that is written in JavaScript.123-Not very uncommon:124-125-.. sourcecode:: javascript126-127- [128- {"username": "admin",129- "email": "admin@localhost"}130- ]131-132-And it is doing that of course only as long as you are logged in and only133-for you. And it is doing that for all ``GET`` requests to a certain URL,134-say the URL for that request is135-``http://example.com/api/get_friends.json``.136-137-So now what happens if a clever hacker is embedding this to his website138-and social engineers a victim to visiting his site:139-140-.. sourcecode:: html141-142- <script type=text/javascript>143- var captured = [];144- var oldArray = Array;145- function Array() {146- var obj = this, id = 0, capture = function(value) {147- obj.__defineSetter__(id++, capture);148- if (value)149- captured.push(value);150- };151- capture();152- }153- </script>154- <script type=text/javascript155- src=http://example.com/api/get_friends.json></script>156- <script type=text/javascript>157- Array = oldArray;158- // now we have all the data in the captured array.159- </script>160-161-If you know a bit of JavaScript internals you might know that it's162-possible to patch constructors and register callbacks for setters. An163-attacker can use this (like above) to get all the data you exported in164-your JSON file. The browser will totally ignore the :mimetype:`application/json`165-mimetype if :mimetype:`text/javascript` is defined as content type in the script166-tag and evaluate that as JavaScript. Because top-level array elements are167-allowed (albeit useless) and we hooked in our own constructor, after that168-page loaded the data from the JSON response is in the `captured` array.169-170-Because it is a syntax error in JavaScript to have an object literal171-(``{...}``) toplevel an attacker could not just do a request to an172-external URL with the script tag to load up the data. So what Flask does173-is to only allow objects as toplevel elements when using174-:func:`~flask.jsonify`. Make sure to do the same when using an ordinary175-JSON generate function.101+ECMAScript 5 closed this vulnerability, so only extremely old browsers are102+still vulnerable. All of these browsers have `other more serious103+vulnerabilities104+<https://github.com/pallets/flask/issues/248#issuecomment-59934857>`_, so105+this behavior was changed and :func:`~flask.jsonify` now supports serializing106+arrays.modified:docs/server.rst+10 added-8 removed
3 unmodified lines4 ==================5 6 .. currentmodule:: flask7 8-Starting with Flask 1.0 there are multiple built-in ways to run a8+Starting with Flask 0.11 there are multiple built-in ways to run a9 development server. The best one is the :command:`flask` command line utility10 but you can also continue using the :meth:`Flask.run` method.11 12 Command Line2 unmodified lines15 The :command:`flask` command line script (:ref:`cli`) is strongly recommended for16 development because it provides a superior reload experience due to how it17 loads the application. The basic usage is like this::18 19- $ flask -a my_application --debug run19+ $ export FLASK_APP=my_application20+ $ export FLASK_DEBUG=121+ $ flask run22 23 This will enable the debugger, the reloader and then start the server on24 *http://localhost:5000/*.25 26 The individual features of the server can be controlled by passing more27 arguments to the ``run`` option. For instance the reloader can be28 disabled::29 28- $ flask -a my_application --debug run --no-reload30+ $ flask run --no-reload31 32 In Code33 -------34 6 unmodified lines41 if __name__ == '__main__':42 app.run()43 44 This works well for the common case but it does not work well for43-development which is why from Flask 1.0 onwards the :command:`flask` method is44-recommended. The reason for this is that due to how the reload mechanism45-works there are some bizarre side-effects (like executing certain code46-twice, sometimes crashing without message or dying when a syntax or47-import error happens).45+development which is why from Flask 0.11 onwards the :command:`flask`46+method is recommended. The reason for this is that due to how the reload47+mechanism works there are some bizarre side-effects (like executing48+certain code twice, sometimes crashing without message or dying when a49+syntax or import error happens).50 51 It is however still a perfectly valid method for invoking a non automatic52 reloading application.modified:docs/shell.rst+1 added-1 removed
27 unmodified lines28 29 Command Line Interface30 ----------------------31 32-Starting with Flask 1.0 the recommended way to work with the shell is the32+Starting with Flask 0.11 the recommended way to work with the shell is the33 ``flask shell`` command which does a lot of this automatically for you.34 For instance the shell is automatically initialized with a loaded35 application context.36 67 unmodified linesmodified:docs/signals.rst+3 added-3 removed
17 unmodified lines18 more. Also keep in mind that signals are intended to notify subscribers19 and should not encourage subscribers to modify data. You will notice that20 there are signals that appear to do the same thing like some of the21 builtin decorators do (eg: :data:`~flask.request_started` is very similar22-to :meth:`~flask.Flask.before_request`). There are however difference in23-how they work. The core :meth:`~flask.Flask.before_request` handler for24-example is executed in a specific order and is able to abort the request22+to :meth:`~flask.Flask.before_request`). However, there are differences in23+how they work. The core :meth:`~flask.Flask.before_request` handler, for24+example, is executed in a specific order and is able to abort the request25 early by returning a response. In contrast all signal handlers are26 executed in undefined order and do not modify any data.27 28 The big advantage of signals over handlers is that you can safely162 unmodified linesmodified:docs/styleguide.rst+1 added-1 removed
165 unmodified lines166 is on its own line.167 """168 169 Module header:170- The module header consists of an utf-8 encoding declaration (if non170+ The module header consists of a utf-8 encoding declaration (if non171 ASCII letters are used, but it is recommended all the time) and a172 standard docstring::173 174 # -*- coding: utf-8 -*-26 unmodified linesmodified:docs/testing.rst+17 added-15 removed
22 unmodified lines23 the :ref:`tutorial`. If you don't have that application yet, get the24 sources from `the examples`_.25 26 .. _the examples:27- https://github.com/mitsuhiko/flask/tree/master/examples/flaskr/27+ https://github.com/pallets/flask/tree/master/examples/flaskr/28 29 The Testing Skeleton30 --------------------31 32 In order to test the application, we add a second module33 (:file:`flaskr_tests.py`) and create a unittest skeleton there::34 35 import os36- import flaskr36+ from flaskr import flaskr37 import unittest38 import tempfile39 40 class FlaskrTestCase(unittest.TestCase):41 42 def setUp(self):43 self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()44- flaskr.app.config['TESTING'] = True44+ flaskr.app.testing = True45 self.app = flaskr.app.test_client()46 with flaskr.app.app_context():47 flaskr.init_db()48 48 unmodified lines97 class FlaskrTestCase(unittest.TestCase):98 99 def setUp(self):100 self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()101+ flaskr.app.testing = True102 self.app = flaskr.app.test_client()103+ with flaskr.app.app_context():102- flaskr.init_db()104+ flaskr.init_db()105 106 def tearDown(self):107 os.close(self.db_fd)108 os.unlink(flaskr.app.config['DATABASE'])44 unmodified lines153 invalid credentials. Add this new test to the class::154 155 def test_login_logout(self):156 rv = self.login('admin', 'default')155- assert 'You were logged in' in rv.data157+ assert b'You were logged in' in rv.data158 rv = self.logout()157- assert 'You were logged out' in rv.data159+ assert b'You were logged out' in rv.data160 rv = self.login('adminx', 'default')159- assert 'Invalid username' in rv.data161+ assert b'Invalid username' in rv.data162 rv = self.login('admin', 'defaultx')161- assert 'Invalid password' in rv.data163+ assert b'Invalid password' in rv.data164 165 Test Adding Messages166 --------------------167 5 unmodified lines173 rv = self.app.post('/add', data=dict(174 title='<Hello>',175 text='<strong>HTML</strong> allowed here'176 ), 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.data177+ assert b'No entries here so far' not in rv.data178+ assert b'<Hello>' in rv.data179+ assert b'<strong>HTML</strong> allowed here' in rv.data180 181 Here we check that HTML is allowed in the text but not in the title,182 which is the intended behavior.183 11 unmodified lines195 suite.196 197 198 .. _MiniTwit Example:197- https://github.com/mitsuhiko/flask/tree/master/examples/minitwit/199+ https://github.com/pallets/flask/tree/master/examples/minitwit/200 201 202 Other Testing Tricks203 --------------------5 unmodified lines209 :class:`~flask.g` and :class:`~flask.session` objects like in view210 functions. Here is a full example that demonstrates this approach::211 212 import flask211- 213+214 app = flask.Flask(__name__)215 216 with app.test_request_context('/?name=Peter'):217 assert flask.request.path == '/'6 unmodified lines224 there does not seem to be a good way to do that, consider switching to225 application factories (see :ref:`app-factories`).226 227 Note however that if you are using a test request context, the226-:meth:`~flask.Flask.before_request` functions are not automatically called227-same for :meth:`~flask.Flask.after_request` functions. However228+:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`229+functions are not called automatically. However230 :meth:`~flask.Flask.teardown_request` functions are indeed executed when231 the test request context leaves the ``with`` block. If you do want the232 :meth:`~flask.Flask.before_request` functions to be called as well, you233 need to call :meth:`~flask.Flask.preprocess_request` yourself::124 unmodified linesmodified:docs/upgrading.rst+91 added-22 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 1.025------------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 supposed66+to be the 1.0 release. However because there was such a long lead time up67+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+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+Debugging76+`````````77+27-Flask 1.0 removed the ``debug_log_format`` attribute from Flask78+Flask 0.11 removed the ``debug_log_format`` attribute from Flask79 applications. Instead the new ``LOGGER_HANDLER_POLICY`` configuration can80 be used to disable the default log handlers and custom log handlers can be81 set up.82 83+Error handling84+``````````````85+86 The behavior of error handlers was changed.87 The precedence of handlers used to be based on the decoration/call order of88 :meth:`~flask.Flask.errorhandler` and89 :meth:`~flask.Flask.register_error_handler`, respectively.90 Now the inheritance hierarchy takes precedence and handlers for more91 specific exception classes are executed instead of more general ones.92 See :ref:`error-handlers` for specifics.93 40-The :func:`~flask.templating.render_template_string` function has changed to41-autoescape template variables by default. This better matches the behavior42-of :func:`~flask.templating.render_template`.94+Trying to register a handler on an instance now raises :exc:`ValueError`.95 96 .. note::97 98 There used to be a logic error allowing you to register handlers99 only for exception *instances*. This was unintended and plain wrong,100 and therefore was replaced with the intended behavior of registering101 handlers only using exception classes and HTTP error codes.50- 51- Trying to register a handler on an instance now raises :exc:`ValueError`.102 103+Templating104+``````````105+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`.109+110+Extension imports111+`````````````````112+113+Extension imports of the form ``flask.ext.foo`` are deprecated, you should use114+``flask_foo``.115+116+The old form still works, but Flask will issue a117+``flask.exthook.ExtDeprecationWarning`` for each extension you import the old118+way. We also provide a migration utility called `flask-ext-migrate119+<https://github.com/pallets/flask-ext-migrate>`_ that is supposed to120+automatically rewrite your imports for this.121+122 .. _upgrading-to-010:123 124 Version 0.10125 ------------16 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 77-.. _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 that105-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 132-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.8 unmodified lines214 215 To apply the upgrade script do the following:216 217 1. Download the script: `flask-07-upgrade.py149- <https://raw.githubusercontent.com/mitsuhiko/flask/master/scripts/flask-07-upgrade.py>`_218+ <https://raw.githubusercontent.com/pallets/flask/master/scripts/flask-07-upgrade.py>`_219 2. Run it in the directory of your application::220 221 python flask-07-upgrade.py > patchfile.diff222 13 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 171-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 system8 unmodified lines253 before, you should catch them with :exc:`RuntimeError` now.254 255 Additionally the :func:`~flask.send_file` function is now issuing256 deprecation warnings if you depend on functionality that will be removed188-in Flask 1.0. Previously it was possible to use etags and mimetypes257+in Flask 0.11. Previously it was possible to use etags and mimetypes258 when file objects were passed. This was unreliable and caused issues259 for a few setups. If you get a deprecation warning, make sure to260 update your application to work with either filenames there or disable261 etag attaching and attach them yourself.91 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 endpoint288- `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 306-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 template326-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.352-- 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/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('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>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('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('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+1 added
1+from .flaskr import appadded:examples/flaskr/flaskr/flaskr.py+110 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 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/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+76 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 import flaskr16+17+18+@pytest.fixture19+def client(request):20+ db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()21+ flaskr.app.config['TESTING'] = True22+ client = flaskr.app.test_client()23+ with flaskr.app.app_context():24+ flaskr.init_db()25+26+ def teardown():27+ os.close(db_fd)28+ os.unlink(flaskr.app.config['DATABASE'])29+ request.addfinalizer(teardown)30+31+ return client32+33+34+def login(client, username, password):35+ return client.post('/login', data=dict(36+ username=username,37+ password=password38+ ), follow_redirects=True)39+40+41+def logout(client):42+ return client.get('/logout', follow_redirects=True)43+44+45+def test_empty_db(client):46+ """Start with a blank database."""47+ rv = client.get('/')48+ assert b'No entries here so far' in rv.data49+50+51+def test_login_logout(client):52+ """Make sure login and logout works"""53+ rv = login(client, flaskr.app.config['USERNAME'],54+ flaskr.app.config['PASSWORD'])55+ assert b'You were logged in' in rv.data56+ rv = logout(client)57+ assert b'You were logged out' in rv.data58+ rv = login(client, flaskr.app.config['USERNAME'] + 'x',59+ flaskr.app.config['PASSWORD'])60+ assert b'Invalid username' in rv.data61+ rv = login(client, flaskr.app.config['USERNAME'],62+ flaskr.app.config['PASSWORD'] + 'x')63+ assert b'Invalid password' in rv.data64+65+66+def test_messages(client):67+ """Test that messages work"""68+ login(client, flaskr.app.config['USERNAME'],69+ flaskr.app.config['PASSWORD'])70+ rv = client.post('/add', data=dict(71+ title='<Hello>',72+ text='<strong>HTML</strong> allowed here'73+ ), follow_redirects=True)74+ assert b'No entries here so far' not in rv.data75+ assert b'<Hello>' in rv.data76+ 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-5 removed
11 unmodified lines12 1. edit the configuration in the flaskr.py file or13 export an FLASKR_SETTINGS environment variable14 pointing to a configuration file.15 16- 2. initialize the database with this command:16+ 2. install the app from the root of the project directory17 18- flask --app=flaskr initdb18+ pip install --editable .19 20- 3. now you can run flaskr:20+ 3. Instruct flask to use the right application21 22- flask --app=flaskr run22+ export FLASK_APP=flaskr23 24+ 4. initialize the database with this command:25+26+ flask initdb27+28+ 5. now you can run flaskr:29+30+ flask run31+32 the application will greet you on33 http://localhost:5000/34 35 ~ Is it tested?36 29- You betcha. Run the `test_flaskr.py` file to see37+ You betcha. Run `python setup.py test` to see38 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+[tool:pytest]2+test=pytestadded:examples/flaskr/setup.py+16 added
1+from setuptools import setup2+3+setup(4+ name='flaskr',5+ packages=['flaskr'],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/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(__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 '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+151 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(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/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+13 added-5 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. fire up a shell and run this:17+ 2. install the app from the root of the project directory18 19- flask --app=minitwit initdb19+ pip install --editable .20 21- 3. now you can run minitwit:21+ 3. tell flask about the right application:22 23- flask --app=minitwit run23+ export FLASK_APP=minitwit24 25+ 4. fire up a shell and run this:26+27+ flask initdb28+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 30- 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(__name__)3+4+import yourapplication.viewsadded:examples/patterns/largerapp/yourapplication/views.py+5 added
1+from yourapplication import app2+3+@app.route('/')4+def index():5+ return 'Hello World!'added:examples/patterns/largerapp/setup.py+10 added
1+from setuptools import setup2+3+setup(4+ name='yourapplication',5+ packages=['yourapplication'],6+ include_package_data=True,7+ install_requires=[8+ 'flask',9+ ],10+)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.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.dev0'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+13 added-5 removed
63 unmodified lines64 return type.__new__(metaclass, 'temporary_class', (), {})65 66 67 # Certain versions of pypy have a bug where clearing the exception stack68-# breaks the __exit__ function in a very peculiar way. This is currently69-# true for pypy 2.2.1 for instance. The second level of exception blocks70-# is necessary because pypy seems to forget to check if an exception71-# happened until the next bytecode instruction?68+# breaks the __exit__ function in a very peculiar way. The second level of69+# exception blocks is necessary because pypy seems to forget to check if an70+# exception happened until the next bytecode instruction?71+#72+# Relevant PyPy bugfix commit:73+# https://bitbucket.org/pypy/pypy/commits/77ecf91c635a287e88e60d8ddb0f4e9df400330174+# According to ronan on #pypy IRC, it is released in PyPy2 2.3 and later75+# versions.76+#77+# Ubuntu 14.04 has PyPy 2.2.1, which does exhibit this bug.78 BROKEN_PYPY_CTXMGR_EXIT = False79 if hasattr(sys, 'pypy_version_info'):80 class _Mgr(object):81 def __enter__(self):82 return self83 def __exit__(self, *args):84+ if hasattr(sys, 'exc_clear'):85+ # Python 3 (PyPy3) doesn't have exc_clear78- sys.exc_clear()86+ sys.exc_clear()87 try:88 try:89 with _Mgr():90 raise AssertionError()6 unmodified linesmodified:flask/app.py+212 added-123 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 import os12 import sys13-from threading import Lock13 from datetime import timedelta15-from itertools import chain14 from functools import update_wrapper17-from collections import deque15+from itertools import chain16+from threading import Lock17 19-from werkzeug.datastructures import ImmutableDict20-from werkzeug.routing import Map, Rule, RequestRedirect, BuildError21-from werkzeug.exceptions import HTTPException, InternalServerError, \22- MethodNotAllowed, BadRequest, default_exceptions18+from werkzeug.datastructures import ImmutableDict, Headers19+from werkzeug.exceptions import BadRequest, HTTPException, \20+ InternalServerError, MethodNotAllowed, default_exceptions21+from werkzeug.routing import BuildError, Map, RequestRedirect, Rule22 24-from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \25- locked_cached_property, _endpoint_from_view_func, find_package26-from . import json, cli27-from .wrappers import Request, Response28-from .config import ConfigAttribute, Config29-from .ctx import RequestContext, AppContext, _AppCtxGlobals30-from .globals import _request_ctx_stack, request, session, g23+from . import cli, json24+from ._compat import integer_types, reraise, string_types, text_type25+from .config import Config, ConfigAttribute26+from .ctx import AppContext, RequestContext, _AppCtxGlobals27+from .globals import _request_ctx_stack, g, request, session28+from .helpers import _PackageBoundObject, \29+ _endpoint_from_view_func, find_package, get_debug_flag, \30+ get_flashed_messages, locked_cached_property, url_for31 from .sessions import SecureCookieSessionInterface32+from .signals import appcontext_tearing_down, got_request_exception, \33+ request_finished, request_started, request_tearing_down34 from .templating import DispatchingJinjaLoader, Environment, \33- _default_template_ctx_processor34-from .signals import request_started, request_finished, got_request_exception, \35- request_tearing_down, appcontext_tearing_down36-from ._compat import reraise, string_types, text_type, integer_types35+ _default_template_ctx_processor36+from .wrappers import Request, Response37 38 # a lock used for logger initialization39 _logger_lock = Lock()40 78 unmodified lines119 .. versionadded:: 0.8120 The `instance_path` and `instance_relative_config` parameters were121 added.122 123- .. versionadded:: 1.0123+ .. versionadded:: 0.11124 The `root_path` parameter was added.125 126+ .. versionadded:: 0.13127+ The `host_matching` and `static_host` parameters were added.128+129 :param import_name: the name of the application package130 :param static_url_path: can be used to specify a different path for the131 static files on the web. Defaults to the name132 of the `static_folder` folder.133 :param static_folder: the folder with static files that should be served134 at `static_url_path`. Defaults to the ``'static'``135 folder in the root path of the application.136+ folder in the root path of the application. Defaults137+ to None.138+ :param host_matching: sets the app's ``url_map.host_matching`` to the given139+ given value. Defaults to False.140+ :param static_host: the host to use when adding the static route. Defaults141+ to None. Required when using ``host_matching=True``142+ with a ``static_folder`` configured.143 :param template_folder: the folder that contains the templates that should144 be used by the application. Defaults to145 ``'templates'`` folder in the root path of the146 application.21 unmodified lines168 response_class = Response169 170 #: The class that is used for the Jinja environment.171 #:162- #: .. versionadded:: 1.0172+ #: .. versionadded:: 0.11173 jinja_environment = Environment174 175 #: The class that is used for the :data:`~flask.g` instance.176 #:30 unmodified lines207 #:208 #: 1. Default values for certain config options.209 #: 2. Access to config values through attributes in addition to keys.210 #:201- #: .. versionadded:: 1.0211+ #: .. versionadded:: 0.11212 config_class = Config213 214 #: The debug flag. Set this to ``True`` to enable debugging of the215 #: application. In debug mode the debugger will kick in when an unhandled82 unmodified lines298 )299 300 #: Default configuration parameters.301 default_config = ImmutableDict({292- 'DEBUG': False,302+ 'DEBUG': get_debug_flag(default=False),303 'TESTING': False,304 'PROPAGATE_EXCEPTIONS': None,305 'PRESERVE_CONTEXT_ON_EXCEPTION': None,306 'SECRET_KEY': None,16 unmodified lines323 'EXPLAIN_TEMPLATE_LOADING': False,324 'PREFERRED_URL_SCHEME': 'http',325 'JSON_AS_ASCII': True,326 'JSON_SORT_KEYS': True,317- 'JSONIFY_PRETTYPRINT_REGULAR': True,327+ 'JSONIFY_PRETTYPRINT_REGULAR': False,328+ 'JSONIFY_MIMETYPE': 'application/json',329 'TEMPLATES_AUTO_RELOAD': None,330 })331 332 #: The rule object to use for URL rules created. This is used by13 unmodified lines346 #: .. versionadded:: 0.8347 session_interface = SecureCookieSessionInterface()348 349 def __init__(self, import_name, static_path=None, static_url_path=None,339- static_folder='static', template_folder='templates',350+ static_folder='static', static_host=None,351+ host_matching=False, template_folder='templates',352 instance_path=None, instance_relative_config=False,353 root_path=None):354 _PackageBoundObject.__init__(self, import_name,355 template_folder=template_folder,45 unmodified lines401 #: special key ``None`` points to a list of tuples where the first item402 #: is the class for the instance check and the second the error handler403 #: function.404 #:393- #: To register a error handler, use the :meth:`errorhandler`405+ #: To register an error handler, use the :meth:`errorhandler`406 #: decorator.407 self.error_handler_spec = {None: self._error_handlers}408 409 #: A list of functions that are called when :meth:`url_for` raises a22 unmodified lines432 433 #: A dictionary with lists of functions that should be called after434 #: each request. The key of the dictionary is the name of the blueprint435 #: this function is active for, ``None`` for all requests. This can for424- #: example be used to open database connections or getting hold of the425- #: currently logged in user. To register a function here, use the426- #: :meth:`after_request` decorator.436+ #: example be used to close database connections. To register a function437+ #: here, use the :meth:`after_request` decorator.438 self.after_request_funcs = {}439 440 #: A dictionary with lists of functions that are called after441 #: each request, even if an exception has occurred. The key of the49 unmodified lines491 492 #: A list of shell context processor functions that should be run493 #: when a shell context is created.494 #:484- #: .. versionadded:: 1.0495+ #: .. versionadded:: 0.11496 self.shell_context_processors = []497 498 #: all the attached blueprints in a dictionary by name. Blueprints499 #: can be attached multiple times so this dictionary does not tell28 unmodified lines528 #: class ListConverter(BaseConverter):529 #: def to_python(self, value):530 #: return value.split(',')531 #: def to_url(self, values):521- #: return ','.join(BaseConverter.to_url(value)532+ #: return ','.join(super(ListConverter, self).to_url(value)533 #: for value in values)534 #:535 #: app = Flask(__name__)536 #: app.url_map.converters['list'] = ListConverter537 self.url_map = Map()538 539+ self.url_map.host_matching = host_matching540+541 # tracks internally if the application already handled at least one542 # request.543 self._got_first_request = False544 self._before_request_lock = Lock()545 533- # register the static folder for the application. Do that even534- # if the folder does not exist. First of all it might be created535- # while the server is running (usually happens during development)536- # but also because google appengine stores static files somewhere537- # else when mapped with the .yml file.546+ # Add a static route using the provided static_url_path, static_host,547+ # and static_folder if there is a configured static_folder.548+ # Note we do this without checking if static_folder exists.549+ # For one, it might be created while the server is running (e.g. during550+ # development). Also, Google App Engine stores static files somewhere551 if self.has_static_folder:552+ assert bool(static_host) == host_matching, 'Invalid static_host/host_matching combination'553 self.add_url_rule(self.static_url_path + '/<path:filename>',540- endpoint='static',554+ endpoint='static', host=static_host,555 view_func=self.send_static_file)556 557 #: The click command line context for this application. Commands558 #: registered here show up in the :command:`flask` command once the559 #: application has been discovered. The default commands are560 #: provided by Flask itself and can be overridden.561 #:562 #: This is an instance of a :class:`click.Group` object.549- self.cli = cli.AppGroup(self)563+ self.cli = cli.AppGroup(self.name)564 565 def _get_error_handlers(self):566 from warnings import warn567 warn(DeprecationWarning('error_handlers is deprecated, use the '128 unmodified lines696 the Jinja2 globals and filters after initialization. Override697 this function to customize the behavior.698 699 .. versionadded:: 0.5686- .. versionchanged:: 1.0700+ .. versionchanged:: 0.11701 ``Environment.auto_reload`` set in accordance with702 ``TEMPLATES_AUTO_RELOAD`` configuration option.703 """704 options = dict(self.jinja_options)80 unmodified lines785 """Returns the shell context for an interactive shell for this786 application. This runs all the registered shell context787 processors.788 775- .. versionadded:: 1.0789+ .. versionadded:: 0.11790 """791 rv = {'app': self, 'g': g}792 for processor in self.shell_context_processors:793 rv.update(processor())794 return rv795 796 def run(self, host=None, port=None, debug=None, **options):783- """Runs the application on a local development server. If the784- :attr:`debug` flag is set the server will automatically reload797+ """Runs the application on a local development server.798+799+ Do not use ``run()`` in a production setting. It is not intended to800+ meet security and performance requirements for a production server.801+ Instead, see :ref:`deployment` for WSGI server recommendations.802+803+ If the :attr:`debug` flag is set the server will automatically reload804 for code changes and show a debugger in case an exception happened.805 806 If you want to run the application in debug mode, but disable the807 code execution on the interactive debugger, you can pass1 unmodified line809 traceback screen active, but disable code execution.810 811 It is not recommended to use this function for development with812 automatic reloading as this is badly supported. Instead you should794- be using the :command:`flask` command line script's ``runserver``795- support.813+ be using the :command:`flask` command line script's ``run`` support.814 815 .. admonition:: Keep in Mind816 817 Flask will suppress any server error with a generic error page8 unmodified lines826 The default port is now picked from the ``SERVER_NAME`` variable.827 828 :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to829 have the server available externally as well. Defaults to812- ``'127.0.0.1'``.830+ ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config831+ variable if present.832 :param port: the port of the webserver. Defaults to ``5000`` or the833 port defined in the ``SERVER_NAME`` config variable if834 present.835 :param debug: if given, enable or disable debug mode.2 unmodified lines838 Werkzeug server. See839 :func:`werkzeug.serving.run_simple` for more840 information.841 """842+ # Change this into a no-op if the server is invoked from the843+ # command line. Have a look at cli.py for more information.844+ if os.environ.get('FLASK_RUN_FROM_CLI_SERVER') == '1':845+ from .debughelpers import explain_ignored_app_run846+ explain_ignored_app_run()847+ return848+849 from werkzeug.serving import run_simple824- if host is None:825- host = '127.0.0.1'826- if port is None:827- server_name = self.config['SERVER_NAME']828- if server_name and ':' in server_name:829- port = int(server_name.rsplit(':', 1)[1])830- else:831- port = 5000850+ _host = '127.0.0.1'851+ _port = 5000852+ server_name = self.config.get("SERVER_NAME")853+ sn_host, sn_port = None, None854+ if server_name:855+ sn_host, _, sn_port = server_name.partition(':')856+ host = host or sn_host or _host857+ port = int(port or sn_port or _port)858 if debug is not None:859 self.debug = bool(debug)860 options.setdefault('use_reloader', self.debug)861 options.setdefault('use_debugger', self.debug)862 try:863 run_simple(host, port, self, **options)864 finally:865 # reset the first request information if the development server840- # resetted normally. This makes it possible to restart the server866+ # reset normally. This makes it possible to restart the server867 # without reloader and that stuff from an interactive shell.868 self._got_first_request = False869 870 def test_client(self, use_cookies=True, **kwargs):25 unmodified lines896 897 from flask.testing import FlaskClient898 899 class CustomClient(FlaskClient):874- def __init__(self, authentication=None, *args, **kwargs):875- FlaskClient.__init__(*args, **kwargs)876- self._authentication = authentication900+ def __init__(self, *args, **kwargs):901+ self._authentication = kwargs.pop("authentication")902+ super(CustomClient,self).__init__( *args, **kwargs)903 904 app.test_client_class = CustomClient905 client = app.test_client(authentication='Basic ....')906 6 unmodified lines913 The `use_cookies` parameter was added as well as the ability914 to override the client to be used by setting the915 :attr:`test_client_class` attribute.916 891- .. versionchanged:: 1.0917+ .. versionchanged:: 0.11918 Added `**kwargs` to support passing additional keyword arguments to919 the constructor of :attr:`test_client_class`.920 """921 cls = self.test_client_class52 unmodified lines974 975 def iter_blueprints(self):976 """Iterates over all blueprints by the order they were registered.977 952- .. versionadded:: 1.0978+ .. versionadded:: 0.11979 """980 return iter(self._blueprint_order)981 982 @setupmethod957- def add_url_rule(self, rule, endpoint=None, view_func=None, **options):983+ def add_url_rule(self, rule, endpoint=None, view_func=None, provide_automatic_options=None, **options):984 """Connects a URL rule. Works exactly like the :meth:`route`985 decorator. If a view_func is provided it will be registered with the986 endpoint.987 31 unmodified lines1019 itself assumes the name of the view function as1020 endpoint1021 :param view_func: the function to call when serving a request to the1022 provided endpoint1023+ :param provide_automatic_options: controls whether the ``OPTIONS``1024+ method should be added automatically. This can also be controlled1025+ by setting the ``view_func.provide_automatic_options = False``1026+ before adding the rule.1027 :param options: the options to be forwarded to the underlying1028 :class:`~werkzeug.routing.Rule` object. A change1029 to Werkzeug is handling of method options. methods1030 is a list of methods this rule should be limited21 unmodified lines1052 required_methods = set(getattr(view_func, 'required_methods', ()))1053 1054 # starting with Flask 0.8 the view_func object can disable and1055 # force-enable the automatic options handling.1056+ if provide_automatic_options is None:1026- provide_automatic_options = getattr(view_func,1027- 'provide_automatic_options', None)1057+ provide_automatic_options = getattr(view_func,1058+ 'provide_automatic_options', None)1059 1060 if provide_automatic_options is None:1061 if 'OPTIONS' not in methods:1062 provide_automatic_options = True77 unmodified lines1140 return exc_class, None1141 1142 @setupmethod1143 def errorhandler(self, code_or_exception):1113- """A decorator that is used to register a function give a given1144+ """A decorator that is used to register a function given an1145 error code. Example::1146 1147 @app.errorhandler(404)1148 def page_not_found(error):29 unmodified lines1178 One can now additionally also register custom exception types1179 that do not necessarily have to be a subclass of the1180 :class:`~werkzeug.exceptions.HTTPException` class.1181 1151- :param code: the code as integer for the handler1182+ :param code_or_exception: the code as integer for the handler, or1183+ an arbitrary exception1184 """1185 def decorator(f):1186 self._register_error_handler(None, code_or_exception, f)1187 return f185 unmodified lines1373 that they will fail. If they do execute code that might fail they1374 will have to surround the execution of these code by try/except1375 statements and log occurring errors.1376 1345- When a teardown function was called because of a exception it will1377+ When a teardown function was called because of an exception it will1378 be passed an error object.1379 1380 The return values of teardown functions are ignored.1381 47 unmodified lines1429 @setupmethod1430 def shell_context_processor(self, f):1431 """Registers a shell context processor function.1432 1401- .. versionadded:: 1.01433+ .. versionadded:: 0.111434 """1435 self.shell_context_processors.append(f)1436 return f1437 24 unmodified lines1462 1463 def find_handler(handler_map):1464 if not handler_map:1465 return1434- queue = deque(exc_class.__mro__)1435- # Protect from geniuses who might create circular references in1436- # __mro__1437- done = set()1438-1439- while queue:1440- cls = queue.popleft()1441- if cls in done:1442- continue1443- done.add(cls)1466+ for cls in exc_class.__mro__:1467 handler = handler_map.get(cls)1468 if handler is not None:1469 # cache for next time exc_class is raised1470 handler_map[exc_class] = handler1471 return handler1472 1450- queue.extend(cls.__mro__)1451-1473 # try blueprint handlers1474 handler = find_handler(self.error_handler_spec1475 .get(request.blueprint, {})1476 .get(code))93 unmodified lines1570 1571 self.log_exception((exc_type, exc_value, tb))1572 if handler is None:1573 return InternalServerError()1553- return handler(e)1574+ return self.finalize_request(handler(e), from_error_handler=True)1575 1576 def log_exception(self, exc_info):1577 """Logs an exception. This is called by :meth:`handle_exception`1578 if debugging is disabled and right before the handler is called.59 unmodified lines1638 if rv is None:1639 rv = self.dispatch_request()1640 except Exception as e:1641 rv = self.handle_user_exception(e)1642+ return self.finalize_request(rv)1643+1644+ def finalize_request(self, rv, from_error_handler=False):1645+ """Given the return value from a view function this finalizes1646+ the request by converting it into a response and invoking the1647+ postprocessing functions. This is invoked for both normal1648+ request dispatching as well as error handlers.1649+1650+ Because this means that it might be called as a result of a1651+ failure a special safe mode is available which can be enabled1652+ with the `from_error_handler` flag. If enabled, failures in1653+ response processing will be logged and otherwise ignored.1654+1655+ :internal:1656+ """1657 response = self.make_response(rv)1658+ try:1622- response = self.process_response(response)1623- request_finished.send(self, response=response)1659+ response = self.process_response(response)1660+ request_finished.send(self, response=response)1661+ except Exception:1662+ if not from_error_handler:1663+ raise1664+ self.logger.exception('Request finalizing failed with an '1665+ 'error while handling an error')1666 return response1667 1668 def try_trigger_before_first_request_functions(self):1669 """Called before each request and will ensure that it triggers44 unmodified lines1714 """1715 return False1716 1717 def make_response(self, rv):1676- """Converts the return value from a view function to a real1677- response object that is an instance of :attr:`response_class`.1718+ """Convert the return value from a view function to an instance of1719+ :attr:`response_class`.1720 1679- The following types are allowed for `rv`:1721+ :param rv: the return value from the view function. The view function1722+ must return a response. Returning ``None``, or the view ending1723+ without returning, is not allowed. The following types are allowed1724+ for ``view_rv``:1725 1681- .. tabularcolumns:: |p{3.5cm}|p{9.5cm}|1726+ ``str`` (``unicode`` in Python 2)1727+ A response object is created with the string encoded to UTF-81728+ as the body.1729+ 1730+ ``bytes`` (``str`` in Python 2)1731+ A response object is created with the bytes as the body.1732+ 1733+ ``tuple``1734+ Either ``(body, status, headers)``, ``(body, status)``, or1735+ ``(body, headers)``, where ``body`` is any of the other types1736+ allowed here, ``status`` is a string or an integer, and1737+ ``headers`` is a dictionary or a list of ``(key, value)``1738+ tuples. If ``body`` is a :attr:`response_class` instance,1739+ ``status`` overwrites the exiting value and ``headers`` are1740+ extended.1741+ 1742+ :attr:`response_class`1743+ The object is returned unchanged.1744+ 1745+ other :class:`~werkzeug.wrappers.Response` class1746+ The object is coerced to :attr:`response_class`.1747+ 1748+ :func:`callable`1749+ The function is called as a WSGI application. The result is1750+ used to create a response object.1751 1683- ======================= ===========================================1684- :attr:`response_class` the object is returned unchanged1685- :class:`str` a response object is created with the1686- string as body1687- :class:`unicode` a response object is created with the1688- string encoded to utf-8 as body1689- a WSGI function the function is called as WSGI application1690- and buffered as response object1691- :class:`tuple` A tuple in the form ``(response, status,1692- headers)`` or ``(response, headers)``1693- where `response` is any of the1694- types defined here, `status` is a string1695- or an integer and `headers` is a list or1696- a dictionary with header values.1697- ======================= ===========================================1698-1699- :param rv: the return value from the view function1700-1752 .. versionchanged:: 0.91753 Previously a tuple was interpreted as the arguments for the1754 response object.1755 """1705- status_or_headers = headers = None1706- if isinstance(rv, tuple):1707- rv, status_or_headers, headers = rv + (None,) * (3 - len(rv))1756 1709- if rv is None:1710- raise ValueError('View function did not return a response')1757+ status = headers = None1758 1712- if isinstance(status_or_headers, (dict, list)):1713- headers, status_or_headers = status_or_headers, None1759+ # unpack tuple returns1760+ if isinstance(rv, (tuple, list)):1761+ len_rv = len(rv)1762 1763+ # a 3-tuple is unpacked directly1764+ if len_rv == 3:1765+ rv, status, headers = rv1766+ # decide if a 2-tuple has status or headers1767+ elif len_rv == 2:1768+ if isinstance(rv[1], (Headers, dict, tuple, list)):1769+ rv, headers = rv1770+ else:1771+ rv, status = rv1772+ # other sized tuples are not allowed1773+ else:1774+ raise TypeError(1775+ 'The view function did not return a valid response tuple.'1776+ ' The tuple must have the form (body, status, headers),'1777+ ' (body, status), or (body, headers).'1778+ )1779+1780+ # the body must not be None1781+ if rv is None:1782+ raise TypeError(1783+ 'The view function did not return a valid response. The'1784+ ' function either returned None or ended without a return'1785+ ' statement.'1786+ )1787+1788+ # make sure the body is an instance of the response class1789 if not isinstance(rv, self.response_class):1716- # When we create a response object directly, we let the constructor1717- # set the headers and status. We do this because there can be1718- # some extra logic involved when creating these objects with1719- # specific values (like default content type selection).1790 if isinstance(rv, (text_type, bytes, bytearray)):1721- rv = self.response_class(rv, headers=headers,1722- status=status_or_headers)1723- headers = status_or_headers = None1791+ # let the response class set the status and headers instead of1792+ # waiting to do it manually, so that the class can handle any1793+ # special logic1794+ rv = self.response_class(rv, status=status, headers=headers)1795+ status = headers = None1796 else:1797+ # evaluate a WSGI callable, or coerce a different response1798+ # class to the correct type1799+ try:1725- rv = self.response_class.force_type(rv, request.environ)1800+ rv = self.response_class.force_type(rv, request.environ)1801+ except TypeError as e:1802+ new_error = TypeError(1803+ '{e}\nThe view function did not return a valid'1804+ ' response. The return type must be a string, tuple,'1805+ ' Response instance, or WSGI callable, but it was a'1806+ ' {rv.__class__.__name__}.'.format(e=e, rv=rv)1807+ )1808+ reraise(TypeError, new_error, sys.exc_info()[2])1809 1810+ # prefer the status if it was provided1727- if status_or_headers is not None:1728- if isinstance(status_or_headers, string_types):1729- rv.status = status_or_headers1811+ if status is not None:1812+ if isinstance(status, (text_type, bytes, bytearray)):1813+ rv.status = status1814 else:1731- rv.status_code = status_or_headers1815+ rv.status_code = status1816+1817+ # extend existing headers with provided headers1818 if headers:1819 rv.headers.extend(headers)1820 1821 return rv225 unmodified lines2047 a list of headers and an optional2048 exception context to start the response2049 """2050 ctx = self.request_context(environ)1965- ctx.push()2051 error = None2052 try:2053 try:2054+ ctx.push()2055 response = self.full_dispatch_request()2056 except Exception as e:2057 error = e1972- response = self.make_response(self.handle_exception(e))2058+ response = self.handle_exception(e)2059+ except:2060+ error = sys.exc_info()[1]2061+ raise2062 return response(environ, start_response)2063 finally:2064 if self.should_ignore_error(error):2065 error = None11 unmodified linesmodified:flask/blueprints.py+8 added-1 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 def __init__(self, name, import_name, static_folder=None,100 static_url_path=None, template_folder=None,101 url_prefix=None, subdomain=None, url_defaults=None,102 root_path=None):310 unmodified lines413 function, akin to the :meth:`~flask.Flask.register_error_handler`414 application-wide function of the :class:`~flask.Flask` object but415 for error handlers limited to this blueprint.416 410- .. versionadded:: 1.0417+ .. versionadded:: 0.11418 """419 self.record_once(lambda s: s.app._register_error_handler(420 self.name, code_or_exception, f))modified:flask/cli.py+123 added-92 removed
9 unmodified lines10 """11 12 import os13 import sys14+import traceback15 from threading import Lock, Thread16 from functools import update_wrapper17 18 import click19 20 from ._compat import iteritems, reraise21+from .helpers import get_debug_flag22+from . import __version__23 21-24 class NoAppException(click.UsageError):25 """Raised if an application cannot be found or loaded."""26 27 27 unmodified lines55 """56 module = []57 58 # Chop off file extensions or package markers57- if filename.endswith('.py'):58- filename = filename[:-3]59- elif os.path.split(filename)[1] == '__init__.py':59+ if os.path.split(filename)[1] == '__init__.py':60 filename = os.path.dirname(filename)61+ elif filename.endswith('.py'):62+ filename = filename[:-3]63 else:64 raise NoAppException('The file provided (%s) does exist but is not a '65 'valid Python file. This means that it cannot '66 'be used as application. Please change the '19 unmodified lines86 else:87 module = app_id88 app_obj = None89 90+ try:88- __import__(module)91+ __import__(module)92+ except ImportError:93+ # Reraise the ImportError if it occurred within the imported module.94+ # Determine this by checking whether the trace has a depth > 1.95+ if sys.exc_info()[-1].tb_next:96+ stack_trace = traceback.format_exc()97+ raise NoAppException('There was an error trying to import'98+ ' the app (%s):\n%s' % (module, stack_trace))99+ else:100+ raise NoAppException('The file/path provided (%s) does not appear'101+ ' to exist. Please verify the path is '102+ 'correct. If app is not on PYTHONPATH, '103+ 'ensure the extension is .py' % module)104+105 mod = sys.modules[module]106 if app_obj is None:107 app = find_best_app(mod)108 else:4 unmodified lines113 114 return app115 116 117+def find_default_import_path():118+ app = os.environ.get('FLASK_APP')119+ if app is None:120+ return121+ if os.path.isfile(app):122+ return prepare_exec_for_file(app)123+ return app124+125+126+def get_version(ctx, param, value):127+ if not value or ctx.resilient_parsing:128+ return129+ message = 'Flask %(version)s\nPython %(python_version)s'130+ click.echo(message % {131+ 'version': __version__,132+ 'python_version': sys.version,133+ }, color=ctx.color)134+ ctx.exit()135+136+version_option = click.Option(['--version'],137+ help='Show the flask version',138+ expose_value=False,139+ callback=get_version,140+ is_flag=True, is_eager=True)141+142 class DispatchingApp(object):102- """Special application that dispatches to a flask application which143+ """Special application that dispatches to a Flask application which144 is imported by name in a background thread. If an error happens104- it is is recorded and shows as part of the WSGI handling which in case145+ it is recorded and shown as part of the WSGI handling which in case146 of the Werkzeug debugger means that it shows up in the browser.147 """148 149 def __init__(self, loader, use_eager_loading=False):45 unmodified lines195 196 class ScriptInfo(object):197 """Help object to deal with Flask applications. This is usually not198 necessary to interface with as it's used internally in the dispatching158- to click.199+ to click. In future versions of Flask this object will most likely play200+ a bigger role. Typically it's created automatically by the201+ :class:`FlaskGroup` but you can also manually create it and pass it202+ onwards as click object.203 """204 161- def __init__(self, app_import_path=None, debug=None, create_app=None):162- #: The application import path205+ def __init__(self, app_import_path=None, create_app=None):206+ if create_app is None:207+ if app_import_path is None:208+ app_import_path = find_default_import_path()209+ self.app_import_path = app_import_path210+ else:211+ app_import_path = None212+213+ #: Optionally the import path for the Flask application.214 self.app_import_path = app_import_path164- #: The debug flag. If this is not None, the application will165- #: automatically have it's debug flag overridden with this value.166- self.debug = debug215 #: Optionally a function that is passed the script info to create216 #: the instance of the application.217 self.create_app = create_app218 #: A dictionary with arbitrary data that can be associated with11 unmodified lines230 return self._loaded_app231 if self.create_app is not None:232 rv = self.create_app(self)233 else:186- if self.app_import_path is None:187- raise NoAppException('Could not locate Flask application. '188- 'You did not provide FLASK_APP or the '189- '--app parameter.')234+ if not self.app_import_path:235+ raise NoAppException(236+ 'Could not locate Flask application. You did not provide '237+ 'the FLASK_APP environment variable.\n\nFor more '238+ 'information see '239+ 'http://flask.pocoo.org/docs/latest/quickstart/')240 rv = locate_app(self.app_import_path)241+ debug = get_debug_flag()191- if self.debug is not None:192- rv.debug = self.debug242+ if debug is not None:243+ rv.debug = debug244 self._loaded_app = rv245 return rv246 247 12 unmodified lines260 return __ctx.invoke(f, *args, **kwargs)261 return update_wrapper(decorator, f)262 263 213-def set_debug_value(ctx, param, value):214- ctx.ensure_object(ScriptInfo).debug = value215-216-217-def set_app_value(ctx, param, value):218- if value is not None:219- if os.path.isfile(value):220- value = prepare_exec_for_file(value)221- elif '.' not in sys.path:222- sys.path.insert(0, '.')223- ctx.ensure_object(ScriptInfo).app_import_path = value224-225-226-debug_option = click.Option(['--debug/--no-debug'],227- help='Enable or disable debug mode.',228- default=None, callback=set_debug_value)229-230-231-app_option = click.Option(['-a', '--app'],232- help='The application to run',233- callback=set_app_value, is_eager=True)234-235-264 class AppGroup(click.Group):265 """This works similar to a regular click :class:`~click.Group` but it266 changes the behavior of the :meth:`command` decorator so that it267 automatically wraps the functions in :func:`with_appcontext`.32 unmodified lines300 For information as of why this is useful see :ref:`custom-scripts`.301 302 :param add_default_commands: if this is True then the default run and303 shell commands wil be added.276- :param add_app_option: adds the default :option:`--app` option. This gets277- automatically disabled if a `create_app`278- callback is defined.279- :param add_debug_option: adds the default :option:`--debug` option.304+ :param add_version_option: adds the ``--version`` option.305 :param create_app: an optional callback that is passed the script info306 and returns the loaded app.307 """308 284- def __init__(self, add_default_commands=True, add_app_option=None,285- add_debug_option=True, create_app=None, **extra):309+ def __init__(self, add_default_commands=True, create_app=None,310+ add_version_option=True, **extra):311 params = list(extra.pop('params', None) or ())287- if add_app_option is None:288- add_app_option = create_app is None289- if add_app_option:290- params.append(app_option)291- if add_debug_option:292- params.append(debug_option)312 313+ if add_version_option:314+ params.append(version_option)315+316 AppGroup.__init__(self, params=params, **extra)317 self.create_app = create_app318 319 if add_default_commands:320 self.add_command(run_command)321 self.add_command(shell_command)322 323+ self._loaded_plugin_commands = False324+325+ def _load_plugin_commands(self):326+ if self._loaded_plugin_commands:327+ return328+ try:329+ import pkg_resources330+ except ImportError:331+ self._loaded_plugin_commands = True332+ return333+334+ for ep in pkg_resources.iter_entry_points('flask.commands'):335+ self.add_command(ep.load(), ep.name)336+ self._loaded_plugin_commands = True337+338 def get_command(self, ctx, name):339+ self._load_plugin_commands()340+341 # We load built-in commands first as these should always be the342 # same no matter what the app does. If the app does want to343 # override this it needs to make a custom instance of this group344 # and not attach the default commands.12 unmodified lines357 except NoAppException:358 pass359 360 def list_commands(self, ctx):361+ self._load_plugin_commands()362+363 # The commands available is the list of both the application (if364 # available) plus the builtin commands.365 rv = set(click.Group.list_commands(self, ctx))366 info = ctx.ensure_object(ScriptInfo)3 unmodified lines370 # Here we intentionally swallow all exceptions as we don't371 # want the help page to break if the app does not exist.372 # If someone attempts to use the command we try to create373 # the app again and this will give us the error.333- pass374+ # However, we will not do so silently because that would confuse375+ # users.376+ traceback.print_exc()377 return sorted(rv)378 379 def main(self, *args, **kwargs):380 obj = kwargs.get('obj')3 unmodified lines384 kwargs.setdefault('auto_envvar_prefix', 'FLASK')385 return AppGroup.main(self, *args, **kwargs)386 387 345-def script_info_option(*args, **kwargs):346- """This decorator works exactly like :func:`click.option` but is eager347- by default and stores the value in the :attr:`ScriptInfo.data`. This348- is useful to further customize an application factory in very complex349- situations.350-351- :param script_info_key: this is a mandatory keyword argument which352- defines under which data key the value should353- be stored.354- """355- try:356- key = kwargs.pop('script_info_key')357- except LookupError:358- raise TypeError('script_info_key not provided.')359-360- real_callback = kwargs.get('callback')361- def callback(ctx, param, value):362- if real_callback is not None:363- value = real_callback(ctx, value)364- ctx.ensure_object(ScriptInfo).data[key] = value365- return value366-367- kwargs['callback'] = callback368- kwargs.setdefault('is_eager', True)369- return click.option(*args, **kwargs)370-371-388 @click.command('run', short_help='Runs a development server.')389 @click.option('--host', '-h', default='127.0.0.1',390 help='The interface to bind to.')391 @click.option('--port', '-p', default=5000,23 unmodified lines415 The reloader and debugger are by default enabled if the debug flag of416 Flask is enabled and disabled otherwise.417 """418 from werkzeug.serving import run_simple419+420+ # Set a global flag that indicates that we were invoked from the421+ # command line interface provided server command. This is detected422+ # by Flask.run to make the call into a no-op. This is necessary to423+ # avoid ugly errors when the script that is loaded here also attempts424+ # to start a server.425+ os.environ['FLASK_RUN_FROM_CLI_SERVER'] = '1'426+427+ debug = get_debug_flag()428 if reload is None:404- reload = info.debug429+ reload = bool(debug)430 if debugger is None:406- debugger = info.debug431+ debugger = bool(debug)432 if eager_loading is None:433 eager_loading = not reload434 435 app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)436 412- # Extra startup messages. This depends a but on Werkzeug internals to437+ # Extra startup messages. This depends a bit on Werkzeug internals to438 # not double execute when the reloader kicks in.439 if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':440 # If we have an import path we can print it out now which can help441 # people understand what's being served. If we do not have an442 # import path because the app was loaded through a callback then443 # we won't print anything.444 if info.app_import_path is not None:445 print(' * Serving Flask app "%s"' % info.app_import_path)421- if info.debug is not None:422- print(' * Forcing debug %s' % (info.debug and 'on' or 'off'))446+ if debug is not None:447+ print(' * Forcing debug mode %s' % (debug and 'on' or 'off'))448 449 run_simple(host, port, app, use_reloader=reload,450 use_debugger=debugger, threaded=with_threads)451 34 unmodified lines486 487 cli = FlaskGroup(help="""\488 This shell command acts as general utility script for Flask applications.489 465-It loads the application configured (either through the FLASK_APP environment466-variable or the --app parameter) and then provides commands either provided467-by the application or Flask itself.490+It loads the application configured (through the FLASK_APP environment491+variable) and then provides commands either provided by the application or492+Flask itself.493 494 The most useful commands are the "run" and "shell" command.495 496 Example usage:497 473- flask --app=hello --debug run474-""")498+\b499+ %(prefix)s%(cmd)s FLASK_APP=hello.py500+ %(prefix)s%(cmd)s FLASK_DEBUG=1501+ %(prefix)sflask run502+""" % {503+ 'cmd': os.name == 'posix' and 'export' or 'set',504+ 'prefix': os.name == 'posix' and '$ ' or '',505+})506 507 508 def main(as_module=False):509 this_module = __package__ + '.cli'20 unmodified linesmodified:flask/config.py+13 added-8 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 False8 unmodified lines142 143 - a string: in this case the object with that name will be imported144 - an actual object reference: that object is used directly145 146- Objects are usually either modules or classes.146+ Objects are usually either modules or classes. :meth:`from_object`147+ loads only the uppercase attributes of the module/class. A ``dict``148+ object will not work with :meth:`from_object` because the keys of a149+ ``dict`` are not attributes of the ``dict`` class.150 148- Just the uppercase variables in that object are stored in the config.149- Example usage::151+ Example of module-based configuration::152 153 app.config.from_object('yourapplication.default_config')154 from yourapplication import default_config155 app.config.from_object(default_config)2 unmodified lines158 rather configuration defaults. The actual config should be loaded159 with :meth:`from_pyfile` and ideally from a location not within the160 package because the package might be installed system wide.161 162+ See :ref:`config-dev-prod` for an example of class-based configuration163+ using :meth:`from_object`.164+165 :param obj: an import name or object166 """167 if isinstance(obj, string_types):168 obj = import_string(obj)11 unmodified lines180 root path.181 :param silent: set to ``True`` if you want silent failure for missing182 files.183 179- .. versionadded:: 1.0184+ .. versionadded:: 0.11185 """186 filename = os.path.join(self.root_path, filename)187 188 try:9 unmodified lines198 def from_mapping(self, *mapping, **kwargs):199 """Updates the config like :meth:`update` ignoring items with non-upper200 keys.201 197- .. versionadded:: 1.0202+ .. versionadded:: 0.11203 """204 mappings = []205 if len(mapping) == 1:206 if hasattr(mapping[0], 'items'):19 unmodified lines226 app.config['IMAGE_STORE_PATH'] = '/var/app/images'227 app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'228 image_store_config = app.config.get_namespace('IMAGE_STORE_')229 225- The resulting dictionary `image_store` would look like::230+ The resulting dictionary `image_store_config` would look like::231 232 {233 'type': 'fs',234 'path': '/var/app/images',8 unmodified lines243 dictionary should be lowercase244 :param trim_namespace: a flag indicating if the keys of the resulting245 dictionary should not include the namespace246 242- .. versionadded:: 1.0247+ .. versionadded:: 0.11248 """249 rv = {}250 for k, v in iteritems(self):251 if not k.startswith(namespace):12 unmodified linesmodified:flask/ctx.py+38 added-34 removed
34 unmodified lines35 else:36 return self.__dict__.pop(name, default)37 38 def setdefault(self, name, default=None):39- self.__dict__.setdefault(name, default)39+ return self.__dict__.setdefault(name, default)40 41 def __contains__(self, item):42 return item in self.__dict__43 136 unmodified lines180 appcontext_pushed.send(self.app)181 182 def pop(self, exc=_sentinel):183 """Pops the app context."""184+ try:184- self._refcnt -= 1185- if self._refcnt <= 0:186- if exc is _sentinel:187- exc = sys.exc_info()[1]188- self.app.do_teardown_appcontext(exc)189- rv = _app_ctx_stack.pop()185+ self._refcnt -= 1186+ if self._refcnt <= 0:187+ if exc is _sentinel:188+ exc = sys.exc_info()[1]189+ self.app.do_teardown_appcontext(exc)190+ finally:191+ rv = _app_ctx_stack.pop()192 assert rv is self, 'Popped wrong app context. (%r instead of %r)' \193 % (rv, self)194 appcontext_popped.send(self.app)195 146 unmodified lines342 Added the `exc` argument.343 """344 app_ctx = self._implicit_app_ctx_stack.pop()345 346+ try:344- clear_request = False345- if not self._implicit_app_ctx_stack:346- self.preserved = False347- self._preserved_exc = None348- if exc is _sentinel:349- exc = sys.exc_info()[1]350- self.app.do_teardown_request(exc)347+ clear_request = False348+ if not self._implicit_app_ctx_stack:349+ self.preserved = False350+ self._preserved_exc = None351+ if exc is _sentinel:352+ exc = sys.exc_info()[1]353+ self.app.do_teardown_request(exc)354 352- # If this interpreter supports clearing the exception information353- # we do that now. This will only go into effect on Python 2.x,354- # on 3.x it disappears automatically at the end of the exception355- # stack.356- if hasattr(sys, 'exc_clear'):357- sys.exc_clear()355+ # If this interpreter supports clearing the exception information356+ # we do that now. This will only go into effect on Python 2.x,357+ # on 3.x it disappears automatically at the end of the exception358+ # stack.359+ if hasattr(sys, 'exc_clear'):360+ sys.exc_clear()361 359- request_close = getattr(self.request, 'close', None)360- if request_close is not None:361- request_close()362- clear_request = True362+ request_close = getattr(self.request, 'close', None)363+ if request_close is not None:364+ request_close()365+ clear_request = True366+ finally:367+ rv = _request_ctx_stack.pop()368 364- rv = _request_ctx_stack.pop()365- assert rv is self, 'Popped wrong request context. (%r instead of %r)' \366- % (rv, self)369+ # get rid of circular dependencies at the end of the request370+ # so that we don't require the GC to be active.371+ if clear_request:372+ rv.request.environ['werkzeug.request'] = None373 368- # get rid of circular dependencies at the end of the request369- # so that we don't require the GC to be active.370- if clear_request:371- rv.request.environ['werkzeug.request'] = None374+ # Get rid of the app as well if necessary.375+ if app_ctx is not None:376+ app_ctx.pop(exc)377 373- # Get rid of the app as well if necessary.374- if app_ctx is not None:375- app_ctx.pop(exc)378+ assert rv is self, 'Popped wrong request context. ' \379+ '(%r instead of %r)' % (rv, self)380 381 def auto_pop(self, exc):382 if self.request.environ.get('flask._preserve_context') or \383 (exc is not None and self.app.preserve_context_on_exception):27 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/exthook.py+24 added-1 removed
19 unmodified lines20 :license: BSD, see LICENSE for more details.21 """22 import sys23 import os24+import warnings25 from ._compat import reraise26 27 28+class ExtDeprecationWarning(DeprecationWarning):29+ pass30+31+warnings.simplefilter('always', ExtDeprecationWarning)32+33+34 class ExtensionImporter(object):35 """This importer redirects imports from this submodule to other locations.36 This makes it possible to transition from the old flaskext.name to the37 newer flask_name without people having a hard time.17 unmodified lines55 def install(self):56 sys.meta_path[:] = [x for x in sys.meta_path if self != x] + [self]57 58 def find_module(self, fullname, path=None):52- if fullname.startswith(self.prefix):59+ if fullname.startswith(self.prefix) and \60+ fullname != 'flask.ext.ExtDeprecationWarning':61 return self62 63 def load_module(self, fullname):64 if fullname in sys.modules:65 return sys.modules[fullname]66+67 modname = fullname.split('.', self.prefix_cutoff)[self.prefix_cutoff]68+69+ warnings.warn(70+ "Importing flask.ext.{x} is deprecated, use flask_{x} instead."71+ .format(x=modname), ExtDeprecationWarning, stacklevel=272+ )73+74 for path in self.module_choices:75 realname = path % modname76 try:77 __import__(realname)19 unmodified lines97 continue98 module = sys.modules[fullname] = sys.modules[realname]99 if '.' not in modname:100 setattr(sys.modules[self.wrapper_module], modname, module)101+102+ if realname.startswith('flaskext.'):103+ warnings.warn(104+ "Detected extension named flaskext.{x}, please rename it "105+ "to flask_{x}. The old form is deprecated."106+ .format(x=modname), ExtDeprecationWarning107+ )108+109 return module110 raise ImportError('No module named %s' % fullname)111 112 def is_important_traceback(self, important_module, tb):31 unmodified linesmodified:flask/helpers.py+133 added-67 removed
12 unmodified lines13 import sys14 import pkgutil15 import posixpath16 import mimetypes17-from datetime import timedelta17 from time import time18 from zlib import adler3219 from threading import RLock20+import unicodedata21 from werkzeug.routing import BuildError22 from functools import update_wrapper23 24 try:25 from werkzeug.urls import url_quote26 except ImportError:27 from urlparse import quote as url_quote28 29-from werkzeug.datastructures import Headers30-from werkzeug.exceptions import NotFound29+from werkzeug.datastructures import Headers, Range30+from werkzeug.exceptions import BadRequest, NotFound, \31+ RequestedRangeNotSatisfiable32 33 # this was moved in 0.734 try:35 from werkzeug.wsgi import wrap_file18 unmodified lines54 _os_alt_seps = list(sep for sep in [os.path.sep, os.path.altsep]55 if sep not in (None, '/'))56 57 58+def get_debug_flag(default=None):59+ val = os.environ.get('FLASK_DEBUG')60+ if not val:61+ return default62+ return val.lower() not in ('0', 'false', 'no')63+64+65 def _endpoint_from_view_func(view_func):66 """Internal helper that returns the default endpoint for a given67 function. This always is the function name.68 """39 unmodified lines108 try:109 gen = iter(generator_or_function)110 except TypeError:111 def decorator(*args, **kwargs):104- gen = generator_or_function()112+ gen = generator_or_function(*args, **kwargs)113 return stream_with_context(gen)114 return update_wrapper(decorator, generator_or_function)115 116 def generator():190 unmodified lines307 method = values.pop('_method', None)308 scheme = values.pop('_scheme', None)309 appctx.app.inject_url_defaults(endpoint, values)310 311+ # This is not the best way to deal with this but currently the312+ # underlying Werkzeug router does not support overriding the scheme on313+ # a per build call basis.314+ old_scheme = None315 if scheme is not None:316 if not external:317 raise ValueError('When specifying _scheme, _external must be True')318+ old_scheme = url_adapter.url_scheme319 url_adapter.url_scheme = scheme320 321 try:322+ try:309- rv = url_adapter.build(endpoint, values, method=method,310- force_external=external)323+ rv = url_adapter.build(endpoint, values, method=method,324+ force_external=external)325+ finally:326+ if old_scheme is not None:327+ url_adapter.url_scheme = old_scheme328 except BuildError as error:329 # We need to inject the values again so that the app callback can330 # deal with that sort of stuff.331 values['_external'] = external332 values['_anchor'] = anchor333 values['_method'] = method334+ values['_scheme'] = scheme335 return appctx.app.handle_url_build_error(error, endpoint, values)336 337 if anchor is not None:338 rv += '#' + url_quote(anchor)92 unmodified lines431 432 433 def send_file(filename_or_fp, mimetype=None, as_attachment=False,434 attachment_filename=None, add_etags=True,417- cache_timeout=None, conditional=False):435+ cache_timeout=None, conditional=False, last_modified=None):436 """Sends the contents of a file to the client. This will use the437 most efficient method available and configured. By default it will438 try to use the WSGI server's file_wrapper support. Alternatively439 you can set the application's :attr:`~Flask.use_x_sendfile` attribute5 unmodified lines445 to send certain files as attachment (HTML for instance). The mimetype446 guessing requires a `filename` or an `attachment_filename` to be447 provided.448 449+ ETags will also be attached automatically if a `filename` is provided. You450+ can turn this off by setting `add_etags=False`.451+452+ If `conditional=True` and `filename` is provided, this method will try to453+ upgrade the response stream to support range requests. This will allow454+ the request to be answered with partial content response.455+456 Please never pass filenames to this function from user sources;457 you should use :func:`send_from_directory` instead.458 459 .. versionadded:: 0.210 unmodified lines470 471 .. versionchanged:: 0.9472 cache_timeout pulls its default from application config, when None.473 474+ .. versionchanged:: 0.12475+ The filename is no longer automatically inferred from file objects. If476+ you want to use automatic mimetype and etag support, pass a filepath via477+ `filename_or_fp` or `attachment_filename`.478+479+ .. versionchanged:: 0.12480+ The `attachment_filename` is preferred over `filename` for MIME-type481+ detection.482+ 483+ .. versionchanged:: 0.13484+ UTF-8 filenames, as specified in `RFC 2231`_, are supported.485+ 486+ .. _RFC 2231: https://tools.ietf.org/html/rfc2231#section-4487+449- :param filename_or_fp: the filename of the file to send in `latin-1`.488+ :param filename_or_fp: the filename of the file to send.489 This is relative to the :attr:`~Flask.root_path`490 if a relative path is specified.491 Alternatively a file object might be provided in492 which case ``X-Sendfile`` might not work and fall493 back to the traditional method. Make sure that the494 file pointer is positioned at the start of data to495 send before calling :func:`send_file`.457- :param mimetype: the mimetype of the file if provided, otherwise458- auto detection happens.496+ :param mimetype: the mimetype of the file if provided. If a file path is497+ given, auto detection happens as fallback, otherwise an498+ error will be raised.499 :param as_attachment: set to ``True`` if you want to send this file with500 a ``Content-Disposition: attachment`` header.501 :param attachment_filename: the filename for the attachment if it502 differs from the file's filename.3 unmodified lines506 :param cache_timeout: the timeout in seconds for the headers. When ``None``507 (default), this value is set by508 :meth:`~Flask.get_send_file_max_age` of509 :data:`~flask.current_app`.510+ :param last_modified: set the ``Last-Modified`` header to this value,511+ a :class:`~datetime.datetime` or timestamp.512+ If a file was passed, this overrides its mtime.513 """514 mtime = None515+ fsize = None516 if isinstance(filename_or_fp, string_types):517 filename = filename_or_fp518+ if not os.path.isabs(filename):519+ filename = os.path.join(current_app.root_path, filename)520 file = None521+ if attachment_filename is None:522+ attachment_filename = os.path.basename(filename)523 else:476- from warnings import warn524 file = filename_or_fp478- filename = getattr(file, 'name', None)525+ filename = None526 480- # XXX: this behavior is now deprecated because it was unreliable.481- # removed in Flask 1.0482- if not attachment_filename and not mimetype \483- and isinstance(filename, string_types):484- warn(DeprecationWarning('The filename support for file objects '485- 'passed to send_file is now deprecated. Pass an '486- 'attach_filename if you want mimetypes to be guessed.'),487- stacklevel=2)488- if add_etags:489- warn(DeprecationWarning('In future flask releases etags will no '490- 'longer be generated for file objects passed to the send_file '491- 'function because this behavior was unreliable. Pass '492- 'filenames instead if possible, otherwise attach an etag '493- 'yourself based on another value'), stacklevel=2)494-495- if filename is not None:496- if not os.path.isabs(filename):497- filename = os.path.join(current_app.root_path, filename)498- if mimetype is None and (filename or attachment_filename):499- mimetype = mimetypes.guess_type(filename or attachment_filename)[0]527 if mimetype is None:528+ if attachment_filename is not None:529+ mimetype = mimetypes.guess_type(attachment_filename)[0] \501- mimetype = 'application/octet-stream'530+ or 'application/octet-stream'531 532+ if mimetype is None:533+ raise ValueError(534+ 'Unable to infer MIME-type because no filename is available. '535+ 'Please set either `attachment_filename`, pass a filepath to '536+ '`filename_or_fp` or set your own MIME-type via `mimetype`.'537+ )538+539 headers = Headers()540 if as_attachment:541 if attachment_filename is None:506- if filename is None:507- raise TypeError('filename unavailable, required for '508- 'sending as attachment')542+ raise TypeError('filename unavailable, required for '543+ 'sending as attachment')509- attachment_filename = os.path.basename(filename)510- headers.add('Content-Disposition', 'attachment',511- filename=attachment_filename)544 545+ try:546+ attachment_filename = attachment_filename.encode('latin-1')547+ except UnicodeEncodeError:548+ filenames = {549+ 'filename': unicodedata.normalize(550+ 'NFKD', attachment_filename).encode('latin-1', 'ignore'),551+ 'filename*': "UTF-8''%s" % url_quote(attachment_filename),552+ }553+ else:554+ filenames = {'filename': attachment_filename}555+556+ headers.add('Content-Disposition', 'attachment', **filenames)557+558 if current_app.use_x_sendfile and filename:559 if file is not None:560 file.close()561 headers['X-Sendfile'] = filename517- headers['Content-Length'] = os.path.getsize(filename)562+ fsize = os.path.getsize(filename)563+ headers['Content-Length'] = fsize564 data = None565 else:566 if file is None:567 file = open(filename, 'rb')568 mtime = os.path.getmtime(filename)523- headers['Content-Length'] = os.path.getsize(filename)569+ fsize = os.path.getsize(filename)570+ headers['Content-Length'] = fsize571 data = wrap_file(request.environ, file)572 573 rv = current_app.response_class(data, mimetype=mimetype, headers=headers,574 direct_passthrough=True)575 529- # if we know the file modification date, we can store it as530- # the time of the last modification.531- if mtime is not None:532- rv.last_modified = int(mtime)576+ if last_modified is not None:577+ rv.last_modified = last_modified578+ elif mtime is not None:579+ rv.last_modified = mtime580 581 rv.cache_control.public = True582 if cache_timeout is None:583 cache_timeout = current_app.get_send_file_max_age(filename)1 unmodified line585 rv.cache_control.max_age = cache_timeout586 rv.expires = int(time() + cache_timeout)587 588 if add_etags and filename is not None:589+ from warnings import warn590+591 try:543- rv.set_etag('flask-%s-%s-%s' % (592+ rv.set_etag('%s-%s-%s' % (593 os.path.getmtime(filename),594 os.path.getsize(filename),595 adler32(596 filename.encode('utf-8') if isinstance(filename, text_type)3 unmodified lines600 except OSError:601 warn('Access %s failed, maybe it does not exist, so ignore etags in '602 'headers' % filename, stacklevel=2)603 555- if conditional:604+ if conditional:605+ if callable(getattr(Range, 'to_content_range_header', None)):606+ # Werkzeug supports Range Requests607+ # Remove this test when support for Werkzeug <0.12 is dropped608+ try:609+ rv = rv.make_conditional(request, accept_ranges=True,610+ complete_length=fsize)611+ except RequestedRangeNotSatisfiable:612+ file.close()613+ raise614+ else:615 rv = rv.make_conditional(request)557- # make sure we don't send x-sendfile for servers that558- # ignore the 304 status code for x-sendfile.559- if rv.status_code == 304:560- rv.headers.pop('x-sendfile', None)616+ # make sure we don't send x-sendfile for servers that617+ # ignore the 304 status code for x-sendfile.618+ if rv.status_code == 304:619+ rv.headers.pop('x-sendfile', None)620 return rv621 622 564-def safe_join(directory, filename):565- """Safely join `directory` and `filename`.623+def safe_join(directory, *pathnames):624+ """Safely join `directory` and zero or more untrusted `pathnames`625+ components.626 627 Example usage::628 629 @app.route('/wiki/<path:filename>')1 unmodified line631 filename = safe_join(app.config['WIKI_FOLDER'], filename)632 with open(filename, 'rb') as fd:633 content = fd.read() # Read and process the file content...634 575- :param directory: the base directory.576- :param filename: the untrusted filename relative to that directory.577- :raises: :class:`~werkzeug.exceptions.NotFound` if the resulting path578- would fall out of `directory`.635+ :param directory: the trusted base directory.636+ :param pathnames: the untrusted pathnames relative to that directory.637+ :raises: :class:`~werkzeug.exceptions.NotFound` if one or more passed638+ paths fall out of its boundaries.639 """640+ for filename in pathnames:641+ if filename != '':580- filename = posixpath.normpath(filename)581- for sep in _os_alt_seps:582- if sep in filename:642+ filename = posixpath.normpath(filename)643+ for sep in _os_alt_seps:644+ if sep in filename:645+ raise NotFound()646+ if os.path.isabs(filename) or \647+ filename == '..' or \648+ filename.startswith('../'):649 raise NotFound()584- if os.path.isabs(filename) or \585- filename == '..' or \586- filename.startswith('../'):587- raise NotFound()588- return os.path.join(directory, filename)650+ directory = os.path.join(directory, filename)651+ return directory652 653 654 def send_from_directory(directory, filename, **options):655 """Send a file from a given directory with :func:`send_file`. This24 unmodified lines680 """681 filename = safe_join(directory, filename)682 if not os.path.isabs(filename):683 filename = os.path.join(current_app.root_path, filename)684+ try:621- if not os.path.isfile(filename):622- raise NotFound()685+ if not os.path.isfile(filename):686+ raise NotFound()687+ except (TypeError, ValueError):688+ raise BadRequest()689 options.setdefault('conditional', True)690 return send_file(filename, **options)691 692 286 unmodified linesmodified:flask/json.py+55 added-29 removed
1 # -*- coding: utf-8 -*-2 """3- flask.jsonimpl4- ~~~~~~~~~~~~~~3+ flask.json4+ ~~~~~~~~~~5 6 Implementation helpers for the JSON support in Flask.7 8 :copyright: (c) 2015 by Armin Ronacher.3 unmodified lines12 import uuid13 from datetime import date14 from .globals import current_app, request15 from ._compat import text_type, PY216+from .ctx import has_request_context17 18 from werkzeug.http import http_date19 from jinja2 import Markup20 21 # Use the same json implementation as itsdangerous on which we22 # depend anyways.22-try:23- from itsdangerous import simplejson as _json24-except ImportError:25- from itsdangerous import json as _json23+from itsdangerous import json as _json24 25 26 # Figure out if simplejson escapes slashes. This behavior was changed27 # from one version to another without reason.63 unmodified lines91 92 def _dump_arg_defaults(kwargs):93 """Inject default arguments for dump functions."""94 if current_app:97- kwargs.setdefault('cls', current_app.json_encoder)95+ bp = current_app.blueprints.get(request.blueprint) if request else None96+ kwargs.setdefault(97+ 'cls',98+ bp.json_encoder if bp and bp.json_encoder99+ else current_app.json_encoder100+ )101+102 if not current_app.config['JSON_AS_ASCII']:103 kwargs.setdefault('ensure_ascii', False)104+105 kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS'])106 else:107 kwargs.setdefault('sort_keys', True)108 kwargs.setdefault('cls', JSONEncoder)1 unmodified line110 111 def _load_arg_defaults(kwargs):112 """Inject default arguments for load functions."""113 if current_app:109- kwargs.setdefault('cls', current_app.json_decoder)114+ bp = current_app.blueprints.get(request.blueprint) if request else None115+ kwargs.setdefault(116+ 'cls',117+ bp.json_decoder if bp and bp.json_decoder118+ else current_app.json_decoder119+ )120 else:121 kwargs.setdefault('cls', JSONDecoder)122 123 80 unmodified lines204 205 206 def htmlsafe_dump(obj, fp, **kwargs):207 """Like :func:`htmlsafe_dumps` but writes into a file object."""198- fp.write(unicode(htmlsafe_dumps(obj, **kwargs)))208+ fp.write(text_type(htmlsafe_dumps(obj, **kwargs)))209 210 211 def jsonify(*args, **kwargs):202- """Creates a :class:`~flask.Response` with the JSON representation of203- the given arguments with an :mimetype:`application/json` mimetype. The204- arguments to this function are the same as to the :class:`dict`205- constructor.212+ """This function wraps :func:`dumps` to add a few enhancements that make213+ life easier. It turns the JSON output into a :class:`~flask.Response`214+ object with the :mimetype:`application/json` mimetype. For convenience, it215+ also converts multiple arguments into an array or multiple keyword arguments216+ into a dict. This means that both ``jsonify(1,2,3)`` and217+ ``jsonify([1,2,3])`` serialize to ``[1,2,3]``.218 219+ For clarity, the JSON serialization behavior has the following differences220+ from :func:`dumps`:221+222+ 1. Single argument: Passed straight through to :func:`dumps`.223+ 2. Multiple arguments: Converted to an array before being passed to224+ :func:`dumps`.225+ 3. Multiple keyword arguments: Converted to a dict before being passed to226+ :func:`dumps`.227+ 4. Both args and kwargs: Behavior undefined and will throw an exception.228+229 Example usage::230 231 from flask import jsonify232 10 unmodified lines243 "email": "admin@localhost",244 "id": 42245 }246 225- For security reasons only objects are supported toplevel. For more226- information about this, have a look at :ref:`json-security`.247 228- This function's response will be pretty printed if it was not requested229- with ``X-Requested-With: XMLHttpRequest`` to simplify debugging unless230- the ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to false.231- Compressed (not pretty) formatting currently means no indents and no232- spaces after separators.248+ .. versionchanged:: 0.11249+ Added support for serializing top-level arrays. This introduces a250+ security risk in ancient browsers. See :ref:`json-security` for details.251 252+ This function's response will be pretty printed if the253+ ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to True or the254+ Flask app is running in debug mode. Compressed (not pretty) formatting255+ currently means no indents and no spaces after separators.256+257 .. versionadded:: 0.2258 """259 260 indent = None261 separators = (',', ':')262 240- if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] \241- and not request.is_xhr:263+ if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug:264 indent = 2265 separators = (', ', ': ')266 245- # Note that we add '\n' to end of response246- # (see https://github.com/mitsuhiko/flask/pull/1262)247- rv = current_app.response_class(248- (dumps(dict(*args, **kwargs), indent=indent, separators=separators),249- '\n'),250- mimetype='application/json')251- return rv267+ if args and kwargs:268+ raise TypeError('jsonify() behavior undefined when passed both args and kwargs')269+ elif len(args) == 1: # single args are passed directly to dumps()270+ data = args[0]271+ else:272+ data = args or kwargs273 274+ return current_app.response_class(275+ (dumps(data, indent=indent, separators=separators), '\n'),276+ mimetype=current_app.config['JSONIFY_MIMETYPE']277+ )278 279+280 def tojson_filter(obj, **kwargs):281 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+16 added-12 removed
82 unmodified lines83 84 def dumps(self, value):85 return json.dumps(_tag(value), separators=(',', ':'))86 87+ LOADS_MAP = {88+ ' t': tuple,89+ ' u': uuid.UUID,90+ ' b': b64decode,91+ ' m': Markup,92+ ' d': parse_date,93+ }94+95 def loads(self, value):96 def object_hook(obj):97 if len(obj) != 1:98 return obj99 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)100+ # Check the key for a corresponding function101+ return_function = self.LOADS_MAP.get(the_key)102+ if return_function:103+ # Pass the value to the function104+ return return_function(the_value)105+ # Didn't find a function for this object106 return obj107 return json.loads(value, object_hook=object_hook)108 109 61 unmodified lines171 #: this type.172 null_session_class = NullSession173 174 #: A flag that indicates if the session interface is pickle based.171- #: This can be used by flask extensions to make a decision in regards175+ #: This can be used by Flask extensions to make a decision in regards176 #: to how to deal with the session object.177 #:178 #: .. versionadded:: 0.10179 pickle_based = False86 unmodified lines266 permanent.267 268 This check is usually skipped if sessions get deleted.269 266- .. versionadded:: 1.0270+ .. versionadded:: 0.11271 """272 if session.modified:273 return True274 save_each = app.config['SESSION_REFRESH_EACH_REQUEST']92 unmodified linesmodified:flask/signals.py+1 added-1 removed
35 unmodified lines36 connect = disconnect = has_receivers_for = receivers_for = \37 temporarily_connected_to = connected_to = _fail38 del _fail39 40-# The namespace for code signals. If you are not flask code, do40+# The namespace for code signals. If you are not Flask code, do41 # not put signals in here. Create your own namespace instead.42 _signals = Namespace()43 44 12 unmodified linesmodified:flask/templating.py+20 added-11 removed
50 unmodified lines51 def __init__(self, app):52 self.app = app53 54 def get_source(self, environment, template):55- explain = self.app.config['EXPLAIN_TEMPLATE_LOADING']55+ if self.app.config['EXPLAIN_TEMPLATE_LOADING']:56+ return self._get_source_explained(environment, template)57+ return self._get_source_fast(environment, template)58+59+ def _get_source_explained(self, environment, template):60 attempts = []57- tmplrv = None61+ trv = None62 63 for srcobj, loader in self._iter_loaders(template):64 try:65 rv = loader.get_source(environment, template)62- if tmplrv is None:63- tmplrv = rv64- if not explain:65- break66+ if trv is None:67+ trv = rv68 except TemplateNotFound:69 rv = None70 attempts.append((loader, srcobj, rv))71 70- if explain:71- from .debughelpers import explain_template_loading_attempts72- explain_template_loading_attempts(self.app, template, attempts)72+ from .debughelpers import explain_template_loading_attempts73+ explain_template_loading_attempts(self.app, template, attempts)74 74- if tmplrv is not None:75- return tmplrv75+ if trv is not None:76+ return trv77 raise TemplateNotFound(template)78 79+ def _get_source_fast(self, environment, template):80+ for srcobj, loader in self._iter_loaders(template):81+ try:82+ return loader.get_source(environment, template)83+ except TemplateNotFound:84+ continue85+ raise TemplateNotFound(template)86+87 def _iter_loaders(self, template):88 loader = self.app.jinja_loader89 if loader is not None:90 yield self.app, loader59 unmodified linesmodified:flask/testing.py+19 added-4 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 21 unmodified lines39 40 class FlaskClient(Client):41 """Works like a regular Werkzeug test client but has some knowledge about42 how Flask works to defer the cleanup of the request context stack to the42- end of a with body when used in a with statement. For general information43- about how to use this class refer to :class:`werkzeug.test.Client`.43+ end of a ``with`` body when used in a ``with`` statement. For general44+ information about how to use this class refer to45+ :class:`werkzeug.test.Client`.46 47+ .. versionchanged:: 0.1248+ `app.test_client()` includes preset default environment, which can be49+ set after instantiation of the `app.test_client()` object in50+ `client.environ_base`.51+52 Basic usage is outlined in the :ref:`testing` chapter.53 """54 55 preserve_context = False56 57+ def __init__(self, *args, **kwargs):58+ super(FlaskClient, self).__init__(*args, **kwargs)59+ self.environ_base = {60+ "REMOTE_ADDR": "127.0.0.1",61+ "HTTP_USER_AGENT": "werkzeug/" + werkzeug.__version__62+ }63+64 @contextmanager65 def session_transaction(self, *args, **kwargs):52- """When used in combination with a with statement this opens a66+ """When used in combination with a ``with`` statement this opens a67 session transaction. This can be used to modify the session that54- the test client uses. Once the with block is left the session is68+ the test client uses. Once the ``with`` block is left the session is69 stored back.70 71 ::72 40 unmodified lines113 114 def open(self, *args, **kwargs):115 kwargs.setdefault('environ_overrides', {}) \116 ['flask._preserve_context'] = self.preserve_context117+ kwargs.setdefault('environ_base', self.environ_base)118 119 as_tuple = kwargs.pop('as_tuple', False)120 buffered = kwargs.pop('buffered', False)121 follow_redirects = kwargs.pop('follow_redirects', False)22 unmodified linesmodified:flask/views.py+23 added-19 removed
46 unmodified lines47 based decorators since those would decorate the view class and not the48 generated view function!49 """50 51- #: A for which methods this pluggable view can handle.51+ #: A list of methods this view can handle.52 methods = None53 54 #: The canonical way to decorate class-based views is to decorate the55 #: return value of as_view(). However since this moves parts of the46 unmodified lines102 return view103 104 105 class MethodViewType(type):106+ """Metaclass for :class:`MethodView` that determines what methods the view107+ defines.108+ """109 107- def __new__(cls, name, bases, d):108- rv = type.__new__(cls, name, bases, d)110+ def __init__(cls, name, bases, d):111+ super(MethodViewType, cls).__init__(name, bases, d)112+113 if 'methods' not in d:110- methods = set(rv.methods or [])111- for key in d:112- if key in http_method_funcs:114+ methods = set()115+116+ for key in http_method_funcs:117+ if hasattr(cls, key):118 methods.add(key.upper())114- # If we have no method at all in there we don't want to115- # add a method list. (This is for instance the case for116- # the base class or another subclass of a base method view117- # that does not introduce new methods).119+120+ # If we have no method at all in there we don't want to add a121+ # method list. This is for instance the case for the base class122+ # or another subclass of a base method view that does not introduce123+ # new methods.124 if methods:119- rv.methods = sorted(methods)120- return rv125+ cls.methods = methods126 127 128 class MethodView(with_metaclass(MethodViewType, View)):124- """Like a regular class-based view but that dispatches requests to125- particular methods. For instance if you implement a method called126- :meth:`get` it means 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::129+ """A class-based view that dispatches request methods to the corresponding130+ class methods. For example, if you implement a ``get`` method, it will be131+ used to handle ``GET`` requests. ::132 133 class CounterAPI(MethodView):132-134 def get(self):135 return session.get('counter', 0)136 137 def post(self):1 unmodified line139 return 'OK'140 141 app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))142 """143+144 def dispatch_request(self, *args, **kwargs):145 meth = getattr(self, request.method.lower(), None)146+147 # If the request method is HEAD and we don't have a handler for it148 # retry with GET.149 if meth is None and request.method == 'HEAD':150 meth = getattr(self, 'get', None)151+152 assert meth is not None, 'Unimplemented method %r' % request.method153 return meth(*args, **kwargs)modified:flask/wrappers.py+9 added-7 removed
111 unmodified lines112 """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:: 1.0116+ .. versionadded:: 0.11117 """118 mt = self.mimetype119 if mt == 'application/json':120 return True1 unmodified line122 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. If127- parsing fails the :meth:`on_json_loading_failed` method on the128- request object will be invoked. By default this function will129- only load the json data if the mimetype is :mimetype:`application/json`130- but this can be overridden by the `force` parameter.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+ # We return cached JSON only when the cache is enabled.139- if rv is not _missing:141+ if cache and rv is not _missing:142 return rv143 144 if not (force or self.is_json):145 return None60 unmodified linesmodified:scripts/flask-07-upgrade.py+3 added-2 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`.5 unmodified lines18 19 :copyright: (c) Copyright 2015 by Armin Ronacher.20 :license: see LICENSE for more details.21 """22+from __future__ import print_function23 import re24 import os25 import inspect26 import difflib32 unmodified lines59 for line in difflib.unified_diff(old.splitlines(), new.splitlines(),60 posixpath.normpath(posixpath.join('a', filename)),61 posixpath.normpath(posixpath.join('b', filename)),62 lineterm=''):62- print line63+ print(line)64 65 66 def looks_like_teardown_function(node):67 returns = [x for x in ast.walk(node) if isinstance(x, ast.Return)]231 unmodified linesdeleted:scripts/flaskext_migrate.py-162 removed
1-# Script which modifies source code away from the deprecated "flask.ext"2-# format.3-#4-# Run in the terminal by typing: `python flaskext_migrate.py <source_file.py>`5-#6-# Author: Keyan Pishdadian 20157-8-from redbaron import RedBaron9-import sys10-11-12-def read_source(input_file):13- """Parses the input_file into a RedBaron FST."""14- with open(input_file, "r") as source_code:15- red = RedBaron(source_code.read())16- return red17-18-19-def write_source(red, input_file):20- """Overwrites the input_file once the FST has been modified."""21- with open(input_file, "w") as source_code:22- source_code.write(red.dumps())23-24-25-def fix_imports(red):26- """Wrapper which fixes "from" style imports and then "import" style."""27- red = fix_standard_imports(red)28- red = fix_from_imports(red)29- return red30-31-32-def fix_from_imports(red):33- """34- Converts "from" style imports to not use "flask.ext".35-36- Handles:37- Case 1: from flask.ext.foo import bam --> from flask_foo import bam38- Case 2: from flask.ext import foo --> import flask_foo as foo39- """40- from_imports = red.find_all("FromImport")41- for x, node in enumerate(from_imports):42- values = node.value43- if len(values) < 2:44- continue45- if (values[0].value == 'flask') and (values[1].value == 'ext'):46- # Case 147- if len(node.value) == 3:48- package = values[2].value49- modules = node.modules()50- module_string = _get_modules(modules)51- if len(modules) > 1:52- node.replace("from flask_%s import %s"53- % (package, module_string))54- else:55- name = node.names()[0]56- node.replace("from flask_%s import %s as %s"57- % (package, module_string, name))58- # Case 259- else:60- module = node.modules()[0]61- node.replace("import flask_%s as %s"62- % (module, module))63- return red64-65-66-def fix_standard_imports(red):67- """68- Handles import modification in the form:69- import flask.ext.foo" --> import flask_foo70- """71- imports = red.find_all("ImportNode")72- for x, node in enumerate(imports):73- try:74- if (node.value[0].value[0].value == 'flask' and75- node.value[0].value[1].value == 'ext'):76- package = node.value[0].value[2].value77- name = node.names()[0].split('.')[-1]78- if name == package:79- node.replace("import flask_%s" % (package))80- else:81- node.replace("import flask_%s as %s" % (package, name))82- except IndexError:83- pass84-85- return red86-87-88-def _get_modules(module):89- """90- Takes a list of modules and converts into a string.91-92- The module list can include parens, this function checks each element in93- the list, if there is a paren then it does not add a comma before the next94- element. Otherwise a comma and space is added. This is to preserve module95- imports which are multi-line and/or occur within parens. While also not96- affecting imports which are not enclosed.97- """98- modules_string = [cur + ', ' if cur.isalnum() and next.isalnum()99- else cur100- for (cur, next) in zip(module, module[1:]+[''])]101-102- return ''.join(modules_string)103-104-105-def fix_function_calls(red):106- """107- Modifies function calls in the source to reflect import changes.108-109- Searches the AST for AtomtrailerNodes and replaces them.110- """111- atoms = red.find_all("Atomtrailers")112- for x, node in enumerate(atoms):113- try:114- if (node.value[0].value == 'flask' and115- node.value[1].value == 'ext'):116- params = _form_function_call(node)117- node.replace("flask_%s%s" % (node.value[2], params))118- except IndexError:119- pass120-121- return red122-123-124-def _form_function_call(node):125- """126- Reconstructs function call strings when making attribute access calls.127- """128- node_vals = node.value129- output = "."130- for x, param in enumerate(node_vals[3::]):131- if param.dumps()[0] == "(":132- output = output[0:-1] + param.dumps()133- return output134- else:135- output += param.dumps() + "."136-137-138-def check_user_input():139- """Exits and gives error message if no argument is passed in the shell."""140- if len(sys.argv) < 2:141- sys.exit("No filename was included, please try again.")142-143-144-def fix_tester(ast):145- """Wrapper which allows for testing when not running from shell."""146- ast = fix_imports(ast)147- ast = fix_function_calls(ast)148- return ast.dumps()149-150-151-def fix():152- """Wrapper for user argument checking and import fixing."""153- check_user_input()154- input_file = sys.argv[1]155- ast = read_source(input_file)156- ast = fix_imports(ast)157- ast = fix_function_calls(ast)158- write_source(ast, input_file)159-160-161-if __name__ == "__main__":162- fix()modified:scripts/flaskext_tester.py+2 added-2 removed
110 unmodified lines111 '''112 113 114 def log(msg, *args):115- print '[EXTTEST]', msg % args115+ print('[EXTTEST] ' + (msg % args))116 117 118 class TestResult(object):119 181 unmodified lines301 filename = render_results(results, only_approved)302 if args.browse:303 import webbrowser304 webbrowser.open('file:///' + filename.lstrip('/'))305- print 'Results written to', filename305+ print('Results written to {}'.format(filename))306 307 308 if __name__ == '__main__':309 main()modified:scripts/make-release.py+4 added-10 removed
8 unmodified lines9 10 :copyright: (c) 2015 by Armin Ronacher.11 :license: BSD, see LICENSE for more details.12 """13+from __future__ import print_function14 import sys15 import os16 import re17 from datetime import datetime, date62 unmodified lines80 info('Setting __init__.py version to %s', version)81 set_filename_version('flask/__init__.py', version, '__version__')82 83 83-def set_setup_version(version):84- info('Setting setup.py version to %s', version)85- set_filename_version('setup.py', version, 'version')86-87-84 def build_and_upload():89- Popen([sys.executable, 'setup.py', 'release', 'sdist', 'upload']).wait()85+ Popen([sys.executable, 'setup.py', 'release', 'sdist', 'bdist_wheel', 'upload']).wait()86 87 88 def fail(message, *args):93- print >> sys.stderr, 'Error:', message % args89+ print('Error:', message % args, file=sys.stderr)90 sys.exit(1)91 92 93 def info(message, *args):98- print >> sys.stderr, message % args94+ print(message % args, file=sys.stderr)95 96 97 def get_git_tags():98 return set(Popen(['git', 'tag'], stdout=PIPE).communicate()[0].splitlines())36 unmodified lines135 if not git_is_clean():136 fail('You have uncommitted changes in git')137 138 set_init_version(version)143- set_setup_version(version)139 make_git_commit('Bump version number to %s', version)140 make_git_tag(version)141 build_and_upload()142 set_init_version(dev_version)148- set_setup_version(dev_version)143 144 145 if __name__ == '__main__':146 main()deleted:scripts/test_import_migration.py-76 removed
1-# Tester for the flaskext_migrate.py module located in flask/scripts/2-#3-# Author: Keyan Pishdadian4-import pytest5-redbaron = pytest.importorskip("redbaron")6-import flaskext_migrate as migrate7-8-def test_simple_from_import():9- red = redbaron.RedBaron("from flask.ext import foo")10- output = migrate.fix_tester(red)11- assert output == "import flask_foo as foo"12-13-14-def test_from_to_from_import():15- red = redbaron.RedBaron("from flask.ext.foo import bar")16- output = migrate.fix_tester(red)17- assert output == "from flask_foo import bar as bar"18-19-20-def test_multiple_import():21- red = redbaron.RedBaron("from flask.ext.foo import bar, foobar, something")22- output = migrate.fix_tester(red)23- assert output == "from flask_foo import bar, foobar, something"24-25-26-def test_multiline_import():27- red = redbaron.RedBaron("from flask.ext.foo import \28- bar,\29- foobar,\30- something")31- output = migrate.fix_tester(red)32- assert output == "from flask_foo import bar, foobar, something"33-34-35-def test_module_import():36- red = redbaron.RedBaron("import flask.ext.foo")37- output = migrate.fix_tester(red)38- assert output == "import flask_foo"39-40-41-def test_named_module_import():42- red = redbaron.RedBaron("import flask.ext.foo as foobar")43- output = migrate.fix_tester(red)44- assert output == "import flask_foo as foobar"45-46-47-def test_named_from_import():48- red = redbaron.RedBaron("from flask.ext.foo import bar as baz")49- output = migrate.fix_tester(red)50- assert output == "from flask_foo import bar as baz"51-52-53-def test_parens_import():54- red = redbaron.RedBaron("from flask.ext.foo import (bar, foo, foobar)")55- output = migrate.fix_tester(red)56- assert output == "from flask_foo import (bar, foo, foobar)"57-58-59-def test_function_call_migration():60- red = redbaron.RedBaron("flask.ext.foo(var)")61- output = migrate.fix_tester(red)62- assert output == "flask_foo(var)"63-64-65-def test_nested_function_call_migration():66- red = redbaron.RedBaron("import flask.ext.foo\n\n"67- "flask.ext.foo.bar(var)")68- output = migrate.fix_tester(red)69- assert output == ("import flask_foo\n\n"70- "flask_foo.bar(var)")71-72-73-def test_no_change_to_import():74- red = redbaron.RedBaron("from flask import Flask")75- output = migrate.fix_tester(red)76- assert output == "from flask import Flask"added:tests/test_apps/cliapp/__init__.py
added:tests/test_apps/cliapp/app.py+5 added
1+from __future__ import absolute_import, print_function2+3+from flask import Flask4+5+testapp = Flask('testapp')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')added:tests/test_apps/cliapp/multiapp.py+6 added
1+from __future__ import absolute_import, print_function2+3+from flask import Flask4+5+app1 = Flask('app1')6+app2 = Flask('app2')modified:tests/conftest.py+6 added-5 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 import flask10+import gc11 import os12 import sys13 import pkgutil14 import pytest111 unmodified lines126 request.addfinalizer(lambda: sys.modules.pop(name, None))127 return inner128 129 129-@pytest.fixture130-def catch_deprecation_warnings():131- import warnings132- warnings.simplefilter('default', category=DeprecationWarning)133- return lambda: warnings.catch_warnings(record=True)130+@pytest.yield_fixture(autouse=True)131+def catch_deprecation_warnings(recwarn):132+ yield133+ gc.collect()134+ assert not recwarn.listmodified:tests/test_appctx.py+22 added
144 unmodified lines145 res = c.get('/')146 assert res.status_code == 200147 assert res.data == b''148 assert called == ['request', 'app']149+150+151+def test_clean_pop():152+ called = []153+ app = flask.Flask(__name__)154+155+ @app.teardown_request156+ def teardown_req(error=None):157+ 1 / 0158+159+ @app.teardown_appcontext160+ def teardown_app(error=None):161+ called.append('TEARDOWN')162+163+ try:164+ with app.test_request_context():165+ called.append(flask.current_app.name)166+ except ZeroDivisionError:167+ pass168+169+ assert called == ['test_appctx', 'TEARDOWN']170+ assert not flask.current_appmodified:tests/test_basic.py+313 added-81 removed
48 unmodified lines49 rv = app.test_client().open('/', method='OPTIONS')50 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']51 52 53-def test_options_handling_disabled():53+def test_provide_automatic_options_attr():54 app = flask.Flask(__name__)55 56 def index():57 return 'Hello World!'11 unmodified lines69 rv = app.test_client().open('/', method='OPTIONS')70 assert sorted(rv.allow) == ['OPTIONS']71 72 73+def test_provide_automatic_options_kwarg():74+ app = flask.Flask(__name__)75+76+ def index():77+ return flask.request.method78+79+ def more():80+ return flask.request.method81+82+ app.add_url_rule('/', view_func=index, provide_automatic_options=False)83+ app.add_url_rule(84+ '/more', view_func=more, methods=['GET', 'POST'],85+ provide_automatic_options=False86+ )87+88+ c = app.test_client()89+ assert c.get('/').data == b'GET'90+91+ rv = c.post('/')92+ assert rv.status_code == 40593+ assert sorted(rv.allow) == ['GET', 'HEAD']94+95+ # Older versions of Werkzeug.test.Client don't have an options method96+ if hasattr(c, 'options'):97+ rv = c.options('/')98+ else:99+ rv = c.open('/', method='OPTIONS')100+101+ assert rv.status_code == 405102+103+ rv = c.head('/')104+ assert rv.status_code == 200105+ assert not rv.data # head truncates106+ assert c.post('/more').data == b'POST'107+ assert c.get('/more').data == b'GET'108+109+ rv = c.delete('/more')110+ assert rv.status_code == 405111+ assert sorted(rv.allow) == ['GET', 'HEAD', 'POST']112+113+ if hasattr(c, 'options'):114+ rv = c.options('/more')115+ else:116+ rv = c.open('/more', method='OPTIONS')117+118+ assert rv.status_code == 405119+120+121 def test_request_dispatching():122 app = flask.Flask(__name__)123 124 @app.route('/')229 unmodified lines354 def test_missing_session():355 app = flask.Flask(__name__)356 357 def expect_exception(f, *args, **kwargs):310- try:311- f(*args, **kwargs)312- except RuntimeError as e:313- assert e.args and 'session is unavailable' in e.args[0]314- else:315- assert False, 'expected exception'358+ e = pytest.raises(RuntimeError, f, *args, **kwargs)359+ assert e.value.args and 'session is unavailable' in e.value.args[0]360 with app.test_request_context():361 assert flask.session.get('missing_key') is None362 expect_exception(flask.session.__setitem__, 'foo', 42)363 expect_exception(flask.session.pop, 'foo')16 unmodified lines380 381 client = app.test_client()382 rv = client.get('/')383 assert 'set-cookie' in rv.headers340- match = re.search(r'\bexpires=([^;]+)(?i)', rv.headers['set-cookie'])384+ match = re.search(r'(?i)\bexpires=([^;]+)', rv.headers['set-cookie'])385 expires = parse_date(match.group())386 expected = datetime.utcnow() + app.permanent_session_lifetime387 assert expires.year == expected.year388 assert expires.month == expected.month426 unmodified lines815 assert rv.status_code == 403816 assert b'forbidden' == rv.data817 818 819+def test_error_handling_processing():820+ app = flask.Flask(__name__)821+ app.config['LOGGER_HANDLER_POLICY'] = 'never'822+823+ @app.errorhandler(500)824+ def internal_server_error(e):825+ return 'internal server error', 500826+827+ @app.route('/')828+ def broken_func():829+ 1 // 0830+831+ @app.after_request832+ def after_request(resp):833+ resp.mimetype = 'text/x-special'834+ return resp835+836+ with app.test_client() as c:837+ resp = c.get('/')838+ assert resp.mimetype == 'text/x-special'839+ assert resp.data == b'internal server error'840+841+842+def test_baseexception_error_handling():843+ app = flask.Flask(__name__)844+ app.config['LOGGER_HANDLER_POLICY'] = 'never'845+846+ @app.route('/')847+ def broken_func():848+ raise KeyboardInterrupt()849+850+ with app.test_client() as c:851+ with pytest.raises(KeyboardInterrupt):852+ c.get('/')853+854+ ctx = flask._request_ctx_stack.top855+ assert ctx.preserved856+ assert type(ctx._preserved_exc) is KeyboardInterrupt857+858+859 def test_before_request_and_routing_errors():860 app = flask.Flask(__name__)861 862 @app.before_request73 unmodified lines936 assert c.get('/fail').status_code == 400937 938 app.config['TRAP_BAD_REQUEST_ERRORS'] = True939 c = app.test_client()856- try:857- c.get('/fail')858- except KeyError as e:859- assert isinstance(e, BadRequest)860- else:861- assert False, 'Expected exception'940+ with pytest.raises(KeyError) as e:941+ c.get("/fail")942+ assert e.errisinstance(BadRequest)943 944 945 def test_trapping_of_all_http_exceptions():946 app = flask.Flask(__name__)21 unmodified lines968 # with statement is important because we leave an exception on the969 # stack otherwise and we want to ensure that this is not the case970 # to not negatively affect other tests.971 with app.test_client() as c:891- try:972+ with pytest.raises(DebugFilesKeyError) as e:973 c.post('/fail', data={'foo': 'index.txt'})893- except DebugFilesKeyError as e:894- assert 'no file contents were transmitted' in str(e)895- assert 'This was submitted: "index.txt"' in str(e)974+ assert 'no file contents were transmitted' in str(e.value)975+ assert 'This was submitted: "index.txt"' in str(e.value)896- else:897- assert False, 'Expected exception'976 977 900-def test_response_creation():978+def test_response_types():979 app = flask.Flask(__name__)980+ app.testing = True981 903- @app.route('/unicode')904- def from_unicode():982+ @app.route('/text')983+ def from_text():984 return u'Hällo Wörld'985 907- @app.route('/string')908- def from_string():986+ @app.route('/bytes')987+ def from_bytes():988 return u'Hällo Wörld'.encode('utf-8')989 911- @app.route('/args')912- def from_tuple():990+ @app.route('/full_tuple')991+ def from_full_tuple():992 return 'Meh', 400, {993 'X-Foo': 'Testing',994 'Content-Type': 'text/plain; charset=utf-8'995 }996 918- @app.route('/two_args')919- def from_two_args_tuple():997+ @app.route('/text_headers')998+ def from_text_headers():999 return 'Hello', {1000 'X-Foo': 'Test',1001 'Content-Type': 'text/plain; charset=utf-8'1002 }1003 925- @app.route('/args_status')926- def from_status_tuple():1004+ @app.route('/text_status')1005+ def from_text_status():1006 return 'Hi, status!', 4001007 929- @app.route('/args_header')930- def from_response_instance_status_tuple():931- return flask.Response('Hello world', 404), {1008+ @app.route('/response_headers')1009+ def from_response_headers():1010+ return flask.Response('Hello world', 404, {'X-Foo': 'Baz'}), {1011 "X-Foo": "Bar",1012 "X-Bar": "Foo"1013 }1014 1015+ @app.route('/response_status')1016+ def from_response_status():1017+ return app.response_class('Hello world', 400), 5001018+1019+ @app.route('/wsgi')1020+ def from_wsgi():1021+ return NotFound()1022+1023 c = app.test_client()937- assert c.get('/unicode').data == u'Hällo Wörld'.encode('utf-8')938- assert c.get('/string').data == u'Hällo Wörld'.encode('utf-8')939- rv = c.get('/args')1024+1025+ assert c.get('/text').data == u'Hällo Wörld'.encode('utf-8')1026+ assert c.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')1027+1028+ rv = c.get('/full_tuple')1029 assert rv.data == b'Meh'1030 assert rv.headers['X-Foo'] == 'Testing'1031 assert rv.status_code == 4001032 assert rv.mimetype == 'text/plain'944- rv2 = c.get('/two_args')945- assert rv2.data == b'Hello'946- assert rv2.headers['X-Foo'] == 'Test'947- assert rv2.status_code == 200948- assert rv2.mimetype == 'text/plain'949- rv3 = c.get('/args_status')950- assert rv3.data == b'Hi, status!'951- assert rv3.status_code == 400952- assert rv3.mimetype == 'text/html'953- rv4 = c.get('/args_header')954- assert rv4.data == b'Hello world'955- assert rv4.headers['X-Foo'] == 'Bar'956- assert rv4.headers['X-Bar'] == 'Foo'957- assert rv4.status_code == 4041033 1034+ rv = c.get('/text_headers')1035+ assert rv.data == b'Hello'1036+ assert rv.headers['X-Foo'] == 'Test'1037+ assert rv.status_code == 2001038+ assert rv.mimetype == 'text/plain'1039 1040+ rv = c.get('/text_status')1041+ assert rv.data == b'Hi, status!'1042+ assert rv.status_code == 4001043+ assert rv.mimetype == 'text/html'1044+1045+ rv = c.get('/response_headers')1046+ assert rv.data == b'Hello world'1047+ assert rv.headers.getlist('X-Foo') == ['Baz', 'Bar']1048+ assert rv.headers['X-Bar'] == 'Foo'1049+ assert rv.status_code == 4041050+1051+ rv = c.get('/response_status')1052+ assert rv.data == b'Hello world'1053+ assert rv.status_code == 5001054+1055+ rv = c.get('/wsgi')1056+ assert b'Not Found' in rv.data1057+ assert rv.status_code == 4041058+1059+1060+def test_response_type_errors():1061+ app = flask.Flask(__name__)1062+ app.testing = True1063+1064+ @app.route('/none')1065+ def from_none():1066+ pass1067+1068+ @app.route('/small_tuple')1069+ def from_small_tuple():1070+ return 'Hello',1071+1072+ @app.route('/large_tuple')1073+ def from_large_tuple():1074+ return 'Hello', 234, {'X-Foo': 'Bar'}, '???'1075+1076+ @app.route('/bad_type')1077+ def from_bad_type():1078+ return True1079+1080+ @app.route('/bad_wsgi')1081+ def from_bad_wsgi():1082+ return lambda: None1083+1084+ c = app.test_client()1085+1086+ with pytest.raises(TypeError) as e:1087+ c.get('/none')1088+ assert 'returned None' in str(e)1089+1090+ with pytest.raises(TypeError) as e:1091+ c.get('/small_tuple')1092+ assert 'tuple must have the form' in str(e)1093+1094+ pytest.raises(TypeError, c.get, '/large_tuple')1095+1096+ with pytest.raises(TypeError) as e:1097+ c.get('/bad_type')1098+ assert 'it was a bool' in str(e)1099+1100+ pytest.raises(TypeError, c.get, '/bad_wsgi')1101+1102+1103 def test_make_response():1104 app = flask.Flask(__name__)1105 with app.test_request_context():1106 rv = flask.make_response()17 unmodified lines1124 with app.test_request_context():1125 rv = flask.make_response(1126 flask.jsonify({'msg': 'W00t'}), 400)1127 assert rv.status_code == 400985- assert rv.data == b'{\n "msg": "W00t"\n}\n'1128+ assert rv.data == b'{"msg":"W00t"}\n'1129 assert rv.mimetype == 'application/json'1130 1131 rv = flask.make_response(1132 flask.Response(''), 400)38 unmodified lines1171 flask.jsonify(compressed_msg), 200)1172 assert rv.data == pretty_response1173 1174 1175+def test_jsonify_mimetype():1176+ app = flask.Flask(__name__)1177+ app.config.update({"JSONIFY_MIMETYPE": 'application/vnd.api+json'})1178+ with app.test_request_context():1179+ msg = {1180+ "msg": {"submsg": "W00t"},1181+ }1182+ rv = flask.make_response(1183+ flask.jsonify(msg), 200)1184+ assert rv.mimetype == 'application/vnd.api+json'1185+1186+1187+def test_jsonify_args_and_kwargs_check():1188+ app = flask.Flask(__name__)1189+ with app.test_request_context():1190+ with pytest.raises(TypeError) as e:1191+ flask.jsonify('fake args', kwargs='fake')1192+ assert 'behavior undefined' in str(e.value)1193+1194+1195 def test_url_generation():1196 app = flask.Flask(__name__)1197 1198 @app.route('/hello/<name>', methods=['POST'])44 unmodified lines1243 with app.test_request_context():1244 pytest.raises(BuildError, flask.url_for, 'not.existing')1245 1246 1247+def test_url_for_passes_special_values_to_build_error_handler():1248+ app = flask.Flask(__name__)1249+1250+ @app.url_build_error_handlers.append1251+ def handler(error, endpoint, values):1252+ assert values == {1253+ '_external': False,1254+ '_anchor': None,1255+ '_method': None,1256+ '_scheme': None,1257+ }1258+ return 'handled'1259+1260+ with app.test_request_context():1261+ flask.url_for('/')1262+1263+1264 def test_custom_converters():1265 from werkzeug.routing import BaseConverter1266 1267 class ListConverter(BaseConverter):25 unmodified lines1293 '/static/index.html'1294 rv.close()1295 1296 1117-def test_none_response():1118- app = flask.Flask(__name__)1297+def test_static_path_deprecated(recwarn):1298+ app = flask.Flask(__name__, static_path='/foo')1299+ recwarn.pop(DeprecationWarning)1300+1301 app.testing = True1302+ rv = app.test_client().get('/foo/index.html')1303+ assert rv.status_code == 2001304+ rv.close()1305 1121- @app.route('/')1122- def test():1123- return None1124- try:1125- app.test_client().get('/')1126- except ValueError as e:1127- assert str(e) == 'View function did not return a response'1128- pass1129- else:1130- assert "Expected ValueError"1306+ with app.test_request_context():1307+ assert flask.url_for('static', filename='index.html') == '/foo/index.html'1308 1309 1310+def test_static_url_path():1311+ app = flask.Flask(__name__, static_url_path='/foo')1312+ app.testing = True1313+ rv = app.test_client().get('/foo/index.html')1314+ assert rv.status_code == 2001315+ rv.close()1316+1317+ with app.test_request_context():1318+ assert flask.url_for('static', filename='index.html') == '/foo/index.html'1319+1320+1321+def test_static_route_with_host_matching():1322+ app = flask.Flask(__name__, host_matching=True, static_host='example.com')1323+ c = app.test_client()1324+ rv = c.get('http://example.com/static/index.html')1325+ assert rv.status_code == 2001326+ rv.close()1327+ with app.test_request_context():1328+ rv = flask.url_for('static', filename='index.html', _external=True)1329+ assert rv == 'http://example.com/static/index.html'1330+ # Providing static_host without host_matching=True should error.1331+ with pytest.raises(Exception):1332+ flask.Flask(__name__, static_host='example.com')1333+ # Providing host_matching=True with static_folder but without static_host should error.1334+ with pytest.raises(Exception):1335+ flask.Flask(__name__, host_matching=True)1336+ # Providing host_matching=True without static_host but with static_folder=None should not error.1337+ flask.Flask(__name__, host_matching=True, static_folder=None)1338+1339+1340 def test_request_locals():1341 assert repr(flask.g) == '<LocalProxy unbound>'1342 assert not flask.g1343 65 unmodified lines1409 1 // 01410 c = app.test_client()1411 if config_key is not None:1412 app.config[config_key] = True1206- try:1413+ with pytest.raises(Exception):1414 c.get('/')1208- except Exception:1209- pass1210- else:1211- assert False, 'expected exception'1415 else:1416 assert c.get('/').status_code == 5001417 1418 # we have to run this test in an isolated thread because if the5 unmodified lines1424 t.start()1425 t.join()1426 1427 1428+@pytest.mark.parametrize('debug', [True, False])1429+@pytest.mark.parametrize('use_debugger', [True, False])1430+@pytest.mark.parametrize('use_reloader', [True, False])1431+@pytest.mark.parametrize('propagate_exceptions', [None, True, False])1432+def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1433+ use_reloader, propagate_exceptions):1434+ rv = {}1435+1436+ # Mocks werkzeug.serving.run_simple method1437+ def run_simple_mock(*args, **kwargs):1438+ rv['passthrough_errors'] = kwargs.get('passthrough_errors')1439+1440+ app = flask.Flask(__name__)1441+ monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1442+ app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1443+ app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)1444+1445+1446 def test_max_content_length():1447 app = flask.Flask(__name__)1448 app.config['MAX_CONTENT_LENGTH'] = 641449 95 unmodified lines1545 def index():1546 return 'Awesome'1547 assert not app.got_first_request1548 assert app.test_client().get('/').data == b'Awesome'1328- try:1549+ with pytest.raises(AssertionError) as e:1550 @app.route('/foo')1551 def broken():1552 return 'Meh'1332- except AssertionError as e:1333- assert 'A setup function was called' in str(e)1553+ assert 'A setup function was called' in str(e)1334- else:1335- assert False, 'Expected exception'1554 1555 app.debug = False1556 1557 @app.route('/foo')47 unmodified lines1605 @app.route('/foo/', methods=['GET', 'POST'])1606 def foo():1607 return 'success'1608 with app.test_client() as c:1391- try:1609+ with pytest.raises(AssertionError) as e:1610 c.post('/foo', data={})1393- except AssertionError as e:1394- assert 'http://localhost/foo/' in str(e)1395- assert ('Make sure to directly send '1396- 'your POST-request to this URL') in str(e)1611+ assert 'http://localhost/foo/' in str(e)1612+ assert ('Make sure to directly send '1613+ 'your POST-request to this URL') in str(e)1397- else:1398- assert False, 'Expected exception'1614 1615 rv = c.get('/foo', data={}, follow_redirects=True)1616 assert rv.data == b'success'1617 212 unmodified lines1830 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1831 hostname, port = 'localhost', 80001832 app.run(hostname, port, debug=True)1833 assert rv['result'] == 'running on %s:%s ...' % (hostname, port)1834+1835+1836+@pytest.mark.parametrize('host,port,expect_host,expect_port', (1837+ (None, None, 'pocoo.org', 8080),1838+ ('localhost', None, 'localhost', 8080),1839+ (None, 80, 'pocoo.org', 80),1840+ ('localhost', 80, 'localhost', 80),1841+))1842+def test_run_from_config(monkeypatch, host, port, expect_host, expect_port):1843+ def run_simple_mock(hostname, port, *args, **kwargs):1844+ assert hostname == expect_host1845+ assert port == expect_port1846+1847+ monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1848+ app = flask.Flask(__name__)1849+ app.config['SERVER_NAME'] = 'pocoo.org:8080'1850+ app.run(host, port)modified:tests/test_blueprints.py+21 added-5 removed
172 unmodified lines173 with app.test_request_context():174 assert flask.url_for('admin.static', filename='test.txt') == '/admin/static/test.txt'175 176 with app.test_request_context():177- try:177+ with pytest.raises(TemplateNotFound) as e:178 flask.render_template('missing.html')179- except TemplateNotFound as e:180- assert e.name == 'missing.html'179+ assert e.value.name == 'missing.html'181- else:182- assert 0, 'expected exception'180 181 with flask.Flask(__name__).test_request_context():182 assert flask.render_template('nested/nested.txt') == 'I\'m nested'183 170 unmodified lines354 assert rv.status_code == 404355 rv = c.get('/py/bar/123')356 assert rv.status_code == 404357 358+359+def test_endpoint_decorator():360+ from werkzeug.routing import Rule361+ app = flask.Flask(__name__)362+ app.url_map.add(Rule('/foo', endpoint='bar'))363+364+ bp = flask.Blueprint('bp', __name__)365+366+ @bp.endpoint('bar')367+ def foobar():368+ return flask.request.endpoint369+370+ app.register_blueprint(bp, url_prefix='/bp_prefix')371+372+ c = app.test_client()373+ assert c.get('/foo').data == b'bar'374+ assert c.get('/bp_prefix/bar').status_code == 404375+376+377 def test_template_filter():378 bp = flask.Blueprint('bp', __name__)379 @bp.app_template_filter()380 def my_reverse(s):213 unmodified linesadded:tests/test_cli.py+210 added
1+# -*- coding: utf-8 -*-2+"""3+ tests.test_cli4+ ~~~~~~~~~~~~~~5+6+ :copyright: (c) 2016 by the Flask Team, see AUTHORS for more details.7+ :license: BSD, see LICENSE for more details.8+"""9+#10+# This file was part of Flask-CLI and was modified under the terms its license,11+# the Revised BSD License.12+# Copyright (C) 2015 CERN.13+#14+from __future__ import absolute_import, print_function15+import os16+import sys17+18+import click19+import pytest20+from click.testing import CliRunner21+from flask import Flask, current_app22+23+from flask.cli import AppGroup, FlaskGroup, NoAppException, ScriptInfo, \24+ find_best_app, locate_app, with_appcontext, prepare_exec_for_file, \25+ find_default_import_path, get_version26+27+28+def test_cli_name(test_apps):29+ """Make sure the CLI object's name is the app's name and not the app itself"""30+ from cliapp.app import testapp31+ assert testapp.cli.name == testapp.name32+33+34+def test_find_best_app(test_apps):35+ """Test if `find_best_app` behaves as expected with different combinations of input."""36+ class Module:37+ app = Flask('appname')38+ assert find_best_app(Module) == Module.app39+40+ class Module:41+ application = Flask('appname')42+ assert find_best_app(Module) == Module.application43+44+ class Module:45+ myapp = Flask('appname')46+ assert find_best_app(Module) == Module.myapp47+48+ class Module:49+ pass50+ pytest.raises(NoAppException, find_best_app, Module)51+52+ class Module:53+ myapp1 = Flask('appname1')54+ myapp2 = Flask('appname2')55+ pytest.raises(NoAppException, find_best_app, Module)56+57+58+def test_prepare_exec_for_file(test_apps):59+ """Expect the correct path to be set and the correct module name to be returned.60+61+ :func:`prepare_exec_for_file` has a side effect, where62+ the parent directory of given file is added to `sys.path`.63+ """64+ realpath = os.path.realpath('/tmp/share/test.py')65+ dirname = os.path.dirname(realpath)66+ assert prepare_exec_for_file('/tmp/share/test.py') == 'test'67+ assert dirname in sys.path68+69+ realpath = os.path.realpath('/tmp/share/__init__.py')70+ dirname = os.path.dirname(os.path.dirname(realpath))71+ assert prepare_exec_for_file('/tmp/share/__init__.py') == 'share'72+ assert dirname in sys.path73+74+ with pytest.raises(NoAppException):75+ prepare_exec_for_file('/tmp/share/test.txt')76+77+78+def test_locate_app(test_apps):79+ """Test of locate_app."""80+ assert locate_app("cliapp.app").name == "testapp"81+ assert locate_app("cliapp.app:testapp").name == "testapp"82+ assert locate_app("cliapp.multiapp:app1").name == "app1"83+ pytest.raises(NoAppException, locate_app, "notanpp.py")84+ pytest.raises(NoAppException, locate_app, "cliapp/app")85+ pytest.raises(RuntimeError, locate_app, "cliapp.app:notanapp")86+ pytest.raises(NoAppException, locate_app, "cliapp.importerrorapp")87+88+89+def test_find_default_import_path(test_apps, monkeypatch, tmpdir):90+ """Test of find_default_import_path."""91+ monkeypatch.delitem(os.environ, 'FLASK_APP', raising=False)92+ assert find_default_import_path() == None93+ monkeypatch.setitem(os.environ, 'FLASK_APP', 'notanapp')94+ assert find_default_import_path() == 'notanapp'95+ tmpfile = tmpdir.join('testapp.py')96+ tmpfile.write('')97+ monkeypatch.setitem(os.environ, 'FLASK_APP', str(tmpfile))98+ expect_rv = prepare_exec_for_file(str(tmpfile))99+ assert find_default_import_path() == expect_rv100+101+102+def test_get_version(test_apps, capsys):103+ """Test of get_version."""104+ from flask import __version__ as flask_ver105+ from sys import version as py_ver106+ class MockCtx(object):107+ resilient_parsing = False108+ color = None109+ def exit(self): return110+ ctx = MockCtx()111+ get_version(ctx, None, "test")112+ out, err = capsys.readouterr()113+ assert flask_ver in out114+ assert py_ver in out115+116+117+def test_scriptinfo(test_apps):118+ """Test of ScriptInfo."""119+ obj = ScriptInfo(app_import_path="cliapp.app:testapp")120+ assert obj.load_app().name == "testapp"121+ assert obj.load_app().name == "testapp"122+123+ def create_app(info):124+ return Flask("createapp")125+126+ obj = ScriptInfo(create_app=create_app)127+ app = obj.load_app()128+ assert app.name == "createapp"129+ assert obj.load_app() == app130+131+132+def test_with_appcontext():133+ """Test of with_appcontext."""134+ @click.command()135+ @with_appcontext136+ def testcmd():137+ click.echo(current_app.name)138+139+ obj = ScriptInfo(create_app=lambda info: Flask("testapp"))140+141+ runner = CliRunner()142+ result = runner.invoke(testcmd, obj=obj)143+ assert result.exit_code == 0144+ assert result.output == 'testapp\n'145+146+147+def test_appgroup():148+ """Test of with_appcontext."""149+ @click.group(cls=AppGroup)150+ def cli():151+ pass152+153+ @cli.command(with_appcontext=True)154+ def test():155+ click.echo(current_app.name)156+157+ @cli.group()158+ def subgroup():159+ pass160+161+ @subgroup.command(with_appcontext=True)162+ def test2():163+ click.echo(current_app.name)164+165+ obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))166+167+ runner = CliRunner()168+ result = runner.invoke(cli, ['test'], obj=obj)169+ assert result.exit_code == 0170+ assert result.output == 'testappgroup\n'171+172+ result = runner.invoke(cli, ['subgroup', 'test2'], obj=obj)173+ assert result.exit_code == 0174+ assert result.output == 'testappgroup\n'175+176+177+def test_flaskgroup():178+ """Test FlaskGroup."""179+ def create_app(info):180+ return Flask("flaskgroup")181+182+ @click.group(cls=FlaskGroup, create_app=create_app)183+ def cli(**params):184+ pass185+186+ @cli.command()187+ def test():188+ click.echo(current_app.name)189+190+ runner = CliRunner()191+ result = runner.invoke(cli, ['test'])192+ assert result.exit_code == 0193+ assert result.output == 'flaskgroup\n'194+195+196+def test_print_exceptions():197+ """Print the stacktrace if the CLI."""198+ def create_app(info):199+ raise Exception("oh no")200+ return Flask("flaskgroup")201+202+ @click.group(cls=FlaskGroup, create_app=create_app)203+ def cli(**params):204+ pass205+206+ runner = CliRunner()207+ result = runner.invoke(cli, ['--help'])208+ assert result.exit_code == 0209+ assert 'Exception: oh no' in result.output210+ assert 'Traceback' in result.outputmodified:tests/test_config.py+37 added-31 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'69 unmodified lines91 env = os.environ92 try:93 os.environ = {}94 app = flask.Flask(__name__)92- try:95+ with pytest.raises(RuntimeError) as e:96 app.config.from_envvar('FOO_SETTINGS')94- except RuntimeError as e:95- assert "'FOO_SETTINGS' is not set" in str(e)97+ assert "'FOO_SETTINGS' is not set" in str(e.value)96- else:97- assert 0, 'expected exception'98 assert not app.config.from_envvar('FOO_SETTINGS', silent=True)99 100 os.environ = {'FOO_SETTINGS': __file__.rsplit('.', 1)[0] + '.py'}101 assert app.config.from_envvar('FOO_SETTINGS')5 unmodified lines107 def test_config_from_envvar_missing():108 env = os.environ109 try:110 os.environ = {'FOO_SETTINGS': 'missing.cfg'}111- try:111+ with pytest.raises(IOError) as e:112 app = flask.Flask(__name__)113 app.config.from_envvar('FOO_SETTINGS')114- except IOError as e:115- msg = str(e)116- assert msg.startswith('[Errno 2] Unable to load configuration '117- 'file (No such file or directory):')118- assert msg.endswith("missing.cfg'")114+ msg = str(e.value)115+ assert msg.startswith('[Errno 2] Unable to load configuration '116+ 'file (No such file or directory):')117+ assert msg.endswith("missing.cfg'")119- else:120- assert False, 'expected IOError'118 assert not app.config.from_envvar('FOO_SETTINGS', silent=True)119 finally:120 os.environ = env121 122 123 def test_config_missing():124 app = flask.Flask(__name__)128- try:125+ with pytest.raises(IOError) as e:126 app.config.from_pyfile('missing.cfg')130- except IOError as e:131- msg = str(e)132- assert msg.startswith('[Errno 2] Unable to load configuration '133- 'file (No such file or directory):')134- assert msg.endswith("missing.cfg'")127+ msg = str(e.value)128+ assert msg.startswith('[Errno 2] Unable to load configuration '129+ 'file (No such file or directory):')130+ assert msg.endswith("missing.cfg'")135- else:136- assert 0, 'expected config'131 assert not app.config.from_pyfile('missing.cfg', silent=True)132 133 134 def test_config_missing_json():135 app = flask.Flask(__name__)142- try:136+ with pytest.raises(IOError) as e:137 app.config.from_json('missing.json')144- except IOError as e:145- msg = str(e)146- assert msg.startswith('[Errno 2] Unable to load configuration '147- 'file (No such file or directory):')148- assert msg.endswith("missing.json'")138+ msg = str(e.value)139+ assert msg.startswith('[Errno 2] Unable to load configuration '140+ 'file (No such file or directory):')141+ assert msg.endswith("missing.json'")149- else:150- assert 0, 'expected config'142 assert not app.config.from_json('missing.json', silent=True)143 144 145 def test_custom_config_class():43 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+8 added-12 removed
14 unmodified lines15 16 17 class TestRequestDeprecation(object):18 19- def test_request_json(self, catch_deprecation_warnings):19+ def test_request_json(self, recwarn):20 """Request.json is deprecated"""21 app = flask.Flask(__name__)22 app.testing = True23 2 unmodified lines26 assert flask.request.json == {'spam': 42}27 print(flask.request.json)28 return 'OK'29 30- with catch_deprecation_warnings() as captured:31- c = app.test_client()32- c.post('/', data='{"spam": 42}', content_type='application/json')30+ c = app.test_client()31+ c.post('/', data='{"spam": 42}', content_type='application/json')32+ recwarn.pop(DeprecationWarning)33 34- assert len(captured) == 135-36- def test_request_module(self, catch_deprecation_warnings):34+ def test_request_module(self, recwarn):35 """Request.module is deprecated"""36 app = flask.Flask(__name__)37 app.testing = True38 1 unmodified line40 def index():41 assert flask.request.module is None42 return 'OK'43 46- with catch_deprecation_warnings() as captured:47- c = app.test_client()48- c.get('/')49-44+ c = app.test_client()45+ c.get('/')46+ recwarn.pop(DeprecationWarning)50- assert len(captured) == 1modified:tests/test_ext.py+14 added-2 removed
19 unmodified lines20 from flask._compat import PY221 22 23 @pytest.fixture(autouse=True)24+def disable_extwarnings(request, 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()31+32+ request.addfinalizer(inner)33+34+35+@pytest.fixture(autouse=True)36 def importhook_setup(monkeypatch, request):37 # we clear this out for various reasons. The most important one is38 # that a real flaskext could be in there which would disable our39 # fake package. Secondly we want to make sure that the flaskext138 unmodified lines178 179 def test_no_error_swallowing(flaskext_broken):180 with pytest.raises(ImportError) as excinfo:181 import flask.ext.broken170-171- assert excinfo.type is ImportError182+ # python3.6 raises a subclass of ImportError: 'ModuleNotFoundError'183+ assert issubclass(excinfo.type, ImportError)184 if PY2:185 message = 'No module named missing_module'186 else:187 message = 'No module named \'missing_module\''12 unmodified linesmodified:tests/test_helpers.py+361 added-97 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_date24 from flask._compat import StringIO, text_type25 8 unmodified lines34 35 36 class TestJSON(object):37 34- def test_jsonify_date_types(self):35- """Test jsonify with datetime.date and datetime.datetime types."""36-37- test_dates = (38- datetime.datetime(1973, 3, 11, 6, 30, 45),39- datetime.date(1975, 1, 5)40- )41-38+ def test_ignore_cached_json(self):39 app = flask.Flask(__name__)43- c = app.test_client()40+ with app.test_request_context('/', method='POST', data='malformed',41+ content_type='application/json'):42+ assert flask.request.get_json(silent=True, cache=True) is None43+ with pytest.raises(BadRequest):44+ flask.request.get_json(silent=False, cache=False)45 45- for i, d in enumerate(test_dates):46- url = '/datetest{0}'.format(i)47- app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val))48- rv = c.get(url)49- assert rv.mimetype == 'application/json'50- assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple())51-46 def test_post_empty_json_adds_exception_to_response_content_in_debug(self):47 app = flask.Flask(__name__)48 app.config['DEBUG'] = True49 @app.route('/json', methods=['POST'])46 unmodified lines96 resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),97 content_type='application/json; charset=iso-8859-15')98 assert resp.data == u'Hällo Wörld'.encode('utf-8')99 106- def test_jsonify(self):107- d = dict(a=23, b=42, c=[1, 2, 3])100+ def test_json_as_unicode(self):101 app = flask.Flask(__name__)102+103+ app.config['JSON_AS_ASCII'] = True104+ with app.app_context():105+ rv = flask.json.dumps(u'\N{SNOWMAN}')106+ assert rv == '"\\u2603"'107+108+ app.config['JSON_AS_ASCII'] = False109+ with app.app_context():110+ rv = flask.json.dumps(u'\N{SNOWMAN}')111+ assert rv == u'"\u2603"'112+113+ def test_json_dump_to_file(self):114+ app = flask.Flask(__name__)115+ test_data = {'name': 'Flask'}116+ out = StringIO()117+118+ with app.app_context():119+ flask.json.dump(test_data, out)120+ out.seek(0)121+ rv = flask.json.load(out)122+ assert rv == test_data123+124+ @pytest.mark.parametrize('test_value', [0, -1, 1, 23, 3.14, 's', "longer string", True, False, None])125+ def test_jsonify_basic_types(self, test_value):126+ """Test jsonify with basic types."""127+ app = flask.Flask(__name__)128+ c = app.test_client()129+130+ url = '/jsonify_basic_types'131+ app.add_url_rule(url, url, lambda x=test_value: flask.jsonify(x))132+ rv = c.get(url)133+ assert rv.mimetype == 'application/json'134+ assert flask.json.loads(rv.data) == test_value135+136+ def test_jsonify_dicts(self):137+ """Test jsonify with dicts and kwargs unpacking."""138+ d = dict(139+ a=0, b=23, c=3.14, d='t', e='Hi', f=True, g=False,140+ h=['test list', 10, False],141+ i={'test':'dict'}142+ )143+ app = flask.Flask(__name__)144 @app.route('/kw')145 def return_kwargs():146 return flask.jsonify(**d)147 @app.route('/dict')4 unmodified lines152 rv = c.get(url)153 assert rv.mimetype == 'application/json'154 assert flask.json.loads(rv.data) == d155 121- def test_json_as_unicode(self):156+ def test_jsonify_arrays(self):157+ """Test jsonify of lists and args unpacking."""158+ l = [159+ 0, 42, 3.14, 't', 'hello', True, False,160+ ['test list', 2, False],161+ {'test':'dict'}162+ ]163 app = flask.Flask(__name__)164+ @app.route('/args_unpack')165+ def return_args_unpack():166+ return flask.jsonify(*l)167+ @app.route('/array')168+ def return_array():169+ return flask.jsonify(l)170+ c = app.test_client()171+ for url in '/args_unpack', '/array':172+ rv = c.get(url)173+ assert rv.mimetype == 'application/json'174+ assert flask.json.loads(rv.data) == l175 124- app.config['JSON_AS_ASCII'] = True125- with app.app_context():126- rv = flask.json.dumps(u'\N{SNOWMAN}')127- assert rv == '"\\u2603"'176+ def test_jsonify_date_types(self):177+ """Test jsonify with datetime.date and datetime.datetime types."""178+ test_dates = (179+ datetime.datetime(1973, 3, 11, 6, 30, 45),180+ datetime.date(1975, 1, 5)181+ )182+ app = flask.Flask(__name__)183+ c = app.test_client()184 129- app.config['JSON_AS_ASCII'] = False130- with app.app_context():131- rv = flask.json.dumps(u'\N{SNOWMAN}')132- assert rv == u'"\u2603"'185+ for i, d in enumerate(test_dates):186+ url = '/datetest{0}'.format(i)187+ app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val))188+ rv = c.get(url)189+ assert rv.mimetype == 'application/json'190+ assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple())191 192+ def test_jsonify_uuid_types(self):193+ """Test jsonify with uuid.UUID types"""194+195+ test_uuid = uuid.UUID(bytes=b'\xDE\xAD\xBE\xEF' * 4)196+ app = flask.Flask(__name__)197+ url = '/uuid_test'198+ app.add_url_rule(url, url, lambda: flask.jsonify(x=test_uuid))199+200+ c = app.test_client()201+ rv = c.get(url)202+203+ rv_x = flask.json.loads(rv.data)['x']204+ assert rv_x == str(test_uuid)205+ rv_uuid = uuid.UUID(rv_x)206+ assert rv_uuid == test_uuid207+208 def test_json_attr(self):209 app = flask.Flask(__name__)210 @app.route('/add', methods=['POST'])211 def add():54 unmodified lines266 'x': {'_foo': 42}267 }), content_type='application/json')268 assert rv.data == b'"<42>"'269 270+ def test_blueprint_json_customization(self):271+ class X(object):272+ def __init__(self, val):273+ self.val = val274+275+ class MyEncoder(flask.json.JSONEncoder):276+ def default(self, o):277+ if isinstance(o, X):278+ return '<%d>' % o.val279+280+ return flask.json.JSONEncoder.default(self, o)281+282+ class MyDecoder(flask.json.JSONDecoder):283+ def __init__(self, *args, **kwargs):284+ kwargs.setdefault('object_hook', self.object_hook)285+ flask.json.JSONDecoder.__init__(self, *args, **kwargs)286+287+ def object_hook(self, obj):288+ if len(obj) == 1 and '_foo' in obj:289+ return X(obj['_foo'])290+291+ return obj292+293+ bp = flask.Blueprint('bp', __name__)294+ bp.json_encoder = MyEncoder295+ bp.json_decoder = MyDecoder296+297+ @bp.route('/bp', methods=['POST'])298+ def index():299+ return flask.json.dumps(flask.request.get_json()['x'])300+301+ app = flask.Flask(__name__)302+ app.testing = True303+ app.register_blueprint(bp)304+305+ c = app.test_client()306+ rv = c.post('/bp', data=flask.json.dumps({307+ 'x': {'_foo': 42}308+ }), content_type='application/json')309+ assert rv.data == b'"<42>"'310+311 def test_modified_url_encoding(self):312 class ModifiedRequest(flask.Request):313 url_charset = 'euc-kr'314 app = flask.Flask(__name__)14 unmodified lines329 330 def test_json_key_sorting(self):331 app = flask.Flask(__name__)332 app.testing = True333+ app.debug = True334+335 assert app.config['JSON_SORT_KEYS'] == True336 d = dict.fromkeys(range(20), 'foo')337 338 @app.route('/')73 unmodified lines412 rv.direct_passthrough = False413 assert rv.data == f.read()414 rv.close()415 299- def test_send_file_xsendfile(self):416+ def test_send_file_xsendfile(self, catch_deprecation_warnings):417 app = flask.Flask(__name__)418 app.use_x_sendfile = True419 with app.test_request_context():420 rv = flask.send_file('static/index.html')3 unmodified lines424 os.path.join(app.root_path, 'static/index.html')425 assert rv.mimetype == 'text/html'426 rv.close()427 311- def test_send_file_object(self, catch_deprecation_warnings):428+ def test_send_file_last_modified(self):429 app = flask.Flask(__name__)313- with catch_deprecation_warnings() as captured:314- with app.test_request_context():315- f = open(os.path.join(app.root_path, 'static/index.html'), mode='rb')316- rv = flask.send_file(f)430+ last_modified = datetime.datetime(1999, 1, 1)431+432+ @app.route('/')433+ def index():434+ return flask.send_file(StringIO("party like it's"),435+ last_modified=last_modified,436+ mimetype='text/plain')437+438+ c = app.test_client()439+ rv = c.get('/')440+ assert rv.last_modified == last_modified441+442+ def test_send_file_object_without_mimetype(self):443+ app = flask.Flask(__name__)444+445+ with app.test_request_context():446+ with pytest.raises(ValueError) as excinfo:447+ flask.send_file(StringIO("LOL"))448+ assert 'Unable to infer MIME-type' in str(excinfo)449+ assert 'no filename is available' in str(excinfo)450+451+ with app.test_request_context():452+ flask.send_file(StringIO("LOL"), attachment_filename='filename')453+454+ def test_send_file_object(self):455+ app = flask.Flask(__name__)456+457+ with app.test_request_context():458+ with open(os.path.join(app.root_path, 'static/index.html'), mode='rb') as f:459+ rv = flask.send_file(f, mimetype='text/html')460 rv.direct_passthrough = False461 with app.open_resource('static/index.html') as f:462 assert rv.data == f.read()463 assert rv.mimetype == 'text/html'464 rv.close()322- # mimetypes + etag323- assert len(captured) == 2465 466 app.use_x_sendfile = True326- with catch_deprecation_warnings() as captured:327- with app.test_request_context():328- f = open(os.path.join(app.root_path, 'static/index.html'))329- rv = flask.send_file(f)467+468+ with app.test_request_context():469+ with open(os.path.join(app.root_path, 'static/index.html')) as f:470+ rv = flask.send_file(f, mimetype='text/html')471 assert rv.mimetype == 'text/html'331- assert 'x-sendfile' in rv.headers332- assert rv.headers['x-sendfile'] == \333- os.path.join(app.root_path, 'static/index.html')472+ assert 'x-sendfile' not in rv.headers473 rv.close()335- # mimetypes + etag336- assert len(captured) == 2474 475 app.use_x_sendfile = False476 with app.test_request_context():340- with catch_deprecation_warnings() as captured:341- f = StringIO('Test')342- rv = flask.send_file(f)343- rv.direct_passthrough = False344- assert rv.data == b'Test'345- assert rv.mimetype == 'application/octet-stream'346- rv.close()477+ f = StringIO('Test')478+ rv = flask.send_file(f, mimetype='application/octet-stream')479+ rv.direct_passthrough = False480+ assert rv.data == b'Test'481+ assert rv.mimetype == 'application/octet-stream'482+ rv.close()347- # etags348- assert len(captured) == 1349- with catch_deprecation_warnings() as captured:350- class PyStringIO(object):351- def __init__(self, *args, **kwargs):352- self._io = StringIO(*args, **kwargs)353- def __getattr__(self, name):354- return getattr(self._io, name)355- f = PyStringIO('Test')356- f.name = 'test.txt'357- rv = flask.send_file(f)358- rv.direct_passthrough = False359- assert rv.data == b'Test'360- assert rv.mimetype == 'text/plain'361- rv.close()362- # attachment_filename and etags363- assert len(captured) == 3364- with catch_deprecation_warnings() as captured:365- f = StringIO('Test')366- rv = flask.send_file(f, mimetype='text/plain')367- rv.direct_passthrough = False368- assert rv.data == b'Test'369- assert rv.mimetype == 'text/plain'370- rv.close()371- # etags372- assert len(captured) == 1483 484+ class PyStringIO(object):485+ def __init__(self, *args, **kwargs):486+ self._io = StringIO(*args, **kwargs)487+ def __getattr__(self, name):488+ return getattr(self._io, name)489+ f = PyStringIO('Test')490+ f.name = 'test.txt'491+ rv = flask.send_file(f, attachment_filename=f.name)492+ rv.direct_passthrough = False493+ assert rv.data == b'Test'494+ assert rv.mimetype == 'text/plain'495+ rv.close()496+497+ f = StringIO('Test')498+ rv = flask.send_file(f, mimetype='text/plain')499+ rv.direct_passthrough = False500+ assert rv.data == b'Test'501+ assert rv.mimetype == 'text/plain'502+ rv.close()503+504 app.use_x_sendfile = True375- with catch_deprecation_warnings() as captured:376- with app.test_request_context():377- f = StringIO('Test')378- rv = flask.send_file(f)379- assert 'x-sendfile' not in rv.headers380- rv.close()381- # etags382- assert len(captured) == 1505 384- def test_attachment(self, catch_deprecation_warnings):506+ with app.test_request_context():507+ f = StringIO('Test')508+ rv = flask.send_file(f, mimetype='text/html')509+ assert 'x-sendfile' not in rv.headers510+ rv.close()511+512+ @pytest.mark.skipif(513+ not callable(getattr(Range, 'to_content_range_header', None)),514+ reason="not implement within werkzeug"515+ )516+ def test_send_file_range_request(self):517 app = flask.Flask(__name__)386- with catch_deprecation_warnings() as captured:387- with app.test_request_context():388- f = open(os.path.join(app.root_path, 'static/index.html'))389- rv = flask.send_file(f, as_attachment=True)390- value, options = parse_options_header(rv.headers['Content-Disposition'])518+519+ @app.route('/')520+ def index():521+ return flask.send_file('static/index.html', conditional=True)522+523+ c = app.test_client()524+525+ rv = c.get('/', headers={'Range': 'bytes=4-15'})526+ assert rv.status_code == 206527+ with app.open_resource('static/index.html') as f:528+ assert rv.data == f.read()[4:16]529+ rv.close()530+531+ rv = c.get('/', headers={'Range': 'bytes=4-'})532+ assert rv.status_code == 206533+ with app.open_resource('static/index.html') as f:534+ assert rv.data == f.read()[4:]535+ rv.close()536+537+ rv = c.get('/', headers={'Range': 'bytes=4-1000'})538+ assert rv.status_code == 206539+ with app.open_resource('static/index.html') as f:540+ assert rv.data == f.read()[4:]541+ rv.close()542+543+ rv = c.get('/', headers={'Range': 'bytes=-10'})544+ assert rv.status_code == 206545+ with app.open_resource('static/index.html') as f:546+ assert rv.data == f.read()[-10:]547+ rv.close()548+549+ rv = c.get('/', headers={'Range': 'bytes=1000-'})550+ assert rv.status_code == 416551+ rv.close()552+553+ rv = c.get('/', headers={'Range': 'bytes=-'})554+ assert rv.status_code == 416555+ rv.close()556+557+ rv = c.get('/', headers={'Range': 'somethingsomething'})558+ assert rv.status_code == 416559+ rv.close()560+561+ last_modified = datetime.datetime.utcfromtimestamp(os.path.getmtime(562+ os.path.join(app.root_path, 'static/index.html'))).replace(563+ microsecond=0)564+565+ rv = c.get('/', headers={'Range': 'bytes=4-15',566+ 'If-Range': http_date(last_modified)})567+ assert rv.status_code == 206568+ rv.close()569+570+ rv = c.get('/', headers={'Range': 'bytes=4-15', 'If-Range': http_date(571+ datetime.datetime(1999, 1, 1))})572+ assert rv.status_code == 200573+ rv.close()574+575+ def test_attachment(self):576+ app = flask.Flask(__name__)577+ with app.test_request_context():578+ with open(os.path.join(app.root_path, 'static/index.html')) as f:579+ rv = flask.send_file(f, as_attachment=True,580+ attachment_filename='index.html')581+ value, options = \582+ parse_options_header(rv.headers['Content-Disposition'])583 assert value == 'attachment'584+ assert options['filename'] == 'index.html'585+ assert 'filename*' not in rv.headers['Content-Disposition']586 rv.close()393- # mimetypes + etag394- assert len(captured) == 2587 588 with app.test_request_context():397- assert options['filename'] == 'index.html'589 rv = flask.send_file('static/index.html', as_attachment=True)590 value, options = parse_options_header(rv.headers['Content-Disposition'])591 assert value == 'attachment'592 assert options['filename'] == 'index.html'8 unmodified lines601 assert value == 'attachment'602 assert options['filename'] == 'index.txt'603 rv.close()604 605+ def test_attachment_with_utf8_filename(self):606+ app = flask.Flask(__name__)607+608+ with app.test_request_context():609+ rv = flask.send_file('static/index.html', as_attachment=True, attachment_filename=u'Ñandú/pingüino.txt')610+ content_disposition = set(rv.headers['Content-Disposition'].split('; '))611+ assert content_disposition == set((612+ 'attachment',613+ 'filename="Nandu/pinguino.txt"',614+ "filename*=UTF-8''%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt"615+ ))616+ rv.close()617+618 def test_static_file(self):619 app = flask.Flask(__name__)620 # default cache timeout is 12 hours621 with app.test_request_context():45 unmodified lines667 rv.direct_passthrough = False668 assert rv.data.strip() == b'Hello Subdomain'669 rv.close()670 671+ def test_send_from_directory_bad_request(self):672+ app = flask.Flask(__name__)673+ app.testing = True674+ app.root_path = os.path.join(os.path.dirname(__file__),675+ 'test_apps', 'subdomaintestmodule')676+ with app.test_request_context():677+ with pytest.raises(BadRequest):678+ flask.send_from_directory('static', 'bad\x00')679 680 class TestLogging(object):681 682 def test_logger_cache(self):106 unmodified lines789 flask.url_for,790 'index',791 _scheme='https')792 793+ def test_url_for_with_alternating_schemes(self):794+ app = flask.Flask(__name__)795+ @app.route('/')796+ def index():797+ return '42'798+ with app.test_request_context():799+ assert flask.url_for('index', _external=True) == 'http://localhost/'800+ assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'801+ assert flask.url_for('index', _external=True) == 'http://localhost/'802+803 def test_url_with_method(self):804 from flask.views import MethodView805 app = flask.Flask(__name__)806 class MyView(MethodView):57 unmodified lines864 app.testing = True865 @app.route('/')866 def index():867 @flask.stream_with_context646- def generate():647- yield 'Hello '868+ def generate(hello):869+ yield hello870 yield flask.request.args['name']871 yield '!'650- return flask.Response(generate())872+ return flask.Response(generate('Hello '))873 c = app.test_client()874 rv = c.get('/?name=World')875 assert rv.data == b'Hello World!'876 22 unmodified lines899 c = app.test_client()900 rv = c.get('/?name=World')901 assert rv.data == b'Hello World!'902 assert called == [42]903+904+905+class TestSafeJoin(object):906+907+ def test_safe_join(self):908+ # Valid combinations of *args and expected joined paths.909+ passing = (910+ (('a/b/c', ), 'a/b/c'),911+ (('/', 'a/', 'b/', 'c/', ), '/a/b/c'),912+ (('a', 'b', 'c', ), 'a/b/c'),913+ (('/a', 'b/c', ), '/a/b/c'),914+ (('a/b', 'X/../c'), 'a/b/c', ),915+ (('/a/b', 'c/X/..'), '/a/b/c', ),916+ # If last path is '' add a slash917+ (('/a/b/c', '', ), '/a/b/c/', ),918+ # Preserve dot slash919+ (('/a/b/c', './', ), '/a/b/c/.', ),920+ (('a/b/c', 'X/..'), 'a/b/c/.', ),921+ # Base directory is always considered safe922+ (('../', 'a/b/c'), '../a/b/c'),923+ (('/..', ), '/..'),924+ )925+926+ for args, expected in passing:927+ assert flask.safe_join(*args) == expected928+929+ def test_safe_join_exceptions(self):930+ # Should raise werkzeug.exceptions.NotFound on unsafe joins.931+ failing = (932+ # path.isabs and ``..'' checks933+ ('/a', 'b', '/c'),934+ ('/a', '../b/c', ),935+ ('/a', '..', 'b/c'),936+ # Boundaries violations after path normalization937+ ('/a', 'b/../b/../../c', ),938+ ('/a', 'b', 'c/../..'),939+ ('/a', 'b/../../c', ),940+ )941+942+ for args in failing:943+ with pytest.raises(NotFound):944+ print(flask.safe_join(*args))modified:tests/test_regression.py+1 added-2 removed
37 unmodified lines38 gc.collect()39 self.old_objects = len(gc.get_objects())40 41 def __exit__(self, exc_type, exc_value, tb):42- if not hasattr(sys, 'getrefcount'):43- gc.collect()42+ gc.collect()43 new_objects = len(gc.get_objects())44 if new_objects > self.old_objects:45 pytest.fail('Example code leaked')46 _gc_lock.release()56 unmodified linesmodified:tests/test_reqctx.py+26 added-5 removed
10 unmodified lines11 12 import pytest13 14 import flask15+from flask.sessions import SessionInterface16 17 try:18 from greenlet import greenlet19 except ImportError:120 unmodified lines140 ctx = app.test_request_context('/?name=World')141 ctx.push()142 assert index() == 'Hello World!'143 ctx.pop()143- try:144+ with pytest.raises(RuntimeError):145 index()145- except RuntimeError:146- pass147- else:148- assert 0, 'expected runtime error'146 147 @pytest.mark.skipif(greenlet is None, reason='greenlet not installed')148 def test_greenlet_context_copying():149 app = flask.Flask(__name__)43 unmodified lines193 assert rv.data == b'Hello World!'194 195 result = greenlets[0].run()196 assert result == 42197+198+199+def test_session_error_pops_context():200+ class SessionError(Exception):201+ pass202+203+ class FailingSessionInterface(SessionInterface):204+ def open_session(self, app, request):205+ raise SessionError()206+207+ class CustomFlask(flask.Flask):208+ session_interface = FailingSessionInterface()209+210+ app = CustomFlask(__name__)211+212+ @app.route('/')213+ def index():214+ # shouldn't get here215+ assert False216+217+ response = app.test_client().get('/')218+ assert response.status_code == 500219+ assert not flask.request220+ assert not flask.current_appmodified:tests/test_testing.py+39 added-10 removed
9 unmodified lines10 """11 import pytest12 13 import flask14+import werkzeug15 16 from flask._compat import text_type17 18 24 unmodified lines43 with app.test_client() as c:44 rv = c.get('/')45 assert rv.data == b'http://localhost/'46 47+def test_environ_base_default():48+ app = flask.Flask(__name__)49+ app.testing = True50+ @app.route('/')51+ def index():52+ flask.g.user_agent = flask.request.headers["User-Agent"]53+ return flask.request.remote_addr54+55+ with app.test_client() as c:56+ rv = c.get('/')57+ assert rv.data == b'127.0.0.1'58+ assert flask.g.user_agent == 'werkzeug/' + werkzeug.__version__59+60+def test_environ_base_modified():61+ app = flask.Flask(__name__)62+ app.testing = True63+ @app.route('/')64+ def index():65+ flask.g.user_agent = flask.request.headers["User-Agent"]66+ return flask.request.remote_addr67+68+ with app.test_client() as c:69+ c.environ_base['REMOTE_ADDR'] = '0.0.0.0'70+ c.environ_base['HTTP_USER_AGENT'] = 'Foo'71+ rv = c.get('/')72+ assert rv.data == b'0.0.0.0'73+ assert flask.g.user_agent == 'Foo'74+75+ c.environ_base['REMOTE_ADDR'] = '0.0.0.1'76+ c.environ_base['HTTP_USER_AGENT'] = 'Bar'77+ rv = c.get('/')78+ assert rv.data == b'0.0.0.1'79+ assert flask.g.user_agent == 'Bar'80+81 def test_redirect_keep_session():82 app = flask.Flask(__name__)83 app.secret_key = 'testing'84 49 unmodified lines134 app = flask.Flask(__name__)135 app.testing = True136 137 with app.test_client() as c:103- try:138+ with pytest.raises(RuntimeError) as e:139 with c.session_transaction() as sess:140 pass106- except RuntimeError as e:107- assert 'Session backend did not open a session' in str(e)141+ assert 'Session backend did not open a session' in str(e.value)108- else:109- assert False, 'Expected runtime error'142 143 def test_session_transactions_keep_context():144 app = flask.Flask(__name__)145 app.testing = True9 unmodified lines155 def test_session_transaction_needs_cookies():156 app = flask.Flask(__name__)157 app.testing = True158 c = app.test_client(use_cookies=False)127- try:159+ with pytest.raises(RuntimeError) as e:160 with c.session_transaction() as s:161 pass130- except RuntimeError as e:131- assert 'cookies' in str(e)162+ assert 'cookies' in str(e.value)132- else:133- assert False, 'Expected runtime error'163 164 def test_test_client_context_binding():165 app = flask.Flask(__name__)166 app.config['LOGGER_HANDLER_POLICY'] = 'never'105 unmodified linesmodified:tests/test_views.py+42 added
158 unmodified lines159 app.add_url_rule('/', view_func=Index.as_view('index'))160 161 # But these tests should still pass. We just log a warning.162 common_test(app)163+164+def test_multiple_inheritance():165+ app = flask.Flask(__name__)166+167+ class GetView(flask.views.MethodView):168+ def get(self):169+ return 'GET'170+171+ class DeleteView(flask.views.MethodView):172+ def delete(self):173+ return 'DELETE'174+175+ class GetDeleteView(GetView, DeleteView):176+ pass177+178+ app.add_url_rule('/', view_func=GetDeleteView.as_view('index'))179+180+ c = app.test_client()181+ assert c.get('/').data == b'GET'182+ assert c.delete('/').data == b'DELETE'183+ assert sorted(GetDeleteView.methods) == ['DELETE', 'GET']184+185+def test_remove_method_from_parent():186+ app = flask.Flask(__name__)187+188+ class GetView(flask.views.MethodView):189+ def get(self):190+ return 'GET'191+192+ class OtherView(flask.views.MethodView):193+ def post(self):194+ return 'POST'195+196+ class View(GetView, OtherView):197+ methods = ['GET']198+199+ app.add_url_rule('/', view_func=View.as_view('index'))200+201+ c = app.test_client()202+ assert c.get('/').data == b'GET'203+ assert c.post('/').status_code == 405204+ assert sorted(View.methods) == ['GET']added:.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+*,covermodified:.travis.yml+14 added-1 removed
6 unmodified lines7 - "pypy"8 - "3.3"9 - "3.4"10 - "3.5"11+ - "3.6"12 13 env:14 - REQUIREMENTS=lowest15+ - REQUIREMENTS=lowest-simplejson16 - REQUIREMENTS=release17+ - REQUIREMENTS=release-simplejson18 - REQUIREMENTS=devel19+ - REQUIREMENTS=devel-simplejson20 21 matrix:22 exclude:23 # Python 3 support currently does not work with lowest requirements24 - python: "3.3"25 env: REQUIREMENTS=lowest26+ - python: "3.3"27+ env: REQUIREMENTS=lowest-simplejson28 - python: "3.4"29 env: REQUIREMENTS=lowest30+ - python: "3.4"31+ env: REQUIREMENTS=lowest-simplejson32 - python: "3.5"33 env: REQUIREMENTS=lowest34+ - python: "3.5"35+ env: REQUIREMENTS=lowest-simplejson36+ - python: "3.6"37+ env: REQUIREMENTS=lowest38+ - python: "3.6"39+ env: REQUIREMENTS=lowest-simplejson40 27-41 install:42 - pip install tox43 44 script:15 unmodified linesmodified:AUTHORS+4 added-1 removed
13 unmodified lines14 - Chris Edgemon15 - Chris Grindstaff16 - Christopher Grebs17 - Daniel Neuhäuser18+- Dan Sully19+- David Lord @davidism20 - Edmond Burnett21 - Florent Xicluna22 - Georg Brandl23+- Jeff Widman @jeffwidman24+- Joshua Bronson @jab25 - Justin Quick26 - Kenneth Reitz27 - Keyan Pishdadian28 - Marian Sigler6 unmodified lines35 - Simon Sapin36 - Stephane Wirtel37 - Thomas Schranz38 - Zhao Xiaohong35-- David Lord @davidismmodified:CHANGES+104 added-6 removed
1 unmodified line2 ===============3 4 Here you can see the full list of changes between each Flask release.5 6-Version 1.07------------6+Version 0.137+------------8 9-(release date to be announced, codename to be selected)9+Major release, unreleased10 11+- Make `app.run()` into a noop if a Flask application is run from the12+ development server on the command line. This avoids some behavior that13+ was confusing to debug for newcomers.14+- Change default configuration `JSONIFY_PRETTYPRINT_REGULAR=False`. jsonify()15+ method returns compressed response by default, and pretty response in16+ debug mode.17+- Change Flask.__init__ to accept two new keyword arguments, ``host_matching``18+ and ``static_host``. This enables ``host_matching`` to be set properly by the19+ time the constructor adds the static route, and enables the static route to20+ be properly associated with the required host. (``#1559``)21+- ``send_file`` supports Unicode in ``attachment_filename``. (`#2223`_)22+- Pass ``_scheme`` argument from ``url_for`` to ``handle_build_error``.23+ (`#2017`_)24+- Add support for ``provide_automatic_options`` in ``add_url_rule`` to disable25+ adding OPTIONS method when the ``view_func`` argument is not a class.26+ (`#1489`_).27+- ``MethodView`` can inherit method handlers from base classes. (`#1936`_)28+- Errors caused while opening the session at the beginning of the request are29+ handled by the app's error handlers. (`#2254`_)30+- Blueprints gained ``json_encoder`` and ``json_decoder`` attributes to31+ override the app's encoder and decoder. (`#1898`_)32+- ``Flask.make_response`` raises ``TypeError`` instead of ``ValueError`` for33+ bad response types. The error messages have been improved to describe why the34+ type is invalid. (`#2256`_)35+36+.. _#1489: https://github.com/pallets/flask/pull/148937+.. _#1898: https://github.com/pallets/flask/pull/189838+.. _#1936: https://github.com/pallets/flask/pull/193639+.. _#2017: https://github.com/pallets/flask/pull/201740+.. _#2223: https://github.com/pallets/flask/pull/222341+.. _#2254: https://github.com/pallets/flask/pull/225442+.. _#2256: https://github.com/pallets/flask/pull/225643+44+Version 0.12.145+--------------46+47+Bugfix release, released on March 31st 201748+49+- Prevent `flask run` from showing a NoAppException when an ImportError occurs50+ within the imported application module.51+- Fix encoding behavior of ``app.config.from_pyfile`` for Python 3. Fix52+ ``#2118``.53+- Use the ``SERVER_NAME`` config if it is present as default values for54+ ``app.run``. ``#2109``, ``#2152``55+- Call `ctx.auto_pop` with the exception object instead of `None`, in the56+ event that a `BaseException` such as `KeyboardInterrupt` is raised in a57+ request handler.58+59+Version 0.1260+------------61+62+Released on December 21st 2016, codename Punsch.63+64+- the cli command now responds to `--version`.65+- Mimetype guessing and ETag generation for file-like objects in ``send_file``66+ has been removed, as per issue ``#104``. See pull request ``#1849``.67+- Mimetype guessing in ``send_file`` now fails loudly and doesn't fall back to68+ ``application/octet-stream``. See pull request ``#1988``.69+- Make ``flask.safe_join`` able to join multiple paths like ``os.path.join``70+ (pull request ``#1730``).71+- Revert a behavior change that made the dev server crash instead of returning72+ a Internal Server Error (pull request ``#2006``).73+- Correctly invoke response handlers for both regular request dispatching as74+ well as error handlers.75+- Disable logger propagation by default for the app logger.76+- Add support for range requests in ``send_file``.77+- ``app.test_client`` includes preset default environment, which can now be78+ directly set, instead of per ``client.get``.79+80+Version 0.11.281+--------------82+83+Bugfix release, unreleased84+85+- Fix crash when running under PyPy3, see pull request ``#1814``.86+87+Version 0.11.188+--------------89+90+Bugfix release, released on June 7th 2016.91+92+- Fixed a bug that prevented ``FLASK_APP=foobar/__init__.py`` from working. See93+ pull request ``#1872``.94+95+Version 0.1196+------------97+98+Released on May 29th 2016, codename Absinthe.99+100+- Added support to serializing top-level arrays to :func:`flask.jsonify`. This101+ introduces a security risk in ancient browsers. See102+ :ref:`json-security` for details.103 - Added before_render_template signal.104 - Added `**kwargs` to :meth:`flask.Test.test_client` to support passing105 additional keyword arguments to the constructor of106 :attr:`flask.Flask.test_client_class`.7 unmodified lines114 - Added support for returning tuples in the form ``(response, headers)``115 from a view function.116 - Added :meth:`flask.Config.from_json`.117 - Added :attr:`flask.Flask.config_class`.26-- Added :meth:`flask.config.Config.get_namespace`.118+- Added :meth:`flask.Config.get_namespace`.119 - Templates are no longer automatically reloaded outside of debug mode. This120 can be configured with the new ``TEMPLATES_AUTO_RELOAD`` config key.121 - Added a workaround for a limitation in Python 3.3's namespace loader.122 - Added support for explicit root paths when using Python 3.3's namespace25 unmodified lines148 unnecessary white space included by default after separators.149 - JSON responses are now terminated with a newline character, because it is a150 convention that UNIX text files end with a newline and some clients don't151 deal well when this newline is missing. See60- https://github.com/mitsuhiko/flask/pull/1262 -- this came up originally as a152+ https://github.com/pallets/flask/pull/1262 -- this came up originally as a153 part of https://github.com/kennethreitz/httpbin/issues/168154 - The automatically provided ``OPTIONS`` method is now correctly disabled if155 the user registered an overriding rule with the lowercase-version156 ``options`` (issue ``#1288``).4 unmodified lines161 - Allow custom Jinja environment subclasses (pull request ``#1422``).162 - ``flask.g`` now has ``pop()`` and ``setdefault`` methods.163 - Turn on autoescape for ``flask.templating.render_template_string`` by default164 (pull request ``#1515``).165+- ``flask.ext`` is now deprecated (pull request ``#1484``).166+- ``send_from_directory`` now raises BadRequest if the filename is invalid on167+ the server OS (pull request ``#1763``).168+- Added the ``JSONIFY_MIMETYPE`` configuration variable (pull request ``#1728``).169+- Exceptions during teardown handling will no longer leave bad application170+ contexts lingering around.171 172 Version 0.10.2173 --------------174 214 unmodified lines389 error if not handled. This is a backwards incompatible change.390 - Applications now not only have a root path where the resources and modules391 are located but also an instance path which is the designated place to392 drop files that are modified at runtime (uploads etc.). Also this is295- conceptionally only instance depending and outside version control so it's393+ conceptually only instance depending and outside version control so it's394 the perfect place to put configuration files etc. For more information395 see :ref:`instance-folders`.396 - Added the ``APPLICATION_ROOT`` configuration variable.397 - Implemented :meth:`~flask.testing.TestClient.session_transaction` to257 unmodified linesmodified:CONTRIBUTING.rst+53 added-11 removed
8 unmodified lines9 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-`StackOverflow <https://stackoverflow.com/>`_ is also worth considering.13+`Stack Overflow <https://stackoverflow.com/>`_ is also worth considering.14 15 Reporting issues16 ================17 9 unmodified lines27 - Include tests if your patch is supposed to solve a bug, and explain28 clearly under which circumstances the bug happens. Make sure the test fails29 without your patch.30 31-- Try to follow `PEP8 <http://legacy.python.org/dev/peps/pep-0008/>`_, but you31+- Try to follow `PEP8 <https://www.python.org/dev/peps/pep-0008/>`_, but you32 may ignore the line-length-limit if following it would make the code uglier.33 34 35 Running the testsuite36 ---------------------37 38 You probably want to set up a `virtualenv39-<http://virtualenv.readthedocs.org/en/latest/index.html>`_.39+<https://virtualenv.readthedocs.io/en/latest/index.html>`_.40 41-The minimal requirement for running the testsuite is ``py.test``. You can41+The minimal requirement for running the testsuite is ``pytest``. You can42 install it with::43 44 pip install pytest45 46 Clone this repository::47 48- git clone https://github.com/mitsuhiko/flask.git48+ git clone https://github.com/pallets/flask.git49 50 Install Flask as an editable package using the current source::51 52 cd flask53 pip install --editable .54 55 Then you can run the testsuite with::56 57- py.test57+ pytest58 59-With only py.test installed, a large part of the testsuite will get skipped59+With only pytest installed, a large part of the testsuite will get skipped60 though. Whether this is relevant depends on which part of Flask you're working61 on. Travis is set up to run the full testsuite when you submit your pull62 request anyways.63 64 If you really want to test everything, you will have to install ``tox`` instead65-of ``pytest``. Currently we're depending on a development version of Tox66-because the released version is missing features we absolutely need. You can67-install it with::65+of ``pytest``. You can install it with::66 69- pip install hg+https://bitbucket.org/hpk42/tox67+ pip install tox68 69 The ``tox`` command will then run all tests against multiple combinations70 Python versions and dependency versions.71+72+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)::77+78+ pip install pytest-cov79+80+After this has been installed, you can output a report to the command line using this command::81+82+ pytest --cov=flask tests/83+84+Generate a HTML report can be done using this command::85+86+ pytest --cov-report html --cov=flask tests/87+88+Full docs on ``coverage.py`` are here: https://coverage.readthedocs.io89+90+Caution91+=======92+pushing93+-------94+This repository contains several zero-padded file modes that may cause issues when pushing this repository to git hosts other than github. Fixing this is destructive to the commit history, so we suggest ignoring these warnings. If it fails to push and you're using a self-hosted git service like Gitlab, you can turn off repository checks in the admin panel.95+96+97+cloning98+-------99+The zero-padded file modes files above can cause issues while cloning, too. If you have100+101+::102+103+ [fetch]104+ fsckobjects = true105+106+or107+108+::109+110+ [receive]111+ fsckObjects = true112+113+114+set in your git configuration file, cloning this repository will fail. The only solution is to set both of the above settings to false while cloning, and then setting them back to true after the cloning is finished.modified:Makefile+2 added-4 removed
1 unmodified line2 3 all: clean-pyc test4 5 test:6- py.test tests examples6+ pip install -r test-requirements.txt7+ tox -e py-release8 8-tox-test:9- tox10-9 audit:10 python setup.py audit11 12 release:29 unmodified linesmodified:MANIFEST.in+8 added-10 removed
1 include Makefile CHANGES LICENSE AUTHORS2-recursive-include artwork *3-recursive-include tests *4-recursive-include examples *5-recursive-include docs *6-recursive-exclude docs *.pyc7-recursive-exclude docs *.pyo8-recursive-exclude tests *.pyc9-recursive-exclude tests *.pyo10-recursive-exclude examples *.pyc11-recursive-exclude examples *.pyo2+3+graft artwork4+graft tests5+graft examples6+graft docs7+8+global-exclude *.py[co]9+10 prune docs/_build11 prune docs/_themesmodified:README+4 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?43 44 Either use the #pocoo IRC channel on irc.freenode.net or45 ask on the mailinglist: http://flask.pocoo.org/mailinglist/4 unmodified linesmodified:setup.cfg+5 added-2 removed
1 [aliases]2 release = egg_info -RDb ''3 4-[wheel]4+[bdist_wheel]5 universal = 16 7-[pytest]7+[metadata]8+license_file = LICENSE9+10+[tool:pytest]11 norecursedirs = .* *.egg *.egg-info env* artwork docsmodified:setup.py+4 added-2 removed
31 unmodified lines32 $ pip install Flask33 $ python hello.py34 * Running on http://localhost:5000/35 36+ Ready for production? `Read this first <http://flask.pocoo.org/docs/deploying/>`.37+38 Links39 `````40 41 * `website <http://flask.pocoo.org/>`_42 * `documentation <http://flask.pocoo.org/docs/>`_43 * `development version42- <http://github.com/mitsuhiko/flask/zipball/master#egg=Flask-dev>`_44+ <https://github.com/pallets/flask/zipball/master#egg=Flask-dev>`_45 46 """47 import re48 import ast9 unmodified lines58 59 setup(60 name='Flask',61 version=version,60- url='http://github.com/mitsuhiko/flask/',62+ url='https://github.com/pallets/flask/',63 license='BSD',64 author='Armin Ronacher',65 author_email='armin.ronacher@active-4.com',66 description='A microframework based on Werkzeug, Jinja2 '34 unmodified linesadded:test-requirements.txt+1 added
1+toxmodified:tox.ini+15 added-7 removed
1 [tox]2-envlist = {py26,py27,pypy}-{lowest,release,devel}, {py33,py34,py35}-{release,devel}2+envlist = {py26,py27,pypy}-{lowest,release,devel}{,-simplejson}, {py33,py34,py35,py36}-{release,devel}{,-simplejson}3 4+5+6 [testenv]7+passenv = LANG8+usedevelop=true9 commands =6- py.test []7-10+ # We need to install those after Flask is installed.11+ pip install -e examples/flaskr12+ pip install -e examples/minitwit13+ pip install -e examples/patterns/largerapp14+ pytest --cov=flask --cov-report html []15 deps=16 pytest17+ pytest-cov18 greenlet11- redbaron19 20 lowest: Werkzeug==0.721 lowest: Jinja2==2.422 lowest: itsdangerous==0.2123 lowest: blinker==1.024 release: blinker18- devel: git+https://github.com/mitsuhiko/werkzeug.git19- devel: git+https://github.com/mitsuhiko/jinja2.git20- devel: git+https://github.com/mitsuhiko/itsdangerous.git25+ devel: git+https://github.com/pallets/werkzeug.git26+ devel: git+https://github.com/pallets/jinja.git27+ devel: git+https://github.com/pallets/itsdangerous.git28 devel: git+https://github.com/jek/blinker.git29+ simplejson: simplejson30 31 [testenv:docs]32 deps = sphinx33 commands = sphinx-build -W -b linkcheck -d {envtmpdir}/doctrees docs docs/_build/linkcheck