Skip to content
Myr

resolve merge conflicts

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

authored by Kenneth Reitz · committed by Kenneth Reitz · parents f80ea4f, 90854c7 · Browse files · 183 files+7307 added−4855 removed
This commit

State

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

Diff stats

183 files+7307 added−4855 removed

  • tests:+2889 added−1217 removed
  • other:+4418 added−3638 removed

183 files+7307 added−4855 removed

added:.github/ISSUE_TEMPLATE.rst+2 added
1The issue tracker is a tool to address bugs.2Please use the #pocoo IRC channel on freenode or Stack Overflow for questions.
added:artwork/logo-lineart.svg+165 added
1<?xml version="1.0" encoding="UTF-8" standalone="no"?>2<!-- Created with Inkscape (http://www.inkscape.org/) -->34<svg5 xmlns:dc="http://purl.org/dc/elements/1.1/"6 xmlns:cc="http://creativecommons.org/ns#"7 xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"8 xmlns:svg="http://www.w3.org/2000/svg"9 xmlns="http://www.w3.org/2000/svg"10 xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"11 xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"12 width="211.15901"13 height="190.52811"14 id="svg2"15 version="1.1"16 inkscape:version="0.48.5 r10040"17 sodipodi:docname="logo-lineart.svg">18 <defs19 id="defs4">20 <inkscape:perspective21 sodipodi:type="inkscape:persp3d"22 inkscape:vp_x="0 : 526.18109 : 1"23 inkscape:vp_y="0 : 1000 : 0"24 inkscape:vp_z="744.09448 : 526.18109 : 1"25 inkscape:persp3d-origin="372.04724 : 350.78739 : 1"26 id="perspective10" />27 <inkscape:perspective28 id="perspective2824"29 inkscape:persp3d-origin="0.5 : 0.33333333 : 1"30 inkscape:vp_z="1 : 0.5 : 1"31 inkscape:vp_y="0 : 1000 : 0"32 inkscape:vp_x="0 : 0.5 : 1"33 sodipodi:type="inkscape:persp3d" />34 <inkscape:perspective35 id="perspective2840"36 inkscape:persp3d-origin="0.5 : 0.33333333 : 1"37 inkscape:vp_z="1 : 0.5 : 1"38 inkscape:vp_y="0 : 1000 : 0"39 inkscape:vp_x="0 : 0.5 : 1"40 sodipodi:type="inkscape:persp3d" />41 <inkscape:perspective42 id="perspective2878"43 inkscape:persp3d-origin="0.5 : 0.33333333 : 1"44 inkscape:vp_z="1 : 0.5 : 1"45 inkscape:vp_y="0 : 1000 : 0"46 inkscape:vp_x="0 : 0.5 : 1"47 sodipodi:type="inkscape:persp3d" />48 <inkscape:perspective49 id="perspective2894"50 inkscape:persp3d-origin="0.5 : 0.33333333 : 1"51 inkscape:vp_z="1 : 0.5 : 1"52 inkscape:vp_y="0 : 1000 : 0"53 inkscape:vp_x="0 : 0.5 : 1"54 sodipodi:type="inkscape:persp3d" />55 <inkscape:perspective56 id="perspective2910"57 inkscape:persp3d-origin="0.5 : 0.33333333 : 1"58 inkscape:vp_z="1 : 0.5 : 1"59 inkscape:vp_y="0 : 1000 : 0"60 inkscape:vp_x="0 : 0.5 : 1"61 sodipodi:type="inkscape:persp3d" />62 <inkscape:perspective63 id="perspective2926"64 inkscape:persp3d-origin="0.5 : 0.33333333 : 1"65 inkscape:vp_z="1 : 0.5 : 1"66 inkscape:vp_y="0 : 1000 : 0"67 inkscape:vp_x="0 : 0.5 : 1"68 sodipodi:type="inkscape:persp3d" />69 <inkscape:perspective70 id="perspective2976"71 inkscape:persp3d-origin="0.5 : 0.33333333 : 1"72 inkscape:vp_z="1 : 0.5 : 1"73 inkscape:vp_y="0 : 1000 : 0"74 inkscape:vp_x="0 : 0.5 : 1"75 sodipodi:type="inkscape:persp3d" />76 <inkscape:perspective77 id="perspective3020"78 inkscape:persp3d-origin="0.5 : 0.33333333 : 1"79 inkscape:vp_z="1 : 0.5 : 1"80 inkscape:vp_y="0 : 1000 : 0"81 inkscape:vp_x="0 : 0.5 : 1"82 sodipodi:type="inkscape:persp3d" />83 <inkscape:perspective84 id="perspective3036"85 inkscape:persp3d-origin="0.5 : 0.33333333 : 1"86 inkscape:vp_z="1 : 0.5 : 1"87 inkscape:vp_y="0 : 1000 : 0"88 inkscape:vp_x="0 : 0.5 : 1"89 sodipodi:type="inkscape:persp3d" />90 <inkscape:perspective91 id="perspective3052"92 inkscape:persp3d-origin="0.5 : 0.33333333 : 1"93 inkscape:vp_z="1 : 0.5 : 1"94 inkscape:vp_y="0 : 1000 : 0"95 inkscape:vp_x="0 : 0.5 : 1"96 sodipodi:type="inkscape:persp3d" />97 <inkscape:perspective98 id="perspective3866"99 inkscape:persp3d-origin="0.5 : 0.33333333 : 1"100 inkscape:vp_z="1 : 0.5 : 1"101 inkscape:vp_y="0 : 1000 : 0"102 inkscape:vp_x="0 : 0.5 : 1"103 sodipodi:type="inkscape:persp3d" />104 </defs>105 <sodipodi:namedview106 id="base"107 pagecolor="#ffffff"108 bordercolor="#666666"109 borderopacity="1.0"110 inkscape:pageopacity="0.0"111 inkscape:pageshadow="2"112 inkscape:zoom="2.1723341"113 inkscape:cx="242.05817"114 inkscape:cy="92.686293"115 inkscape:document-units="px"116 inkscape:current-layer="layer1"117 showgrid="false"118 inkscape:window-width="1676"119 inkscape:window-height="1005"120 inkscape:window-x="4"121 inkscape:window-y="0"122 inkscape:window-maximized="1"123 fit-margin-top="10"124 fit-margin-left="10"125 fit-margin-right="10"126 fit-margin-bottom="10" />127 <metadata128 id="metadata7">129 <rdf:RDF>130 <cc:Work131 rdf:about="">132 <dc:format>image/svg+xml</dc:format>133 <dc:type134 rdf:resource="http://purl.org/dc/dcmitype/StillImage" />135 <dc:title></dc:title>136 </cc:Work>137 </rdf:RDF>138 </metadata>139 <g140 inkscape:label="Layer 1"141 inkscape:groupmode="layer"142 id="layer1"143 transform="translate(-29.820801,-20.186869)">144 <path145 style="fill:none;stroke:#000000;stroke-width:2;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"146 d="M 9.7525867,55.788422 C 40.421293,45.982204 33.821969,46.567748 69.327984,40.346648 c 8.493721,2.411576 22.910914,5.687215 22.240236,12.296506 -6.241933,2.320572 -15.351869,-6.455434 -20.254712,-1.539882 0.01014,18.421641 5.965221,38.200493 13.480678,55.747588 7.515457,17.5471 18.880714,32.86245 34.290034,42.35708 20.42595,12.66826 41.92048,14.9356 63.64846,15.65546 6.66858,0.23786 17.30912,-1.47838 20.01846,0 -4.9124,8.703 -19.28006,12.8118 -34.21844,14.71154 -14.93837,1.89974 -30.44747,1.59043 -37.64272,1.45723 -15.88921,-0.50065 -29.5942,-2.65111 -42.06658,-7.29048 C 56.640409,160.78176 38.428746,134.71246 24.668078,106.25832 16.765019,89.693325 11.290118,72.259923 9.7525867,55.788422 z"147 id="path3826"148 inkscape:connector-curvature="0"149 transform="translate(29.820801,20.186869)"150 sodipodi:nodetypes="ccccscccscccc" />151 <path152 style="fill:none;stroke:#000000;stroke-width:2;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"153 d="m 54.066806,32.351647 c -0.427165,0.87404 -0.384822,1.998232 -0.02834,2.90275 0.781834,1.983761 2.799883,3.252081 4.397491,4.681241 0.728446,0.651642 2.26934,0.803097 2.364296,1.769134 0.215279,2.190161 -2.700769,3.566537 -4.456242,4.921486 -1.316317,1.015991 -3.845581,0.776849 -4.451985,2.314219 -0.417515,1.058499 0.837317,2.10047 1.1679,3.188615 0.465799,1.533243 1.642442,3.150334 1.145997,4.674061 -0.597449,1.833868 -2.700081,2.84663 -4.420626,3.754433 -1.893115,0.998854 -4.450538,0.497797 -6.207667,1.715064 -1.674125,1.159765 -3.485979,2.907099 -3.554321,4.925579 -0.03097,0.915115 -0.384582,2.676814 -0.233936,3.114037 12.863193,-4.155671 20.195138,-6.507915 28.694286,-8.598094 8.499136,-2.090222 16.108852,-3.399531 29.579722,-5.689662 -0.06867,-0.457321 -1.197061,-1.855664 -1.647827,-2.652661 -0.994254,-1.75795 -3.408869,-2.469029 -5.429591,-2.722885 -2.120906,-0.26644 -4.15652,1.360749 -6.296964,1.350851 -1.945327,-0.009 -4.277958,0.06569 -5.655921,-1.283841 -1.144955,-1.121286 -0.849755,-3.099246 -1.145997,-4.674061 -0.210243,-1.117649 0.420309,-2.621884 -0.439473,-3.367212 -1.248754,-1.082519 -3.380554,0.299434 -5.017542,0.0075 -2.183125,-0.389274 -5.405114,-0.260713 -6.227327,-2.302063 -0.362663,-0.900401 0.93342,-1.747432 1.277831,-2.662119 0.75535,-2.006065 1.957858,-4.064009 1.733419,-6.184432 -0.102333,-0.966833 -0.5848,-1.983113 -1.367813,-2.56044 -1.68203,-1.191313 -4.366912,-1.323763 -7.531636,-0.525881 -3.164723,0.797885 -5.342193,2.137743 -6.247739,3.90434 z"154 id="path3832"155 inkscape:connector-curvature="0"156 sodipodi:nodetypes="csssssscssscccssscssssssccc" />157 <path158 style="fill:none;stroke:#000000;stroke-width:2;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"159 d="m 71.836704,50.617573 c 0,0 -24.55635,5.277975 -35.918352,8.551988 C 27.8621,61.491007 12.143824,67.37947 12.143824,67.37947"160 id="path3847"161 inkscape:connector-curvature="0"162 transform="translate(29.820801,20.186869)"163 sodipodi:nodetypes="csc" />164 </g>165</svg>
added:docs/_static/pycharm-runconfig.pngbinary

A binary file, added.

modified:docs/_templates/sidebarintro.html+4 added-4 removed
modified:docs/deploying/fastcgi.rst+4 added-4 removed
142 unmodified lines
143 ))144 )145146 alias.url = (147 "/static/" => "/path/to/your/static"147 "/static/" => "/path/to/your/static/"148 )149150 url.rewrite-once = (151 "^(/static($|/.*))$" => "$1",
6 unmodified lines
158:class:`~werkzeug.contrib.fixers.LighttpdCGIRootFix` middleware.159160Make sure to apply it only if you are mounting the application the URL161root. Also, see the Lighty docs for more information on `FastCGI and Python162<http://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModFastCGI>`_ (note that162<https://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModFastCGI>`_ (note that163explicitly passing a socket to run() is no longer necessary).164165Configuring nginx166-----------------
66 unmodified lines
233- The code depending on environment variables that are not set by the234 web server.235- Different python interpreters being used.236237.. _nginx: http://nginx.org/238.. _lighttpd: http://www.lighttpd.net/237.. _nginx: https://nginx.org/238.. _lighttpd: https://www.lighttpd.net/239.. _cherokee: http://cherokee-project.com/240.. _flup: https://pypi.python.org/pypi/flup
modified:docs/deploying/index.rst+4 added-4 removed
17 unmodified lines
18--------------1920- `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/>`_282829Self-hosted options30-------------------3132.. toctree::33 :maxdepth: 23435 mod_wsgi35 wsgi-standalone36 uwsgi37 mod_wsgi38 fastcgi39 cgi
modified:docs/deploying/mod_wsgi.rst+27 added-7 removed
11 unmodified lines
12 '__main__':`` block or moved to a separate file. Just make sure it's13 not called because this will always start a local WSGI server which14 we do not want if we deploy that application to mod_wsgi.1516.. _Apache: http://httpd.apache.org/16.. _Apache: https://httpd.apache.org/1718Installing `mod_wsgi`19---------------------20
92 unmodified lines
113 </VirtualHost>114115Note: There have been some changes in access control configuration for `Apache 2.4`_.116117.. _Apache 2.4: http://httpd.apache.org/docs/trunk/upgrading.html117.. _Apache 2.4: https://httpd.apache.org/docs/trunk/upgrading.html118119For more information consult the `mod_wsgi wiki`_.119Most notably, the syntax for directory permissions has changed from httpd 2.2120121.. _mod_wsgi: http://code.google.com/p/modwsgi/122.. _installation instructions: http://code.google.com/p/modwsgi/wiki/QuickInstallationGuide121.. sourcecode:: apache122123 Order allow,deny124 Allow from all125126to httpd 2.4 syntax127128.. sourcecode:: apache129130 Require all granted131132133For more information consult the `mod_wsgi documentation`_.134135.. _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/virtualenv124.. _mod_wsgi wiki: http://code.google.com/p/modwsgi/w/list138.. _mod_wsgi documentation: https://modwsgi.readthedocs.io/en/develop/index.html139140Troubleshooting141---------------142143If your application does not run, follow this guide to troubleshoot:144145**Problem:** application does not run, errorlog shows SystemExit ignored132 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
55 unmodified lines
206207 activate_this = '/path/to/env/bin/activate_this.py'208 execfile(activate_this, dict(__file__=activate_this))209210For Python 3 add the following lines to the top of your ``.wsgi`` file::211212 activate_this = '/path/to/env/bin/activate_this.py'213 with open(activate_this) as file_:214 exec(file_.read(), dict(__file__=activate_this))215216This sets up the load paths according to the settings of the virtual217environment. Keep in mind that the path has to be absolute.
modified:docs/deploying/uwsgi.rst+19 added-14 removed
27 unmodified lines
28Given a flask application in myapp.py, use the following command:2930.. sourcecode:: text3132 $ uwsgi -s /tmp/uwsgi.sock --module myapp --callable app32 $ uwsgi -s /tmp/yourapplication.sock --manage-script-name --mount /yourapplication=myapp:app3334Or, if you prefer:34The ``--manage-script-name`` will move the handling of ``SCRIPT_NAME`` to uwsgi,35since its smarter about that. It is used together with the ``--mount`` directive36which will make requests to ``/yourapplication`` be directed to ``myapp:app``.37If your application is accessible at root level, you can use a single ``/``38instead of ``/yourapplication``. ``myapp`` refers to the name of the file of39your 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__)``.4236.. sourcecode:: text43If you want to deploy your flask application inside of a virtual environment,44you need to also add ``--virtualenv /path/to/virtual/environment``. You might45also need to add ``--plugin python`` or ``--plugin python3`` depending on which46python version you use for your project.4738 $ uwsgi -s /tmp/uwsgi.sock -w myapp:app3948Configuring nginx49-----------------5043A basic flask uWSGI configuration for nginx looks like this::51A basic flask nginx configuration looks like this::5253 location = /yourapplication { rewrite ^ /yourapplication/; }54 location /yourapplication { try_files $uri @yourapplication; }55 location @yourapplication {56 include uwsgi_params;49 uwsgi_param SCRIPT_NAME /yourapplication;50 uwsgi_modifier1 30;51 uwsgi_pass unix:/tmp/uwsgi.sock;57 uwsgi_pass unix:/tmp/yourapplication.sock;58 }5960This configuration binds the application to ``/yourapplication``. If you want55to have it in the URL root it's a bit simpler because you don't have to tell56it the WSGI ``SCRIPT_NAME`` or set the uwsgi modifier to make use of it::61to have it in the URL root its a bit simpler::6263 location / { try_files $uri @yourapplication; }64 location @yourapplication {65 include uwsgi_params;61 uwsgi_pass unix:/tmp/uwsgi.sock;66 uwsgi_pass unix:/tmp/yourapplication.sock;67 }6864.. _nginx: http://nginx.org/65.. _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+24 added-7 removed
23 unmodified lines
24 gunicorn -w 4 -b 127.0.0.1:4000 myproject:app2526.. _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/2930uWSGI31--------3233`uWSGI`_ is a fast application server written in C. It is very configurable34which makes it more complicated to setup than gunicorn.3536Running `uWSGI HTTP Router`_::3738 uwsgi --http 127.0.0.1:5000 --module myproject:app3940For a more optimized setup, see `configuring uWSGI and NGINX`_.4142.. _uWSGI: http://uwsgi-docs.readthedocs.io/en/latest/43.. _uWSGI HTTP Router: http://uwsgi-docs.readthedocs.io/en/latest/HTTP.html#the-uwsgi-http-https-router44.. _configuring uWSGI and NGINX: uwsgi.html#starting-your-app-with-uwsgi4546Gevent47-------4849`Gevent`_ is a coroutine-based Python networking library that uses34`greenlet`_ to provide a high-level synchronous API on top of `libevent`_50`greenlet`_ to provide a high-level synchronous API on top of `libev`_51event loop::5253 from gevent.wsgi import WSGIServer54 from yourapplication import app
1 unmodified line
56 http_server = WSGIServer(('', 5000), app)57 http_server.serve_forever()5859.. _Gevent: http://www.gevent.org/44.. _greenlet: http://greenlet.readthedocs.org/en/latest/45.. _libevent: http://libevent.org/60.. _greenlet: https://greenlet.readthedocs.io/en/latest/61.. _libev: http://software.schmorp.de/pkg/libev.html6263Twisted Web64-----------65
46 unmodified lines
112 location / {113 proxy_pass http://127.0.0.1:8000/;114 proxy_redirect off;115100 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;116 proxy_set_header Host $host;117 proxy_set_header X-Real-IP $remote_addr;118 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;119 proxy_set_header X-Forwarded-Proto $scheme;120 }121 }122123If your httpd is not providing these headers, the most common setup invokes the
27 unmodified lines
modified:docs/patterns/apierrors.rst+1 added-1 removed
1Implementing API Exceptions2===========================34It's very common to implement RESTful APIs on top of Flask. One of the5first thing that developers run into is the realization that the builtin5first things that developers run into is the realization that the builtin6exceptions 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.89The better solution than using ``abort`` to signal errors for invalid API
54 unmodified lines
modified:docs/patterns/appdispatch.rst+7 added-7 removed
2 unmodified lines
3Application Dispatching4=======================56Application dispatching is the process of combining multiple Flask7applications on the WSGI level. You can not only combine Flask8applications into something larger but any WSGI application. This would9even allow you to run a Django and a Flask application in the same10interpreter side by side if you want. The usefulness of this depends on11how the applications work internally.7applications on the WSGI level. You can combine not only Flask8applications but any WSGI application. This would allow you to run a9Django and a Flask application in the same interpreter side by side if10you want. The usefulness of this depends on how the applications work11internally.1213The fundamental difference from the :ref:`module approach14<larger-applications>` is that in this case you are running the same or15different Flask applications that are entirely isolated from each other.
14 unmodified lines
30Note that :func:`run_simple <werkzeug.serving.run_simple>` is not intended for31use in production. Use a :ref:`full-blown WSGI server <deployment>`.3233In order to use the interactive debugger, debugging must be enabled both on34the application and the simple server, here is the "hello world" example with34the application and the simple server. Here is the "hello world" example with35debugging and :func:`run_simple <werkzeug.serving.run_simple>`::3637 from flask import Flask38 from werkzeug.serving import run_simple
16 unmodified lines
55If you have entirely separated applications and you want them to work next56to each other in the same Python interpreter process you can take57advantage of the :class:`werkzeug.wsgi.DispatcherMiddleware`. The idea58here is that each Flask application is a valid WSGI application and they59are combined by the dispatcher middleware into a larger one that59are combined by the dispatcher middleware into a larger one that is60dispatched based on prefix.6162For example you could have your main application run on ``/`` and your63backend interface on ``/backend``::
125 unmodified lines
modified:docs/patterns/appfactories.rst+5 added-4 removed
4 unmodified lines
56If you are already using packages and blueprints for your application7(:ref:`blueprints`) there are a couple of really nice ways to further improve8the experience. A common pattern is creating the application object when9the blueprint is imported. But if you move the creation of this object,10into a function, you can then create multiple instances of this and later.9the blueprint is imported. But if you move the creation of this object10into a function, you can then create multiple instances of this app later.1112So why would you want to do this?13141. Testing. You can have instances of the application with different
44 unmodified lines
5960It's preferable to create your extensions and app factories so that the61extension object does not initially get bound to the application.6263Using `Flask-SQLAlchemy <http://pythonhosted.org/Flask-SQLAlchemy/>`_,63Using `Flask-SQLAlchemy <http://flask-sqlalchemy.pocoo.org/>`_,64as an example, you should not do something along those lines::6566 def create_app(config_filename):67 app = Flask(__name__)
30 unmodified lines
98 app = create_app('/path/to/config.cfg')99100It can then be used with the :command:`flask` command::101102 flask --app=exampleapp run102 export FLASK_APP=exampleapp103 flask run104105Factory Improvements106--------------------107
9 unmodified lines
modified:docs/patterns/celery.rst+44 added-36 removed
1Celery Based Background Tasks2=============================1Celery Background Tasks2=======================34Celery is a task queue for Python with batteries included. It used to5have a Flask integration but it became unnecessary after some6restructuring of the internals of Celery with Version 3. This guide fills7in the blanks in how to properly use Celery with Flask but assumes that8you generally already read the `First Steps with Celery9<http://docs.celeryproject.org/en/master/getting-started/first-steps-with-celery.html>`_10guide in the official Celery documentation.4If your application has a long running task, such as processing some uploaded5data or sending email, you don't want to wait for it to finish during a6request. Instead, use a task queue to send the necessary data to another7process that will run the task in the background while the request returns8immediately.912Installing Celery13-----------------10Celery is a powerful task queue that can be used for simple background tasks11as well as complex multi-stage programs and schedules. This guide will show you12how to configure Celery using Flask, but assumes you've already read the13`First Steps with Celery <http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html>`_14guide in the Celery documentation.1515Celery is on the Python Package Index (PyPI), so it can be installed with16standard Python tools like :command:`pip` or :command:`easy_install`::16Install17-------1819Celery is a separate Python package. Install it from PyPI using pip::2021 $ pip install celery2220Configuring Celery21------------------23Configure24---------2526The first thing you need is a Celery instance, this is called the celery27application. It serves the same purpose as the :class:`~flask.Flask`28object in Flask, just for Celery. Since this instance is used as the
9 unmodified lines
3839 from celery import Celery4041 def make_celery(app):39 celery = Celery(app.import_name, backend=app.config['CELERY_BACKEND'],40 broker=app.config['CELERY_BROKER_URL'])42 celery = Celery(43 app.import_name,44 backend=app.config['CELERY_RESULT_BACKEND'],45 broker=app.config['CELERY_BROKER_URL']46 )47 celery.conf.update(app.config)42 TaskBase = celery.Task43 class ContextTask(TaskBase):44 abstract = True4849 class ContextTask(celery.Task):50 def __call__(self, *args, **kwargs):51 with app.app_context():47 return TaskBase.__call__(self, *args, **kwargs)52 return self.run(*args, **kwargs)5354 celery.Task = ContextTask55 return celery5657The function creates a new Celery object, configures it with the broker58from the application config, updates the rest of the Celery config from59the Flask config and then creates a subclass of the task that wraps the60task execution in an application context.6156Minimal Example62An example task63---------------6459With what we have above this is the minimal example of using Celery with60Flask::65Let's write a task that adds two numbers together and returns the result. We66configure Celery's broker and backend to use Redis, create a ``celery``67application using the factor from above, and then use it to define the task. ::6869 from flask import Flask7071 flask_app = Flask(__name__)
2 unmodified lines
74 CELERY_RESULT_BACKEND='redis://localhost:6379'75 )76 celery = make_celery(flask_app)777178 @celery.task()79 def add_together(a, b):80 return a + b8176This task can now be called in the background:82This task can now be called in the background::8378>>> result = add_together.delay(23, 42)79>>> result.wait()806584 result = add_together.delay(23, 42)85 result.wait() # 658682Running the Celery Worker83-------------------------87Run a worker88------------8985Now if you jumped in and already executed the above code you will be86disappointed to learn that your ``.wait()`` will never actually return.87That's because you also need to run celery. You can do that by running88celery as a worker::90If you jumped in and already executed the above code you will be91disappointed to learn that ``.wait()`` will never actually return.92That's because you also need to run a Celery worker to receive and execute the93task. ::9495 $ celery -A your_application.celery worker9697The ``your_application`` string has to point to your application's package93or module that creates the `celery` object.98or module that creates the ``celery`` object.99100Now that the worker is running, ``wait`` will return the result once the task101is finished.
modified:docs/patterns/deferredcallbacks.rst+25 added-53 removed
1 unmodified line
23Deferred Request Callbacks4==========================56One of the design principles of Flask is that response objects are created7and passed down a chain of potential callbacks that can modify them or8replace them. When the request handling starts, there is no response9object yet. It is created as necessary either by a view function or by10some other component in the system.6One of the design principles of Flask is that response objects are created and7passed down a chain of potential callbacks that can modify them or replace8them. When the request handling starts, there is no response object yet. It is9created as necessary either by a view function or by some other component in10the system.1112But what happens if you want to modify the response at a point where the13response does not exist yet? A common example for that would be a14before-request function that wants to set a cookie on the response object.12What happens if you want to modify the response at a point where the response13does not exist yet? A common example for that would be a14:meth:`~flask.Flask.before_request` callback that wants to set a cookie on the15response object.1616One way is to avoid the situation. Very often that is possible. For17instance you can try to move that logic into an after-request callback18instead. Sometimes however moving that code there is just not a very19pleasant experience or makes code look very awkward.17One way is to avoid the situation. Very often that is possible. For instance18you can try to move that logic into a :meth:`~flask.Flask.after_request`19callback instead. However, sometimes moving code there makes it more20more complicated or awkward to reason about.2121As an alternative possibility you can attach a bunch of callback functions22to the :data:`~flask.g` object and call them at the end of the request.23This way you can defer code execution from anywhere in the application.22As an alternative, you can use :func:`~flask.after_this_request` to register23callbacks that will execute after only the current request. This way you can24defer code execution from anywhere in the application, based on the current25request.2627At any time during a request, we can register a function to be called at the28end of the request. For example you can remember the current language of the29user in a cookie in a :meth:`~flask.Flask.before_request` callback::3026The Decorator27-------------31 from flask import request, after_this_request3229The following decorator is the key. It registers a function on a list on30the :data:`~flask.g` object::3132 from flask import g3334 def after_this_request(f):35 if not hasattr(g, 'after_request_callbacks'):36 g.after_request_callbacks = []37 g.after_request_callbacks.append(f)38 return f394041Calling the Deferred42--------------------4344Now you can use the `after_this_request` decorator to mark a function to45be called at the end of the request. But we still need to call them. For46this the following function needs to be registered as47:meth:`~flask.Flask.after_request` callback::4849 @app.after_request50 def call_after_request_callbacks(response):51 for callback in getattr(g, 'after_request_callbacks', ()):52 callback(response)53 return response545556A Practical Example57-------------------5859Now we can easily at any point in time register a function to be called at60the end of this particular request. For example you can remember the61current language of the user in a cookie in the before-request function::6263 from flask import request6433 @app.before_request34 def detect_user_language():35 language = request.cookies.get('user_lang')3637 if language is None:38 language = guess_language_from_request()3940 # when the response exists, set a cookie with the language41 @after_this_request42 def remember_language(response):43 response.set_cookie('user_lang', language)4445 g.language = language
modified:docs/patterns/distribute.rst+56 added-45 removed
1.. _distribute-deployment:23Deploying with Distribute3Deploying with Setuptools4=========================56`distribute`_, formerly setuptools, is an extension library that is7commonly used to (like the name says) distribute Python libraries and8extensions. It extends distutils, a basic module installation system9shipped with Python to also support various more complex constructs that10make larger applications easier to distribute:6`Setuptools`_, is an extension library that is commonly used to7distribute Python libraries and extensions. It extends distutils, a basic8module installation system shipped with Python to also support various more9complex constructs that make larger applications easier to distribute:1011- **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.2126Flask itself, and all the libraries you can find on the cheeseshop27are distributed with either distribute, the older setuptools or distutils.22If you have Python 2 (>=2.7.9) or Python 3 (>=3.4) installed from python.org,23you will already have pip and setuptools on your system. Otherwise, you24will need to install them yourself.2526Flask itself, and all the libraries you can find on PyPI are distributed with27either setuptools or distutils.2829In 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 is32not supported by `distribute`_ so we will not bother with it. If you have33not 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 into32a package, head over to the :ref:`larger-applications` pattern to see33how this can be done.3436A working deployment with distribute is the first step into more complex35A working deployment with setuptools is the first step into more complex36and more automated deployment scenarios. If you want to fully automate37the process, also read the :ref:`fabric-deployment` chapter.3839Basic Setup Script40------------------4143Because you have Flask running, you either have setuptools or distribute44available on your system anyways. If you do not, fear not, there is a45script to install it for you: `distribute_setup.py`_. Just download and46run with your Python interpreter.42Because you have Flask installed, you have setuptools available on your system.43Flask already depends upon setuptools.4445Standard disclaimer applies: :ref:`you better use a virtualenv46<virtualenv>`.4748Your setup code always goes into a file named :file:`setup.py` next to your49application. The name of the file is only convention, but because50everybody will look for a file with that name, you better not change it.5155Yes, even if you are using `distribute`, you are importing from a package56called `setuptools`. `distribute` is fully backwards compatible with57`setuptools`, so it also uses the same import name.5852A basic :file:`setup.py` file for a Flask application looks like this::5354 from setuptools import setup55
7 unmodified lines
63 install_requires=['Flask']64 )6566Please keep in mind that you have to list subpackages explicitly. If you74want distribute to lookup the packages for you automatically, you can use75the `find_packages` function::67want setuptools to lookup the packages for you automatically, you can use68the ``find_packages`` function::6970 from setuptools import setup, find_packages7172 setup(73 ...74 packages=find_packages()75 )7684Most 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` file77Most 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` file80and install all the entries that match as package data. We will use this81to 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 to83force or prevent zip Archive creation. In general you probably don't want84your packages to be installed as zip files because some tools do not85support them and they make debugging a lot harder.868788Tagging Builds89--------------9091It is useful to distinguish between release and development builds. Add a92:file:`setup.cfg` file to configure these options.9394 [egg_info]95 tag_build = .dev96 tag_date = 19798 [aliases]99 release = egg_info -RDb ''100101Running ``python setup.py sdist`` will create a development package102with ".dev" and the current date appended: ``flaskr-1.0.dev20160314.tar.gz``.103Running ``python setup.py release sdist`` will create a release package104with only the version: ``flaskr-1.0.tar.gz``.105106107.. _distributing-resources:108109Distributing Resources110----------------------111112If you try to install the package you just created, you will notice that113folders like :file:`static` or :file:`templates` are not installed for you. The102reason for this is that distribute does not know which files to add for114reason for this is that setuptools does not know which files to add for115you. 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 to117your tarball::118
1 unmodified line
120 recursive-include yourapplication/static *121122Don't forget that even if you enlist them in your :file:`MANIFEST.in` file, they123won't be installed for you unless you set the `include_package_data`112parameter of the `setup` function to ``True``!124parameter of the ``setup`` function to ``True``!125126127Declaring Dependencies128----------------------129118Dependencies are declared in the `install_requires` parameter as list.130Dependencies are declared in the ``install_requires`` parameter as a list.131Each item in that list is the name of a package that should be pulled from132PyPI on installation. By default it will always use the most recent133version, but you can also provide minimum and maximum version134requirements. Here some examples::
3 unmodified lines
138 'SQLAlchemy>=0.6',139 'BrokenPackage>=0.7,<=1.0'140 ]141130I mentioned earlier that dependencies are pulled from PyPI. What if you142As mentioned earlier, dependencies are pulled from PyPI. What if you143want to depend on a package that cannot be found on PyPI and won't be144because it is an internal package you don't want to share with anyone?133Just still do as if there was a PyPI entry for it and provide a list of134alternative locations where distribute should look for tarballs::145Just do it as if there was a PyPI entry and provide a list of146alternative locations where setuptools should look for tarballs::147148 dependency_links=['http://example.com/yourfiles']149150Make sure that page has a directory listing and the links on the page are151pointing to the actual tarballs with their correct filenames as this is140how distribute will find the files. If you have an internal company141server that contains the packages, provide the URL to that server there.152how setuptools will find the files. If you have an internal company153server that contains the packages, provide the URL to that server.154155156Installing / Developing157-----------------------158159To 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 your161application into the virtualenv's site-packages folder and also download162and install all dependencies::163164 $ python setup.py install165166If you are developing on the package and also want the requirements to be155installed, you can use the `develop` command instead::167installed, you can use the ``develop`` command instead::168169 $ python setup.py develop170171This has the advantage of just installing a link to the site-packages172folder instead of copying the data over. You can then continue to work on161the code without having to run `install` again after each change.173the code without having to run ``install`` again after each change.174175164.. _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/setuptools
modified:docs/patterns/errorpages.rst+35 added-19 removed
45 unmodified lines
4647Error Handlers48--------------4950An error handler is a function, just like a view function, but it is51called when an error happens and is passed that error. The error is most52likely a :exc:`~werkzeug.exceptions.HTTPException`, but in one case it53can be a different error: a handler for internal server errors will be54passed other exception instances as well if they are uncaught.50An error handler is a function that returns a response when a type of error is51raised, similar to how a view is a function that returns a response when a52request URL is matched. It is passed the instance of the error being handled,53which is most likely a :exc:`~werkzeug.exceptions.HTTPException`. An error54handler for "500 Internal Server Error" will be passed uncaught exceptions in55addition to explicit 500 errors.5657An error handler is registered with the :meth:`~flask.Flask.errorhandler`57decorator and the error code of the exception. Keep in mind that Flask58will *not* set the error code for you, so make sure to also provide the59HTTP status code when returning a response.58decorator or the :meth:`~flask.Flask.register_error_handler` method. A handler59can be registered for a status code, like 404, or for an exception class.6061Please note that if you add an error handler for "500 Internal Server62Error", Flask will not trigger it if it's running in Debug mode.61The status code of the response will not be set to the handler's code. Make62sure to provide the appropriate HTTP status code when returning a response from63a handler.6464Here an example implementation for a "404 Page Not Found" exception::65A handler for "500 Internal Server Error" will not be used when running in66debug mode. Instead, the interactive debugger will be shown.6768Here is an example implementation for a "404 Page Not Found" exception::6970 from flask import render_template7172 @app.errorhandler(404)73 def page_not_found(e):74 # note that we set the 404 status explicitly75 return render_template('404.html'), 4047677When using the :ref:`application factory pattern <app-factories>`::7879 from flask import Flask, render_template8081 def page_not_found(e):82 return render_template('404.html'), 4048384 def create_app(config_filename):85 app = Flask(__name__)86 app.register_error_handler(404, page_not_found)87 return app8889An example template might be this:9091.. sourcecode:: html+jinja9276 {% extends "layout.html" %}77 {% block title %}Page Not Found{% endblock %}78 {% block body %}79 <h1>Page Not Found</h1>80 <p>What you were looking for is just not there.81 <p><a href="{{ url_for('index') }}">go somewhere nice</a>82 {% endblock %}8393 {% extends "layout.html" %}94 {% block title %}Page Not Found{% endblock %}95 {% block body %}96 <h1>Page Not Found</h1>97 <p>What you were looking for is just not there.98 <p><a href="{{ url_for('index') }}">go somewhere nice</a>99 {% endblock %}
modified:docs/patterns/fabric.rst+14 added-24 removed
41 unmodified lines
42 # the servers where the commands are executed43 env.hosts = ['server1.example.com', 'server2.example.com']4445 def pack():46 # create a new source distribution as tarball46 # build the package47 local('python setup.py sdist --formats=gztar', capture=False)4849 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' % dist5368The example above is well documented and should be straightforward. Here69a 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)5671- `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)5960 # remove the uploaded package61 run('rm -r /tmp/%s' % filename)6263 # touch the .wsgi file to trigger a reload in mod_wsgi64 run('touch /var/www/yourapplication.wsgi')6566Running Fabfiles67----------------6869Now how do you execute that fabfile? You use the `fab` command. To
74 unmodified lines
144145Either way, in our case here we only expect one or two servers and we can146upload them ahead of time by hand.147148149First Deployment150----------------151152Now we can do our first deployment. We have set up the servers so that
34 unmodified lines
modified:docs/patterns/favicon.rst+1 added-1 removed
47 unmodified lines
4849See also50--------5152* The `Favicon <http://en.wikipedia.org/wiki/Favicon>`_ article on52* The `Favicon <https://en.wikipedia.org/wiki/Favicon>`_ article on53 Wikipedia
modified:docs/patterns/fileuploads.rst+11 added-11 removed
19 unmodified lines
20specific upload folder and displays a file to the user. Let's look at the21bootstrapping code for our application::2223 import os24 from flask import Flask, request, redirect, url_for24 from flask import Flask, flash, request, redirect, url_for25 from werkzeug.utils import secure_filename2627 UPLOAD_FOLDER = '/path/to/the/uploads'28 ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
10 unmodified lines
39your users to be able to upload everything there if the server is directly40sending out the data to the client. That way you can make sure that users41are not able to upload HTML files that would cause XSS problems (see42:ref:`xss`). Also make sure to disallow ``.php`` files if the server43executes them, but who has PHP installed on his server, right? :)43executes them, but who has PHP installed on their server, right? :)4445Next the functions that check if an extension is valid and that uploads46the file and redirects the user to the URL for the uploaded file::4748 def allowed_file(filename):49 return '.' in filename and \50 filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS50 filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS5152 @app.route('/', methods=['GET', 'POST'])53 def upload_file():54 if request.method == 'POST':
2 unmodified lines
57 flash('No file part')58 return redirect(request.url)59 file = request.files['file']60 # if user does not select file, browser also61 # submit a empty part without filename61 # submit an empty part without filename62 if file.filename == '':63 flash('No selected file')64 return redirect(request.url)65 if file and allowed_file(file.filename):
4 unmodified lines
70 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 '''7980So what does that :func:`~werkzeug.utils.secure_filename` function actually do?
22 unmodified lines
103104 >>> secure_filename('../../../../home/username/.bashrc')105 'home_username_.bashrc'106107Now 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``. 107Now 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``.110So we write the :func:`uploaded_file` function to return the file of that name. As111of Flask 0.5 we can use a function that does that for us::112113 from flask import send_from_directory
66 unmodified lines
180`Flask-Uploads`_ that implements a full fledged upload mechanism with white and181blacklisting of extensions and more.182183.. _jQuery: https://jquery.com/184.. _Flask-Uploads: http://pythonhosted.org/Flask-Uploads/184.. _Flask-Uploads: https://pythonhosted.org/Flask-Uploads/
modified:docs/patterns/flashing.rst+4 added-2 removed
7 unmodified lines
8application. Flask provides a really simple way to give feedback to a9user with the flashing system. The flashing system basically makes it10possible to record a message at the end of a request and access it next11request and only next request. This is usually combined with a layout12template that does this.12template that does this. Note that browsers and sometimes web servers enforce13a limit on cookie sizes. This means that flashing messages that are too14large for session cookies causes message flashing to fail silently.1516Simple Flashing17---------------18
58 unmodified lines
77 <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 lines
modified:docs/patterns/index.rst+1 added
39 unmodified lines
40 deferredcallbacks41 methodoverrides42 requestchecksum43 celery44 subclassing
modified:docs/patterns/jquery.rst+1 added-1 removed
162 unmodified lines
163 we set earlier.164165If you don't get the whole picture, download the `sourcecode166for this example167<https://github.com/mitsuhiko/flask/tree/master/examples/jqueryexample>`_167<https://github.com/pallets/flask/tree/master/examples/jqueryexample>`_168from GitHub.
modified:docs/patterns/lazyloading.rst+10 added-5 removed
88 unmodified lines
8990You can further optimize this in terms of amount of keystrokes needed to91write this by having a function that calls into92:meth:`~flask.Flask.add_url_rule` by prefixing a string with the project93name and a dot, and by wrapping `view_func` in a `LazyView` as needed::93name and a dot, and by wrapping `view_func` in a `LazyView` as needed. ::9495 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)9999 url('/', 'views.index')100 url('/user/<username>', 'views.user')100 # add a single route to the index view101 url('views.index', ['/'])102103 # add two routes to a single function endpoint104 url_rules = ['/user/','/user/<username>']105 url('views.user', url_rules)106107One thing to keep in mind is that before and after request handlers have108to be in a file that is imported upfront to work properly on the first109request. The same goes for any kind of remaining decorator.
modified:docs/patterns/mongokit.rst+1 added
46 unmodified lines
47insert query to the next without any problem. MongoKit is just schemaless48too, but implements some validation to ensure data integrity.4950Here is an example document (put this also into :file:`app.py`, e.g.)::5152 from mongokit import ValidationError5354 def max_length(length):55 def validate(value):
89 unmodified lines
modified:docs/patterns/packages.rst+41 added-11 removed
6 unmodified lines
7module. That is quite simple. Imagine a small application looks like8this::910 /yourapplication11 /yourapplication.py11 yourapplication.py12 /static13 /style.css13 style.css14 /templates15 layout.html16 index.html17 login.html18 ...1920If you find yourself stuck on something, feel free21to take a look at the source code for this example.22You'll find `the full src for this example here`_.2324Simple Packages25---------------2627To convert that into a larger one, just create a new folder
4 unmodified lines
32You should then end up with something like that::3334 /yourapplication35 /yourapplication32 /__init__.py36 __init__.py37 /static34 /style.css38 style.css39 /templates40 layout.html41 index.html42 login.html
1 unmodified line
4445But how do you run your application now? The naive ``python46yourapplication/__init__.py`` will not work. Let's just say that Python47does not want modules in packages to be the startup file. But that is not44a big problem, just add a new file called :file:`runserver.py` next to the inner48a big problem, just add a new file called :file:`setup.py` next to the inner49:file:`yourapplication` folder with the following contents::5047 from yourapplication import app48 app.run(debug=True)51 from setuptools import setup5253 setup(54 name='yourapplication',55 packages=['yourapplication'],56 include_package_data=True,57 install_requires=[58 'flask',59 ],60 )6162In order to run the application you need to export an environment variable 63that tells Flask where to find the application instance:: 6465 export FLASK_APP=yourapplication6667If you are outside of the project directory make sure to provide the exact 68path to your application directory. Similarly you can turn on "debug 69mode" with this environment variable:: 7071 export FLASK_DEBUG=true 7273In order to install and run the application you need to issue the following 74commands::7576 pip install -e . 77 flask run7879What did we gain from this? Now we can restructure the application a bit80into multiple modules. The only thing you have to remember is the81following quick checklist:82
22 unmodified lines
105106You should then end up with something like that::107108 /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.html
14 unmodified lines
133 :ref:`becomingbig` section for some inspiration how to deal with that.134135136.. _working-with-modules:137.. _the full src for this example here: https://github.com/pallets/flask/tree/master/examples/patterns/largerapp138139Working with Blueprints140-----------------------141
4 unmodified lines
modified:docs/patterns/sqlalchemy.rst+6 added-6 removed
20 unmodified lines
2122You can download `Flask-SQLAlchemy`_ from `PyPI23<https://pypi.python.org/pypi/Flask-SQLAlchemy>`_.2425.. _Flask-SQLAlchemy: http://pythonhosted.org/Flask-SQLAlchemy/25.. _Flask-SQLAlchemy: http://flask-sqlalchemy.pocoo.org/262728Declarative29-----------
2 unmodified lines
32SQLAlchemy. It allows you to define tables and models in one go, similar33to how Django works. In addition to the following text I recommend the34official documentation on the `declarative`_ extension.3536Here the example :file:`database.py` module for your application::36Here's the example :file:`database.py` module for your application::3738 from sqlalchemy import create_engine39 from sqlalchemy.orm import scoped_session, sessionmaker40 from sqlalchemy.ext.declarative import declarative_base
66 unmodified lines
107[<User u'admin'>]108>>> User.query.filter(User.name == 'admin').first()109<User u'admin'>110111.. _SQLAlchemy: http://www.sqlalchemy.org/111.. _SQLAlchemy: https://www.sqlalchemy.org/112.. _declarative:113 http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/113 https://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/114115Manual Object Relational Mapping116--------------------------------117
16 unmodified lines
134 bind=engine))135 def init_db():136 metadata.create_all(bind=engine)137138As for the declarative approach you need to close the session after138As in the declarative approach, you need to close the session after139each request or application context shutdown. Put this into your140application module::141142 from yourapplication.database import db_session
71 unmodified lines
214>>> engine.execute('select * from users where id = :1', [1]).first()215(1, u'admin', u'admin@localhost')216217For more information about SQLAlchemy, head over to the218`website <http://www.sqlalchemy.org/>`_.218`website <https://www.sqlalchemy.org/>`_.
modified:docs/patterns/sqlite3.rst+25 added-8 removed
1 unmodified line
23Using SQLite 3 with Flask4=========================56In Flask you can easily implement the opening of database connections on 7demand and closing them when the context dies (usually at the end of the 6In Flask you can easily implement the opening of database connections on7demand and closing them when the context dies (usually at the end of the8request).910Here is a simple example of how you can use SQLite 3 with Flask::11
58 unmodified lines
70Now in each request handling function you can access `g.db` to get the71current open database connection. To simplify working with SQLite, a72row factory function is useful. It is executed for every result returned73from the database to convert the result. For instance, in order to get74dictionaries instead of tuples, this could be inserted into ``get_db``::74dictionaries instead of tuples, this could be inserted into the ``get_db``75function we created above::7677 def make_dicts(cursor, row):78 return dict((cursor.description[idx][0], value)79 for idx, value in enumerate(row))8081 db.row_factory = make_dicts8282Or even simpler::83This 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::8485 db.row_factory = sqlite3.Row8687This 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``::8889 >>> # 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 M102103Additionally, it is a good idea to provide a query function that combines104getting the cursor, executing and fetching the results::88 105106 def query_db(query, args=(), one=False):107 cur = get_db().execute(query, args)108 rv = cur.fetchall()109 cur.close()110 return (rv[0] if rv else None) if one else rv11195This handy little function, in combination with a row factory, makes 96working with the database much more pleasant than it is by just using the 112This handy little function, in combination with a row factory, makes113working with the database much more pleasant than it is by just using the114raw cursor and connection objects.115116Here is how you can use it::117
12 unmodified lines
130To pass variable parts to the SQL statement, use a question mark in the131statement and pass in the arguments as a list. Never directly add them to132the SQL statement with string formatting because this makes it possible133to attack the application using `SQL Injections117<http://en.wikipedia.org/wiki/SQL_injection>`_.134<https://en.wikipedia.org/wiki/SQL_injection>`_.135136Initial Schemas137---------------138
16 unmodified lines
added:docs/patterns/subclassing.rst+17 added
1Subclassing Flask2=================34The :class:`~flask.Flask` class is designed for subclassing.56For example, you may want to override how request parameters are handled to preserve their order::78 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 = MyRequest1617This is the recommended approach for overriding or augmenting Flask's internal functionality.
modified:docs/patterns/viewdecorators.rst+17 added-10 removed
14 unmodified lines
15Login Required Decorator16------------------------1718So let's implement such a decorator. A decorator is a function that19returns a function. Pretty simple actually. The only thing you have to20keep in mind when implementing something like this is to update the21`__name__`, `__module__` and some other attributes of a function. This is22often forgotten, but you don't have to do that by hand, there is a23function for that that is used like a decorator (:func:`functools.wraps`).19wraps and replaces another function. Since the original function is20replaced, you need to remember to copy the original function's information21to the new function. Use :func:`functools.wraps` to handle this for you.2223This example assumes that the login page is called ``'login'`` and that26the current user is stored as `g.user` and ``None`` if there is no-one27logged in::24the current user is stored in ``g.user`` and is ``None`` if there is no-one25logged in. ::2627 from functools import wraps28 from flask import g, request, redirect, url_for29
4 unmodified lines
34 return redirect(url_for('login', next=request.url))35 return f(*args, **kwargs)36 return decorated_function3740So how would you use that decorator now? Apply it as innermost decorator41to a view function. When applying further decorators, always remember42that the :meth:`~flask.Flask.route` decorator is the outermost::38To use the decorator, apply it as innermost decorator to a view function.39When applying further decorators, always remember40that the :meth:`~flask.Flask.route` decorator is the outermost. ::4142 @app.route('/secret_page')43 @login_required44 def secret_page():45 pass4647.. 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. ::5253 <input type="hidden" value="{{ request.args.get('next', '') }}"/>545556Caching Decorator57-----------------5859Imagine you have a view function that does an expensive calculation and
113 unmodified lines
modified:docs/patterns/wtforms.rst+18 added-18 removed
1Form Validation with WTForms2============================34When you have to work with form data submitted by a browser view code4When you have to work with form data submitted by a browser view, code5quickly becomes very hard to read. There are libraries out there designed6to make this process easier to manage. One of them is `WTForms`_ which we7will handle here. If you find yourself in the situation of having many8forms, you might want to give it a try.
2 unmodified lines
11first. I recommend breaking up the application into multiple modules12(:ref:`larger-applications`) for that and adding a separate module for the13forms.1415.. admonition:: Getting most of WTForms with an Extension15.. admonition:: Getting the most out of WTForms with an Extension1617 The `Flask-WTF`_ extension expands on this pattern and adds a few18 handful little helpers that make working with forms and Flask more17 The `Flask-WTF`_ extension expands on this pattern and adds a18 few little helpers that make working with forms and Flask more19 fun. You can get it from `PyPI20 <https://pypi.python.org/pypi/Flask-WTF>`_.2122.. _Flask-WTF: http://pythonhosted.org/Flask-WTF/22.. _Flask-WTF: https://flask-wtf.readthedocs.io/en/stable/2324The Forms25---------26
4 unmodified lines
31 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()])4041In the View42-----------43
9 unmodified lines
53 flash('Thanks for registering')54 return redirect(url_for('login'))55 return render_template('register.html', form=form)5657Notice that we are implying that the view is using SQLAlchemy here58(:ref:`sqlalchemy-pattern`) but this is no requirement of course. Adapt57Notice we're implying that the view is using SQLAlchemy here58(:ref:`sqlalchemy-pattern`), but that's not a requirement, of course. Adapt59the code as necessary.6061Things to remember:62631. create the form from the request :attr:`~flask.request.form` value if64 the data is submitted via the HTTP ``POST`` method and65 :attr:`~flask.request.args` if the data is submitted as ``GET``.662. to validate the data, call the :func:`~wtforms.form.Form.validate`67 method which will return ``True`` if the data validates, ``False``67 method, which will return ``True`` if the data validates, ``False``68 otherwise.693. to access individual values from the form, access `form.<NAME>.data`.7071Forms in Templates72------------------7374Now to the template side. When you pass the form to the templates you can74Now to the template side. When you pass the form to the templates, you can75easily render them there. Look at the following example template to see76how easy this is. WTForms does half the form generation for us already.77To make it even nicer, we can write a macro that renders a field with78label and a list of errors if there are any.
15 unmodified lines
94 </dd>95 {% endmacro %}9697This macro accepts a couple of keyword arguments that are forwarded to98WTForm's field function that renders the field for us. The keyword99arguments will be inserted as HTML attributes. So for example you can98WTForm's field function, which renders the field for us. The keyword99arguments will be inserted as HTML attributes. So, for example, you can100call ``render_field(form.username, class='username')`` to add a class to101the input element. Note that WTForms returns standard Python unicode102strings, so we have to tell Jinja2 that this data is already HTML escaped102strings, so we have to tell Jinja2 that this data is already HTML-escaped103with the ``|safe`` filter.104105Here the :file:`register.html` template for the function we used above which105Here is the :file:`register.html` template for the function we used above, which106takes advantage of the :file:`_formhelpers.html` template:107108.. sourcecode:: html+jinja109110 {% 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 lines
121122For more information about WTForms, head over to the `WTForms123website`_.124125.. _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:23Step 7: Adding Style3Step 8: Adding Style4====================56Now that everything else works, it's time to add some style to the7application. Just create a stylesheet called :file:`style.css` in the8:file:`static` folder we created before:8:file:`static` folder:910.. sourcecode:: css1112 body { font-family: sans-serif; background: #eee; }
19 unmodified lines
modified:docs/tutorial/dbcon.rst+16 added-16 removed
1.. _tutorial-dbcon:23Step 3: Database Connections3Step 4: Database Connections4----------------------------56We have created a function for establishing a database connection with7`connect_db`, but by itself, that's not particularly useful. Creating and8closing database connections all the time is very inefficient, so we want9to keep it around for longer. Because database connections encapsulate a10transaction, we also need to make sure that only one request at the time11uses the connection. How can we elegantly do that with Flask?6Let's continue building our code in the ``flaskr.py`` file.7(Scroll to the end of the page for more about project layout.)813This is where the application context comes into play, so let's start14there.9You currently have a function for establishing a database connection with10`connect_db`, but by itself, it is not particularly useful. Creating and11closing database connections all the time is very inefficient, so you will12need to keep it around for longer. Because database connections13encapsulate a transaction, you will need to make sure that only one14request at a time uses the connection. An elegant way to do this is by15utilizing the *application context*.1616Flask provides us with two contexts: the application context and the17request context. For the time being, all you have to know is that there17Flask provides two contexts: the *application context* and the18*request context*. For the time being, all you have to know is that there19are special variables that use these. For instance, the20:data:`~flask.request` variable is the request object associated with21the current request, whereas :data:`~flask.g` is a general purpose21variable associated with the current application context. We will go into22the details of this a bit later.22variable associated with the current application context. The tutorial23will cover some more details of this later on.2425For the time being, all you have to know is that you can store information26safely on the :data:`~flask.g` object.27
9 unmodified lines
37 if not hasattr(g, 'sqlite_db'):38 g.sqlite_db = connect_db()39 return g.sqlite_db404041So now we know how to connect, but how do we properly disconnect? For41Now you know how to connect, but how can you properly disconnect? For42that, Flask provides us with the :meth:`~flask.Flask.teardown_appcontext`43decorator. It's executed every time the application context tears down::4445 @app.teardown_appcontext
28 unmodified lines
74 into a single Python module. You don't have to, and if your app :ref:`grows75 larger <larger-applications>`, it's a good idea not to.7677.. _example source:78 https://github.com/mitsuhiko/flask/tree/master/examples/flaskr/78 https://github.com/pallets/flask/tree/master/examples/flaskr/
modified:docs/tutorial/dbinit.rst+30 added-22 removed
1.. _tutorial-dbinit:23Step 4: Creating The Database3Step 5: Creating The Database4=============================56As outlined earlier, Flaskr is a database powered application, and more7precisely, it is an application powered by a relational database system. Such8systems need a schema that tells them how to store that information.9Before starting the server for the first time, it's important to create10that schema.1112Such a schema can be created by piping the ``schema.sql`` file into the13`sqlite3` command as follows::12Such a schema could be created by piping the ``schema.sql`` file into the13``sqlite3`` command as follows::1415 sqlite3 /tmp/flaskr.db < schema.sql1617The downside of this is that it requires the ``sqlite3`` command to be18installed, which is not necessarily the case on every system. This also19requires that we provide the path to the database, which can introduce20errors. It's a good idea to add a function that initializes the database21for you to the application.17However, the downside of this is that it requires the ``sqlite3`` command18to be installed, which is not necessarily the case on every system. This19also requires that you provide the path to the database, which can introduce20errors.2123To do this, we can create a function and hook it into the :command:`flask`24command that initializes the database. Let me show you the code first. Just25add this function below the `connect_db` function in :file:`flaskr.py`::22Instead of the ``sqlite3`` command above, it's a good idea to add a function23to our application that initializes the database for you. To do this, you24can create a function and hook it into a :command:`flask` command that25initializes the database.2627Take a look at the code segment below. A good place to add this function,28and command, is just below the ``connect_db`` function in :file:`flaskr.py`::2930 def init_db():31 db = get_db()3233 with app.open_resource('schema.sql', mode='r') as f:34 db.cursor().executescript(f.read())3536 db.commit()373839 @app.cli.command('initdb')40 def initdb_command():41 """Initializes the database."""4243 init_db()37 print 'Initialized the database.'44 print('Initialized the database.')4546The ``app.cli.command()`` decorator registers a new command with the47:command:`flask` script. When the command executes, Flask will automatically41create a application context for us bound to the right application.42Within the function, we can then access :attr:`flask.g` and other things as43we would expect. When the script ends, the application context tears down48create an application context which is bound to the right application.49Within the function, you can then access :attr:`flask.g` and other things as50you might expect. When the script ends, the application context tears down51and the database connection is released.5246We want to keep an actual functions around that initializes the database,53You will want to keep an actual function around that initializes the database,54though, so that we can easily create databases in unit tests later on. (For55more information see :ref:`testing`.)5657The :func:`~flask.Flask.open_resource` method of the application object58is a convenient helper function that will open a resource that the59application provides. This function opens a file from the resource53location (your ``flaskr`` folder) and allows you to read from it. We are54using this here to execute a script on the database connection.60location (the :file:`flaskr/flaskr` folder) and allows you to read from it.61It is used in this example to execute a script on the database connection.6256The connection object provided by SQLite can give us a cursor object.57On that cursor, there is a method to execute a complete script. Finally, we63The connection object provided by SQLite can give you a cursor object.64On that cursor, there is a method to execute a complete script. Finally, you65only have to commit the changes. SQLite3 and other transactional66databases will not commit unless you explicitly tell it to.6768Now, in a terminal, from the application root directory :file:`flaskr/` it is61Now, it is possible to create a database with the :command:`flask` script::69possible to create a database with the :command:`flask` script::7063 flask --app=flaskr initdb71 flask initdb72 Initialized the database.7374.. admonition:: Troubleshooting75
5 unmodified lines
modified:docs/tutorial/folders.rst+20 added-12 removed
1 unmodified line
23Step 0: Creating The Folders4============================56Before we get started, let's create the folders needed for this7application::6It is recommended to install your Flask application within a virtualenv. Please7read the :ref:`installation` section to set up your environment.89Now that you have installed Flask, you will need to create the folders required10for this tutorial. Your directory structure will look like this::1112 /flaskr13 /flaskr10 /static11 /templates14 /static15 /templates1613The ``flaskr`` folder is not a Python package, but just something where we14drop our files. Later on, we will put our database schema as well as main15module into this folder. It is done in the following way. The files inside16the :file:`static` folder are available to users of the application via HTTP.17This is the place where CSS and Javascript files go. Inside the18:file:`templates` folder, Flask will look for `Jinja2`_ templates. The19templates you create later on in the tutorial will go in this directory.17The application will be installed and run as Python package. This is the18recommended way to install and run Flask applications. You will see exactly19how to run ``flaskr`` later on in this tutorial.2021Continue with :ref:`tutorial-schema`.21For now go ahead and create the applications directory structure. In the next22few steps you will be creating the database schema as well as the main module.2324As a quick side note, the files inside of the :file:`static` folder are25available to users of the application via HTTP. This is the place where CSS and26JavaScript files go. Inside the :file:`templates` folder, Flask will look for27`Jinja2`_ templates. You will see examples of this later on.2829For now you should continue with :ref:`tutorial-schema`.3031.. _Jinja2: http://jinja.pocoo.org/
modified:docs/tutorial/index.rst+10 added-9 removed
1 unmodified line
23Tutorial4========56You want to develop an application with Python and Flask? Here you have7the chance to learn by example. In this tutorial, we will create a simple8microblogging application. It only supports one user that can create9text-only entries and there are no feeds or comments, but it still10features everything you need to get started. We will use Flask and SQLite11as a database (which comes out of the box with Python) so there is nothing12else you need.6Learn by example to develop an application with Python and Flask.78In this tutorial, we will create a simple blogging application. It only9supports one user, only allows text entries, and has no feeds or comments.1011While very simple, this example still features everything you need to get12started. In addition to Flask, we will use SQLite for the database, which is13built-in to Python, so there is nothing else you need.1415If you want the full source code in advance or for comparison, check out16the `example source`_.1717.. _example source:18 https://github.com/mitsuhiko/flask/tree/master/examples/flaskr/18.. _example source: https://github.com/pallets/flask/tree/master/examples/flaskr/1920.. toctree::21 :maxdepth: 22223 introduction24 folders25 schema26 setup27 packaging28 dbcon29 dbinit30 views31 templates
2 unmodified lines
modified:docs/tutorial/introduction.rst+7 added-6 removed
1 unmodified line
23Introducing Flaskr4==================56We will call our blogging application flaskr, but feel free to choose your own7less Web-2.0-ish name ;) Essentially, we want it to do the following things:6This tutorial will demonstrate a blogging application named Flaskr, but feel7free to choose your own less Web-2.0-ish name ;) Essentially, it will do the8following things:9101. Let the user sign in and out with credentials specified in the11 configuration. Only one user is supported.122. When the user is logged in, they can add new entries to the page
1 unmodified line
14 is not sanitized because we trust the user here.153. 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.1717We will be using SQLite3 directly for this application because it's good18enough for an application of this size. For larger applications, however,18SQLite3 will be used directly for this application because it's good enough19for an application of this size. For larger applications, however,20it makes a lot of sense to use `SQLAlchemy`_, as it handles database21connections in a more intelligent way, allowing you to target different22relational databases at once and more. You might also want to consider23one of the popular NoSQL databases if your data is more suited for those.2424Here a screenshot of the final application:25Here is a screenshot of the final application:2627.. image:: ../_static/flaskr.png28 :align: center29 :class: screenshot30 :alt: screenshot of the final application3132Continue with :ref:`tutorial-folders`.3333.. _SQLAlchemy: http://www.sqlalchemy.org/34.. _SQLAlchemy: https://www.sqlalchemy.org/
added:docs/tutorial/packaging.rst+106 added
1.. _tutorial-packaging:23Step 3: Installing flaskr as a Package4======================================56Flask is now shipped with built-in support for `Click`_. Click provides7Flask with enhanced and extensible command line utilities. Later in this8tutorial you will see exactly how to extend the ``flask`` command line9interface (CLI).1011A useful pattern to manage a Flask application is to install your app12following the `Python Packaging Guide`_. Presently this involves13creating two new files; :file:`setup.py` and :file:`MANIFEST.in` in the14projects root directory. You also need to add an :file:`__init__.py`15file to make the :file:`flaskr/flaskr` directory a package. After these16changes, your code structure should be::1718 /flaskr19 /flaskr20 __init__.py21 /static22 /templates23 flaskr.py24 schema.sql25 setup.py26 MANIFEST.in2728Create the ``setup.py`` file for ``flaskr`` with the following content::2930 from setuptools import setup3132 setup(33 name='flaskr',34 packages=['flaskr'],35 include_package_data=True,36 install_requires=[37 'flask',38 ],39 )4041When using setuptools, it is also necessary to specify any special files42that should be included in your package (in the :file:`MANIFEST.in`).43In this case, the static and templates directories need to be included,44as well as the schema.4546Create the :file:`MANIFEST.in` and add the following lines::4748 graft flaskr/templates49 graft flaskr/static50 include flaskr/schema.sql5152Next, to simplify locating the application, create the file,53:file:`flaskr/__init__.py` containing only the following import statement::5455 from .flaskr import app5657This import statement brings the application instance into the top-level58of the application package. When it is time to run the application, the59Flask development server needs the location of the app instance. This60import statement simplifies the location process. Without the above61import statement, the export statement a few steps below would need to be62``export FLASK_APP=flaskr.flaskr``.6364At this point you should be able to install the application. As usual, it65is recommended to install your Flask application within a `virtualenv`_.66With that said, from the ``flaskr/`` directory, go ahead and install the67application with::6869 pip install --editable .7071The above installation command assumes that it is run within the projects72root directory, ``flaskr/``. The ``editable`` flag allows editing73source code without having to reinstall the Flask app each time you make74changes. The flaskr app is now installed in your virtualenv (see output75of ``pip freeze``).7677With that out of the way, you should be able to start up the application.78Do this on Mac or Linux with the following commands in ``flaskr/``::7980 export FLASK_APP=flaskr81 export FLASK_DEBUG=true82 flask run8384(In case you are on Windows you need to use ``set`` instead of ``export``).85The :envvar:`FLASK_DEBUG` flag enables or disables the interactive debugger.86*Never leave debug mode activated in a production system*, because it will87allow users to execute code on the server!8889You will see a message telling you that server has started along with90the address at which you can access it in a browser.9192When you head over to the server in your browser, you will get a 404 error93because we don't have any views yet. That will be addressed a little later,94but first, you should get the database working.9596.. admonition:: Externally Visible Server9798 Want your server to be publicly available? Check out the99 :ref:`externally visible server <public-server>` section for more100 information.101102Continue with :ref:`tutorial-dbcon`.103104.. _Click: http://click.pocoo.org105.. _Python Packaging Guide: https://packaging.python.org106.. _virtualenv: https://virtualenv.pypa.io
modified:docs/tutorial/schema.rst+5 added-5 removed
1 unmodified line
23Step 1: Database Schema4=======================56First, we want to create the database schema. Only a single table is needed7for this application and we only want to support SQLite, so creating the8database schema is quite easy. Just put the following contents into a file9named `schema.sql` in the just created `flaskr` folder:6In this step, you will create the database schema. Only a single table is7needed for this application and it will only support SQLite. All you need to do8is put the following contents into a file named :file:`schema.sql` in the9:file:`flaskr/flaskr` folder:1011.. sourcecode:: sql1213 drop table if exists entries;
2 unmodified lines
16 title text not null,17 'text' text not null18 );1920This schema consists of a single table called ``entries``. Each row in20This schema consists of a single table called ``entries``. Each row in21this table has an ``id``, a ``title``, and a ``text``. The ``id`` is an22automatically incrementing integer and a primary key, the other two are23strings that must not be null.24
1 unmodified line
modified:docs/tutorial/setup.rst+41 added-55 removed
1 unmodified line
23Step 2: Application Setup Code4==============================56Now that we have the schema in place, we can create the application module.7Let's call it ``flaskr.py``. We will place this file inside the ``flaskr``8folder. We will begin by adding the imports we need and by adding the config9section. For small applications, it is possible to drop the configuration10directly into the module, and this is what we will be doing here. However,11a cleaner solution would be to create a separate ``.ini`` or ``.py`` file,12load that, and import the values from there.6Next, we will create the application module, :file:`flaskr.py`. Just like the7:file:`schema.sql` file you created in the previous step, this file should be8placed inside of the :file:`flaskr/flaskr` folder.914First, we add the imports in :file:`flaskr.py`::10For this tutorial, all the Python code we use will be put into this file11(except for one line in ``__init__.py``, and any testing or optional files you12decide to create).1316 # all the imports14The first several lines of code in the application module are the needed import15statements. After that there will be a few lines of configuration code.1617For small applications like ``flaskr``, it is possible to drop the configuration18directly into the module. However, a cleaner solution is to create a separate19``.py`` file, load that, and import the values from there.2021Here are the import statements (in :file:`flaskr.py`)::2223 import os24 import sqlite319 from flask import Flask, request, session, g, redirect, url_for, abort, \20 render_template, flash2522Next, we can create our actual application and initialize it with the23config from the same file in :file:`flaskr.py`::26 from flask import (Flask, request, session, g, redirect, url_for, abort,27 render_template, flash)2825 # create our little application :)26 app = Flask(__name__)27 app.config.from_object(__name__)29The next couple lines will create the actual application instance and30initialize it with the config from the same file in :file:`flaskr.py`::3132 app = Flask(__name__) # create the application instance :)33 app.config.from_object(__name__) # load config from this file , flaskr.py3435 # Load default config and override config from an environment variable36 app.config.update(dict(37 DATABASE=os.path.join(app.root_path, 'flaskr.db'),38 SECRET_KEY='development key',
1 unmodified line
40 PASSWORD='default'41 ))42 app.config.from_envvar('FLASKR_SETTINGS', silent=True)4338The :class:`~flask.Config` object works similarly to a dictionary so we39can update it with new values.44In the above code, the :class:`~flask.Config` object works similarly to a45dictionary, so it can be updated with new values.4647.. admonition:: Database Path4849 Operating systems know the concept of a current working directory for
10 unmodified lines
60 :ref:`instance-folders` instead.6162Usually, it is a good idea to load a separate, environment-specific63configuration file. Flask allows you to import multiple configurations and it58will use the setting defined in the last import. This enables robust59configuration setups. :meth:`~flask.Config.from_envvar` can help achieve this.64will use the setting defined in the last import. This enables robust65configuration setups. :meth:`~flask.Config.from_envvar` can help achieve66this. ::6761.. code-block:: python6268 app.config.from_envvar('FLASKR_SETTINGS', silent=True)6965Simply define the environment variable :envvar:`FLASKR_SETTINGS` that points to66a config file to be loaded. The silent switch just tells Flask to not complain67if no such environment key is set.70If you want to do this (not required for this tutorial) simply define the71environment variable :envvar:`FLASKR_SETTINGS` that points to a config file72to be loaded. The silent switch just tells Flask to not complain if no such73environment key is set.7475In addition to that, you can use the :meth:`~flask.Config.from_object`76method on the config object and provide it with an import name of a77module. Flask will then initialize the variable from that module. Note
1 unmodified line
7980The ``SECRET_KEY`` is needed to keep the client-side sessions secure.81Choose that key wisely and as hard to guess and complex as possible.8277We will also add a method that allows for easy connections to the78specified database. This can be used to open a connection on request and79also from the interactive Python shell or a script. This will come in80handy later. We create a simple database connection through SQLite and81then tell it to use the :class:`sqlite3.Row` object to represent rows.82This allows us to treat the rows as if they were dictionaries instead of83tuples.83Lastly, add a method that allows for easy connections to the specified84database. ::8585::8686 def connect_db():87 """Connects to the specific database."""8889 rv = sqlite3.connect(app.config['DATABASE'])90 rv.row_factory = sqlite3.Row91 return rv9293With that out of the way, you should be able to start up the application94without problems. Do this with the following command::93This can be used to open a connection on request and also from the94interactive Python shell or a script. This will come in handy later.95You can create a simple database connection through SQLite and then tell96it to use the :class:`sqlite3.Row` object to represent rows. This allows97the rows to be treated as if they were dictionaries instead of tuples.9896 flask --app=flaskr --debug run99In the next section you will see how to run the application.10098The :option:`--debug` flag enables or disables the interactive debugger. *Never99leave debug mode activated in a production system*, because it will allow100users to execute code on the server!101102You will see a message telling you that server has started along with103the address at which you can access it.104105When you head over to the server in your browser, you will get a 404 error106because we don't have any views yet. We will focus on that a little later,107but first, we should get the database working.108109.. admonition:: Externally Visible Server110111 Want your server to be publicly available? Check out the112 :ref:`externally visible server <public-server>` section for more113 information.114115Continue with :ref:`tutorial-dbcon`.101Continue with :ref:`tutorial-packaging`.
modified:docs/tutorial/templates.rst+12 added-10 removed
1.. _tutorial-templates:23Step 6: The Templates3Step 7: The Templates4=====================56Now we should start working on the templates. If we were to request the URLs7now, we would only get an exception that Flask cannot find the templates. The8templates are using `Jinja2`_ syntax and have autoescaping enabled by6Now it is time to start working on the templates. As you may have7noticed, if you make requests with the app running, you will get8an exception that Flask cannot find the templates. The templates9are using `Jinja2`_ syntax and have autoescaping enabled by10default. This means that unless you mark a value in the code with11:class:`~flask.Markup` or with the ``|safe`` filter in the template,12Jinja2 will ensure that special characters such as ``<`` or ``>`` are13escaped with their XML equivalents.1415We are also using template inheritance which makes it possible to reuse16the layout of the website in all pages.1717Put the following templates into the :file:`templates` folder:18Create the follwing three HTML files and place them in the19:file:`templates` folder:2021.. _Jinja2: http://jinja.pocoo.org/docs/templates2223layout.html
34 unmodified lines
58-----------------5960This template extends the :file:`layout.html` template from above to display the61messages. Note that the ``for`` loop iterates over the messages we passed60in with the :func:`~flask.render_template` function. We also tell the61form to submit to your `add_entry` function and use ``POST`` as HTTP62method:62in with the :func:`~flask.render_template` function. Notice that the form is63configured to submit to the `add_entry` view function and use ``POST`` as64HTTP method:6566.. sourcecode:: html+jinja6768 {% extends "layout.html" %}
10 unmodified lines
79 </form>80 {% endif %}81 <ul class=entries>82 {% for entry in entries %}81 <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}83 <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}</li>84 {% else %}83 <li><em>Unbelievable. No entries here so far</em>85 <li><em>Unbelievable. No entries here so far</em></li>86 {% endfor %}87 </ul>88 {% endblock %}89
24 unmodified lines
modified:docs/tutorial/testing.rst+86 added
6 unmodified lines
7expected, it's probably not a bad idea to add automated tests to simplify8modifications in the future. The application above is used as a basic9example of how to perform unit testing in the :ref:`testing` section of the10documentation. Go there to see how easy it is to test Flask applications.1112Adding tests to flaskr13----------------------1415Assuming you have seen the :ref:`testing` section and have either written16your own tests for ``flaskr`` or have followed along with the examples17provided, you might be wondering about ways to organize the project.1819One possible and recommended project structure is::2021 flaskr/22 flaskr/23 __init__.py24 static/25 templates/26 tests/27 test_flaskr.py28 setup.py29 MANIFEST.in3031For now go ahead a create the :file:`tests/` directory as well as the 32:file:`test_flaskr.py` file.3334Running the tests35-----------------3637At this point you can run the tests. Here ``pytest`` will be used. 3839.. 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::4243 pip install -e .44 pip install pytest 4546Run and watch the tests pass, within the top-level :file:`flaskr/` 47directory as::4849 pytest5051Testing + setuptools52--------------------5354One way to handle testing is to integrate it with ``setuptools``. Here55that requires adding a couple of lines to the :file:`setup.py` file and56creating a new file :file:`setup.cfg`. One benefit of running the tests 57this way is that you do not have to install ``pytest``. Go ahead and 58update the :file:`setup.py` file to contain::5960 from setuptools import setup6162 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 )7677Now create :file:`setup.cfg` in the project root (alongside78:file:`setup.py`)::7980 [aliases]81 test=pytest8283Now you can run::8485 python setup.py test8687This calls on the alias created in :file:`setup.cfg` which in turn runs88``pytest`` via ``pytest-runner``, as the :file:`setup.py` script has89been called. (Recall the `setup_requires` argument in :file:`setup.py`)90Following the standard rules of test-discovery your tests will be91found, run, and hopefully pass.9293This is one possible way to run and manage testing. Here ``pytest`` is94used, but there are other options such as ``nose``. Integrating testing95with ``setuptools`` is convenient because it is not necessary to actually96download ``pytest`` or any other testing framework one might use.
modified:docs/tutorial/views.rst+32 added-12 removed
1.. _tutorial-views:23Step 5: The View Functions3Step 6: The View Functions4==========================56Now that the database connections are working, we can start writing the7view functions. We will need four of them:6Now that the database connections are working, you can start writing the7view functions. You will need four of them; Show Entries, Add New Entry,8Login and Logout. Add the following code snipets to :file:`flaskr.py`.910Show Entries11------------1213This view shows all the entries stored in the database. It listens on the14root of the application and will select title and text from the database.15The one with the highest id (the newest entry) will be on top. The rows15returned from the cursor look a bit like tuples because we are using16returned from the cursor look a bit like dictionaries because we are using17the :class:`sqlite3.Row` row factory.1818The view function will pass the entries as dictionaries to the19:file:`show_entries.html` template and return the rendered one::19The view function will pass the entries to the :file:`show_entries.html`20template and return the rendered one::2122 @app.route('/')23 def show_entries():24 db = get_db()
5 unmodified lines
30-------------3132This view lets the user add new entries if they are logged in. This only33responds to ``POST`` requests; the actual form is shown on the33`show_entries` page. If everything worked out well, we will34`show_entries` page. If everything worked out well, it will35:func:`~flask.flash` an information message to the next request and36redirect back to the `show_entries` page::3738 @app.route('/add', methods=['POST'])
6 unmodified lines
45 db.commit()46 flash('New entry was successfully posted')47 return redirect(url_for('show_entries'))4848Note that we check that the user is logged in here (the `logged_in` key is49present in the session and ``True``).49Note that this view checks that the user is logged in (that is, if the50`logged_in` key is present in the session and ``True``).5152.. admonition:: Security Note5354 Be sure to use question marks when building SQL statements, as done in the
26 unmodified lines
81 return redirect(url_for('show_entries'))82 return render_template('login.html', error=error)8384The `logout` function, on the other hand, removes that key from the session84again. We use a neat trick here: if you use the :meth:`~dict.pop` method85again. There is a neat trick here: if you use the :meth:`~dict.pop` method86of the dict and pass a second parameter to it (the default), the method87will delete the key from the dictionary if present or do nothing when that87key is not in there. This is helpful because now we don't have to check88if the user was logged in.88key is not in there. This is helpful because now it is not necessary to89check if the user was logged in.9091::9293 @app.route('/logout')
1 unmodified line
95 session.pop('logged_in', None)96 flash('You were logged out')97 return redirect(url_for('show_entries'))9899.. admonition:: Security Note100101 Passwords should never be stored in plain text in a production102 system. This tutorial uses plain text passwords for simplicity. If you103 plan to release a project based off this tutorial out into the world,104 passwords should be both `hashed and salted`_ before being stored in a105 database or file.106107 Fortunately, there are Flask extensions for the purpose of108 hashing passwords and verifying passwords against hashes, so adding109 this functionality is fairly straight forward. There are also110 many general python libraries that can be used for hashing.111112 You can find a list of recommended Flask extensions113 `here <http://flask.pocoo.org/extensions/>`_114115116Continue with :ref:`tutorial-templates`.117118.. _hashed and salted: https://blog.codinghorror.com/youre-probably-storing-passwords-incorrectly/
modified:docs/advanced_foreword.rst+4 added-18 removed
44 unmodified lines
4546Flask is no different from any other framework in that you the developer must47build with caution, watching for exploits when building to your requirements.4849The Status of Python 350----------------------49Python 3 Support in Flask50-------------------------5152Currently the Python community is in the process of improving libraries to53support the new iteration of the Python programming language. While the54situation is greatly improving there are still some issues that make it55hard for users to switch over to Python 3 just now. These problems are56partially caused by changes in the language that went unreviewed for too57long, partially also because we have not quite worked out how the lower-58level API should change to account for the Unicode differences in Python 3.52Flask, its dependencies, and most Flask extensions all support Python 3.53If you want to use Flask with Python 3 have a look at the :ref:`python3-support` page.5460We strongly recommend using Python 2.7 with activated Python 361warnings during development. If you plan on upgrading to Python 3 in the62near future we strongly recommend that you read `How to write forwards63compatible Python code64<http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/>`_.6566If you do want to dive into Python 3 already have a look at the67:ref:`python3-support` page.6855Continue to :ref:`installation` or the :ref:`quickstart`.
modified:docs/api.rst+133 added-90 removed
28 unmodified lines
29---------------------3031.. autoclass:: Request32 :members:33 :inherited-members:3434 .. attribute:: form3536 A :class:`~werkzeug.datastructures.MultiDict` with the parsed form data from ``POST``37 or ``PUT`` requests. Please keep in mind that file uploads will not38 end up here, but instead in the :attr:`files` attribute.3940 .. attribute:: args4142 A :class:`~werkzeug.datastructures.MultiDict` with the parsed contents of the query43 string. (The part in the URL after the question mark).4445 .. attribute:: values4647 A :class:`~werkzeug.datastructures.CombinedMultiDict` with the contents of both48 :attr:`form` and :attr:`args`.4950 .. attribute:: cookies5152 A :class:`dict` with the contents of all cookies transmitted with53 the request.5455 .. attribute:: stream5657 If the incoming form data was not encoded with a known mimetype58 the data is stored unmodified in this stream for consumption. Most59 of the time it is a better idea to use :attr:`data` which will give60 you that data as a string. The stream only returns the data once.6162 .. attribute:: headers6364 The incoming request headers as a dictionary like object.6566 .. attribute:: data6768 Contains the incoming request data as string in case it came with69 a mimetype Flask does not handle.7071 .. attribute:: files7273 A :class:`~werkzeug.datastructures.MultiDict` with files uploaded as part of a74 ``POST`` or ``PUT`` request. Each file is stored as75 :class:`~werkzeug.datastructures.FileStorage` object. It basically behaves like a76 standard file object you know from Python, with the difference that77 it also has a :meth:`~werkzeug.datastructures.FileStorage.save` function that can78 store the file on the filesystem.7935 .. attribute:: environ3637 The underlying WSGI environment.3884 .. attribute:: method8586 The current request method (``POST``, ``GET`` etc.)8739 .. attribute:: path40 .. attribute:: full_path41 .. attribute:: script_root42 .. attribute:: url
21 unmodified lines
64 `url` ``u'http://www.example.com/myapplication/π/page.html?x=y'``65 `url_root` ``u'http://www.example.com/myapplication/'``66 ============= ======================================================67117 .. attribute:: is_xhr68119 ``True`` if the request was triggered via a JavaScript120 `XMLHttpRequest`. This only works with libraries that support the121 ``X-Requested-With`` header and set it to `XMLHttpRequest`.122 Libraries that do that are prototype, jQuery and Mochikit and123 probably some more.69.. attribute:: request70125.. class:: request12671 To access incoming request data, you can use the global `request`72 object. Flask parses incoming request data for you and gives you73 access to it through that global object. Internally Flask makes74 sure that you always get the correct data for the active thread if you
157 unmodified lines
232233 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.235236 As of 0.11 you can use :meth:`pop` and :meth:`setdefault` in the same237 way you would use them on a dictionary.238239 This is a proxy. See :ref:`notes-on-proxies` for more information.240241242Useful Functions and Classes
16 unmodified lines
259.. autofunction:: has_app_context260261.. autofunction:: url_for262316.. function:: abort(code)263.. autofunction:: abort264318 Raises an :exc:`~werkzeug.exceptions.HTTPException` for the given319 status code. For example to abort request handling with a page not320 found exception, you would call ``abort(404)``.321322 :param code: the HTTP error code.323265.. autofunction:: redirect266267.. autofunction:: make_response268
179 unmodified lines
448449.. autoclass:: flask.blueprints.BlueprintSetupState450 :members:451452.. _core-signals-list:453454Signals455-------456514.. when modifying this list, also update the one in signals.rst515457.. versionadded:: 0.6458518.. data:: signals_available459.. data:: signals.signals_available460461 ``True`` if the signaling system is available. This is the case462 when `blinker`_ is installed.463464The following signals exist in Flask:465466.. data:: template_rendered467468 This signal is sent when a template was successfully rendered. The469 signal is invoked with the instance of the template as `template`470 and the context as dictionary (named `context`).471472 Example subscriber::473474 def log_template_renders(sender, template, context, **extra):475 sender.logger.debug('Rendering template "%s" with context %s',476 template.name or 'string template',477 context)478479 from flask import template_rendered480 template_rendered.connect(log_template_renders, app)481482.. data:: flask.before_render_template483 :noindex:484485 This signal is sent before template rendering process. The486 signal is invoked with the instance of the template as `template`487 and the context as dictionary (named `context`).488489 Example subscriber::490491 def log_template_renders(sender, template, context, **extra):492 sender.logger.debug('Rendering template "%s" with context %s',493 template.name or 'string template',494 context)495496 from flask import before_render_template497 before_render_template.connect(log_template_renders, app)498499.. data:: request_started500531 This signal is sent before any request processing started but when the532 request context was set up. Because the request context is already501 This signal is sent when the request context is set up, before502 any request processing happens. Because the request context is already503 bound, the subscriber can access the request with the standard global504 proxies such as :class:`~flask.request`.505506 Example subscriber::507508 def log_request(sender, **extra):509 sender.logger.debug('Request context is set up')510511 from flask import request_started512 request_started.connect(log_request, app)513514.. data:: request_finished515516 This signal is sent right before the response is sent to the client.517 It is passed the response to be sent named `response`.518519 Example subscriber::520521 def log_response(sender, response, **extra):522 sender.logger.debug('Request context is about to close down. '523 'Response: %s', response)524525 from flask import request_finished526 request_finished.connect(log_response, app)527528.. data:: got_request_exception529530 This signal is sent when an exception happens during request processing.531 It is sent *before* the standard exception handling kicks in and even532 in debug mode, where no exception handling happens. The exception533 itself is passed to the subscriber as `exception`.534535 Example subscriber::536537 def log_exception(sender, exception, **extra):538 sender.logger.debug('Got exception during processing: %s', exception)539540 from flask import got_request_exception541 got_request_exception.connect(log_exception, app)542543.. data:: request_tearing_down544550 This signal is sent when the application is tearing down the request.551 This is always called, even if an error happened. An `exc` keyword552 argument is passed with the exception that caused the teardown.545 This signal is sent when the request is tearing down. This is always546 called, even if an exception is caused. Currently functions listening547 to this signal are called after the regular teardown handlers, but this548 is not something you can rely on.549554 .. versionchanged:: 0.9555 The `exc` parameter was added.550 Example subscriber::551552 def close_db_connection(sender, **extra):553 session.close()554555 from flask import request_tearing_down556 request_tearing_down.connect(close_db_connection, app)557558 As of Flask 0.9, this will also be passed an `exc` keyword argument559 that has a reference to the exception that caused the teardown if560 there was one.561562.. data:: appcontext_tearing_down563559 This signal is sent when the application is tearing down the560 application context. This is always called, even if an error happened.561 An `exc` keyword argument is passed with the exception that caused the562 teardown. The sender is the application.564 This signal is sent when the app context is tearing down. This is always565 called, even if an exception is caused. Currently functions listening566 to this signal are called after the regular teardown handlers, but this567 is not something you can rely on.568569 Example subscriber::570571 def close_db_connection(sender, **extra):572 session.close()573574 from flask import appcontext_tearing_down575 appcontext_tearing_down.connect(close_db_connection, app)576577 This will also be passed an `exc` keyword argument that has a reference578 to the exception that caused the teardown if there was one.579580.. data:: appcontext_pushed581582 This signal is sent when an application context is pushed. The sender567 is the application.583 is the application. This is usually useful for unittests in order to584 temporarily hook in information. For instance it can be used to585 set a resource early onto the `g` object.586587 Example usage::588589 from contextlib import contextmanager590 from flask import appcontext_pushed591592 @contextmanager593 def user_set(app, user):594 def handler(sender, **kwargs):595 g.user = user596 with appcontext_pushed.connected_to(handler, app):597 yield598599 And in the testcode::600601 def test_user_me(self):602 with user_set(app, 'john'):603 c = app.test_client()604 resp = c.get('/users/me')605 assert resp.data == 'username=john'606607 .. versionadded:: 0.10608609.. data:: appcontext_popped610
2 unmodified lines
613 :data:`appcontext_tearing_down` signal.614615 .. versionadded:: 0.10616617618.. data:: message_flashed619620 This signal is sent when the application is flashing a message. The621 messages is sent as `message` keyword argument and the category as622 `category`.623585 .. versionadded:: 0.10624 Example subscriber::625587.. currentmodule:: None626 recorded = []627 def record(sender, message, category, **extra):628 recorded.append((message, category))629589.. class:: flask.signals.Namespace630 from flask import message_flashed631 message_flashed.connect(record, app)632633 .. versionadded:: 0.10634635.. class:: signals.Namespace636637 An alias for :class:`blinker.base.Namespace` if blinker is available,638 otherwise a dummy class that creates fake signals. This class is639 available for Flask extensions that want to provide the same fallback640 system as Flask itself.
4 unmodified lines
645 otherwise returns a fake signal that has a send method that will646 do nothing but will fail with a :exc:`RuntimeError` for all other647 operations, including connecting.648649650.. _blinker: https://pypi.python.org/pypi/blinker651652653Class-Based Views654-----------------655656.. versionadded:: 0.7
31 unmodified lines
688`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=========== ===============================================695696Custom converters can be defined using :attr:`flask.Flask.url_map`.697
131 unmodified lines
829830 Marks a function so that an instance of :class:`ScriptInfo` is passed831 as first argument to the click callback.832783.. autofunction:: script_info_option784785 A special decorator that informs a click callback to be passed the786 script info object as first argument. This is normally not useful787 unless you implement very special commands like the run command which788 does not want the application to be loaded yet.789833.. autodata:: run_command834835.. autodata:: shell_command
modified:docs/appcontext.rst+7 added-2 removed
24 unmodified lines
25- any code can get hold of these objects at any time.2627There is a third state which is sitting in between a little bit.28Sometimes you are dealing with an application in a way that is similar to29how you interact with applications during request handling just that there30is no request active. Consider for instance that you're sitting in an29how you interact with applications during request handling; just that there30is no request active. Consider, for instance, that you're sitting in an31interactive Python shell and interacting with the application, or a32command line application.3334The application context is what powers the :data:`~flask.current_app`
38 unmodified lines
73The application context is also used by the :func:`~flask.url_for`74function in case a ``SERVER_NAME`` was configured. This allows you to75generate URLs even in the absence of a request.7677If no request context has been pushed and an application context has78not been explicitly set, a ``RuntimeError`` will be raised. ::7980 RuntimeError: Working outside of application context.8182Locality of the Context83-----------------------8485The application context is created and destroyed as necessary. It never
53 unmodified lines
modified:docs/becomingbig.rst+2 added-2 removed
10 unmodified lines
11Flask started in part to demonstrate how to build your own framework on top of12existing well-used tools Werkzeug (WSGI) and Jinja (templating), and as it13developed, it became useful to a wide audience. As you grow your codebase,14don't just use Flask -- understand it. Read the source. Flask's code is15written to be read; it's documentation is published so you can use its internal15written to be read; its documentation is published so you can use its internal16APIs. Flask sticks to documented APIs in upstream libraries, and documents its17internal utilities so that you can find the hook points needed for your18project.19
14 unmodified lines
3435The :class:`~flask.Flask` class has many methods designed for subclassing. You36can quickly add or customize behavior by subclassing :class:`~flask.Flask` (see37the linked method docs) and using that subclass wherever you instantiate an38application class. This works well with :ref:`app-factories`.38application class. This works well with :ref:`app-factories`. See :doc:`/patterns/subclassing` for an example.3940Wrap with middleware.41---------------------42
59 unmodified lines
modified:docs/blueprints.rst+33 added-6 removed
174 unmodified lines
175the `template_folder` parameter to the :class:`Blueprint` constructor::176177 admin = Blueprint('admin', __name__, template_folder='templates')178179As for static files, the path can be absolute or relative to the blueprint180resource folder. The template folder is added to the searchpath of181templates but with a lower priority than the actual application's template182folder. That way you can easily override templates that a blueprint183provides in the actual application.179For static files, the path can be absolute or relative to the blueprint180resource folder.181182The template folder is added to the search path of templates but with a lower183priority than the actual application's template folder. That way you can184easily override templates that a blueprint provides in the actual application.185This also means that if you don't want a blueprint template to be accidentally186overridden, make sure that no other blueprint or actual application template187has the same relative path. When multiple blueprints provide the same relative188template path the first blueprint registered takes precedence over the others.189190191So if you have a blueprint in the folder ``yourapplication/admin`` and you192want to render the template ``'admin/index.html'`` and you have provided193``templates`` as a `template_folder` you will have to create a file like188this: :file:`yourapplication/admin/templates/admin/index.html`.194this: :file:`yourapplication/admin/templates/admin/index.html`. The reason195for the extra ``admin`` folder is to avoid getting our template overridden196by a template named ``index.html`` in the actual application template197folder.198199To further reiterate this: if you have a blueprint named ``admin`` and you200want to render a template called :file:`index.html` which is specific to this201blueprint, the best idea is to lay out your templates like this::
42 unmodified lines
244 @simple_page.errorhandler(404)245 def page_not_found(e):246 return render_template('pages/404.html')247248Most errorhandlers will simply work as expected; however, there is a caveat249concerning handlers for 404 and 405 exceptions. These errorhandlers are only250invoked from an appropriate ``raise`` statement or a call to ``abort`` in another251of the blueprint's view functions; they are not invoked by, e.g., an invalid URL252access. This is because the blueprint does not "own" a certain URL space, so253the application instance has no way of knowing which blueprint errorhandler it254should run if given an invalid URL. If you would like to execute different255handling strategies for these errors based on URL prefixes, they may be defined256at the application level using the ``request`` proxy object::257258 @app.errorhandler(404)259 @app.errorhandler(405)260 def _handle_api_error(ex):261 if request.path.startswith('/api/'):262 return jsonify_error(ex)263 else:264 return ex265266More information on error handling see :ref:`errorpages`.
modified:docs/cli.rst+134 added-90 removed
1 unmodified line
23Command Line Interface4======================56.. versionadded:: 1.06.. versionadded:: 0.1178.. currentmodule:: flask910One of the nice new features in Flask 1.0 is the built-in integration of10One of the nice new features in Flask 0.11 is the built-in integration of11the `click <http://click.pocoo.org/>`_ command line interface. This12enables a wide range of new features for the Flask ecosystem and your own13applications.1415Basic Usage16-----------1718After installation of Flask you will now find a :command:`flask` script installed19into your virtualenv. If you don't want to install Flask or you have a20special use-case you can also use ``python -m flask`` to accomplish exactly21the same.18After installation of Flask you will now find a :command:`flask` script19installed into your virtualenv. If you don't want to install Flask or you20have a special use-case you can also use ``python -m flask`` to accomplish21exactly the same.2223The way this script works is by providing access to all the commands on24your Flask application's :attr:`Flask.cli` instance as well as some25built-in commands that are always there. Flask extensions can also26register more commands there if they desire so.2728For the :command:`flask` script to work, an application needs to be discovered.29The two most common ways are either an environment variable30(``FLASK_APP``) or the :option:`--app` / :option:`-a` parameter. It should be the31import path for your application or the path to a Python file. In the32latter case Flask will attempt to setup the Python path for you33automatically and discover the module name but that might not always work.28For the :command:`flask` script to work, an application needs to be29discovered. This is achieved by exporting the ``FLASK_APP`` environment30variable. It can be either set to an import path or to a filename of a31Python module that contains a Flask application.3233In that imported file the name of the app needs to be called ``app`` or36optionally be specified after a colon.34optionally be specified after a colon. For instance35``mymodule:application`` would tell it to use the `application` object in36the :file:`mymodule.py` file.3738Given a :file:`hello.py` file with the application in it named ``app`` this is39how it can be run.38Given a :file:`hello.py` file with the application in it named ``app``39this is how it can be run.4041Environment variables (On Windows use ``set`` instead of ``export``)::4243 export FLASK_APP=hello44 flask run4546Parameters::46Or with a filename::4748 flask --app=hello run48 export FLASK_APP=/path/to/hello.py49 flask run5050File names::5152 flask --app=hello.py run5351Virtualenv Integration52----------------------5354If you are constantly working with a virtualenv you can also put the55``export FLASK_APP`` into your ``activate`` script by adding it to the56bottom of the file. That way every time you activate your virtualenv you57automatically also activate the correct application name.5859Edit the activate script for the shell you use. For example:6061Unix Bash: ``venv/bin/activate``::6263 FLASK_APP=hello64 export FLASK_APP6566Windows CMD.exe: ``venv\Scripts\activate.bat``::6768 set "FLASK_APP=hello"69 :END7071Debug Flag72----------7365The :command:`flask` script can be run with :option:`--debug` or :option:`--no-debug` to66automatically flip the debug flag of the application. This can also be67configured by setting ``FLASK_DEBUG`` to ``1`` or ``0``.74The :command:`flask` script can also be instructed to enable the debug75mode of the application automatically by exporting ``FLASK_DEBUG``. If76set to ``1`` debug is enabled or ``0`` disables it::7778 export FLASK_DEBUG=17980Running a Shell81---------------8283To run an interactive Python shell you can use the ``shell`` command::8474 flask --app=hello shell85 flask shell8687This will start up an interactive Python shell, setup the correct88application context and setup the local variables in the shell. This is89done by invoking the :meth:`Flask.make_shell_context` method of the
6 unmodified lines
96easily. Flask uses `click`_ for the command interface which makes97creating custom commands very easy. For instance if you want a shell98command to initialize the database you can do this::99100 import click101 from flask import Flask102103 app = Flask(__name__)104105 @app.cli.command()106 def initdb():107 """Initialize the database."""96 print 'Init the db'108 click.echo('Init the db')109110The command will then show up on the command line::111100 $ flask -a hello.py initdb112 $ flask initdb113 Init the db114115Application Context116-------------------
16 unmodified lines
133Factory Functions134-----------------135136In case you are using factory functions to create your application (see125:ref:`app-factories`) you will discover that the :command:`flask` command cannot126work with them directly. Flask won't be able to figure out how to137:ref:`app-factories`) you will discover that the :command:`flask` command138cannot work with them directly. Flask won't be able to figure out how to139instantiate your application properly by itself. Because of this reason140the recommendation is to create a separate file that instantiates129applications. This is by far not the only way to make this work. Another130is the :ref:`custom-scripts` support.141applications. This is not the only way to make this work. Another is the142:ref:`custom-scripts` support.143144For instance if you have a factory function that creates an application145from a filename you could make a separate file that creates such an146application from an environment variable.
3 unmodified lines
150 import os151 from yourapplication import create_app152 app = create_app(os.environ['YOURAPPLICATION_CONFIG'])153142Once this has happened you can make the flask command automatically pick143it up::154Once this has happened you can make the :command:`flask` command automatically155pick it up::156157 export YOURAPPLICATION_CONFIG=/path/to/config.cfg158 export FLASK_APP=/path/to/autoapp.py159
3 unmodified lines
163164Custom Scripts165--------------166155While the most common way is to use the :command:`flask` command, you can also156make your own "driver scripts". Since Flask uses click for the scripts157there is no reason you cannot hook these scripts into any click167While the most common way is to use the :command:`flask` command, you can168also make your own "driver scripts". Since Flask uses click for the169scripts there is no reason you cannot hook these scripts into any click170application. There is one big caveat and that is, that commands171registered to :attr:`Flask.cli` will expect to be (indirectly at least)172launched from a :class:`flask.cli.FlaskGroup` click group. This is173necessary so that the commands know which Flask application they have to174work with.175176To understand why you might want custom scripts you need to understand how165click finds and executes the Flask application. If you use the :command:`flask`166script you specify the application to work with on the command line or167environment variable as an import name. This is simple but it has some168limitations. Primarily it does not work with application factory169functions (see :ref:`app-factories`).177click finds and executes the Flask application. If you use the178:command:`flask` script you specify the application to work with on the179command line or environment variable as an import name. This is simple180but it has some limitations. Primarily it does not work with application181factory functions (see :ref:`app-factories`).182183With a custom script you don't have this problem as you can fully184customize how the application will be created. This is very useful if you185write reusable applications that you want to ship to users and they should186be presented with a custom management script.187176If you are used to writing click applications this will look familiar but177at the same time, slightly different because of how commands are loaded.178We won't go into detail now about the differences but if you are curious179you can have a look at the :ref:`script-info-object` section to learn all180about it.181188To explain all of this, here is an example :file:`manage.py` script that189manages a hypothetical wiki application. We will go through the details190afterwards::191192 import os193 import click187 from flask.cli import FlaskGroup, script_info_option194 from flask.cli import FlaskGroup195196 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'))200201 @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."""204205 if __name__ == '__main__':206 cli()
2 unmodified lines
209step.2102111. 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.2142. 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`).214215 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.2203. 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.223224 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.2244. 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.2295. All is rounded up by invoking the script.2264. All is rounded up by invoking the script.227231.. _script-info-object:228CLI Plugins229-----------230233The Script Info234---------------231Flask extensions can always patch the :attr:`Flask.cli` instance with more232commands if they want. However there is a second way to add CLI plugins233to Flask which is through ``setuptools``. If you make a Python package that234should export a Flask command line plugin you can ship a :file:`setup.py` file235that declares an entrypoint that points to a click command:236236The Flask script integration might be confusing at first, but there is a reason237why it's done this way. The reason for this is that Flask wants to238both provide custom commands to click as well as not loading your239application unless it has to. The reason for this is added flexibility.237Example :file:`setup.py`::238241This way an application can provide custom commands, but even in the242absence of an application the :command:`flask` script is still operational on a243basic level. In addition to that it means that the individual commands244have the option to avoid creating an instance of the Flask application245unless required. This is very useful as it allows the server commands for246instance to load the application on a first request instead of247immediately, therefore giving a better debug experience.239 from setuptools import setup240249All of this is provided through the :class:`flask.cli.ScriptInfo` object250and some helper utilities around. The basic way it operates is that when251the :class:`flask.cli.FlaskGroup` executes as a script it creates a script252info and keeps it around. From that point onwards modifications on the253script info can be done through click options. To simplify this pattern254the :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 )249256Once Flask actually needs the individual Flask application it will invoke257the :meth:`flask.cli.ScriptInfo.load_app` method. This happens when the258server starts, when the shell is launched or when the script looks for an259application-provided click command.250Inside :file:`mypackage/commands.py` you can then export a Click object::251252 import click253254 @click.command()255 def cli():256 """This is an example command."""257258Once that package is installed in the same virtualenv as Flask itself you259can run ``flask my-command`` to invoke your command. This is useful to260provide extra functionality that Flask itself cannot ship.261262PyCharm Integration263-------------------264265The new Flask CLI features aren’t yet fully integrated into the PyCharm IDE,266so we have to do a few tweaks to get them working smoothly.267268In your PyCharm application, with your project open, click on *Run*269from the menu bar and go to *Edit Configurations*. You’ll be greeted by a270screen similar to this:271272.. image:: _static/pycharm-runconfig.png273 :align: center274 :class: screenshot275 :alt: screenshot of pycharm's run configuration settings276277There’s quite a few options to change, but don’t worry— once we’ve done it278for one command, we can easily copy the entire configuration and make a279single tweak to give us access to other flask cli commands, including280any custom ones you may implement yourself.281282For the *Script* input (**A**), we want to navigate to the virtual environment283we’re using for our project and within that folder we want to pick the ``flask``284file which will reside in the ``bin`` folder, or in the ``Scripts`` folder if285you're on Windows.286287The *Script Parameter* field (**B**) is set to the cli command you wish to288execute, in this example we use ``run`` which will run our development server.289290We need to add an environment variable (**C**) to identify our application.291Click on the browse button and add an entry with ``FLASK_APP`` on the292left and the name of the python file, or package on the right293(``app.py`` for example).294295Next we need to set the working directory (**D**) to be the same folder where296our application file or package resides.297298Finally, untick the *PYTHONPATH* options (**E**) and give the configuration a299good descriptive name, such as “Run Flask Server” and click *Apply*.300301Now that we have on run configuration which implements ``flask run`` from within302PyCharm, we can simply copy that configuration and alter the script argument303to run a different cli command, e.g. ``flask shell``.
modified:docs/conf.py+67 added-49 removed
8 unmodified lines
9# autogenerated file.10#11# All configuration values have a default; values that are commented out12# serve to show the default.13from __future__ import print_function14import os15import sys16import pkg_resources17import time18import datetime1914import sys, os20BUILD_DATE = datetime.datetime.utcfromtimestamp(int(os.environ.get('SOURCE_DATE_EPOCH', time.time())))2122# If extensions (or modules to document with autodoc) are in another directory,23# add these directories to sys.path here. If the directory is relative to the24# documentation root, use os.path.abspath to make it absolute, like shown here.19sys.path.append(os.path.abspath('_themes'))20sys.path.append(os.path.abspath('.'))25sys.path.append(os.path.join(os.path.dirname(__file__), '_themes'))26sys.path.append(os.path.dirname(__file__))2728# -- General configuration -----------------------------------------------------2930# If your documentation needs a minimal Sphinx version, state it here.31#needs_sphinx = '1.0'3233# Add any Sphinx extension module names here, as strings. They can be extensions34# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.35extensions = [36 'sphinx.ext.autodoc',29extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx',30 'flaskdocext']37 'sphinx.ext.intersphinx',38 'flaskdocext'39]4041try:42 __import__('sphinxcontrib.log_cabinet')43except ImportError:44 print('sphinxcontrib-log-cabinet is not installed.')45 print('Changelog directives will not be re-organized.')46else:47 extensions.append('sphinxcontrib.log_cabinet')4849# Add any paths that contain templates here, relative to this directory.50templates_path = ['_templates']5152# The suffix of source filenames.
6 unmodified lines
59master_doc = 'index'6061# General information about the project.62project = u'Flask'46copyright = u'2015, Armin Ronacher'63copyright = u'2010 - {0}, Armin Ronacher'.format(BUILD_DATE.year)6465# The version info for the project you're documenting, acts as replacement for66# |version| and |release|, also used in various other places throughout the67# built documents.51import pkg_resources68try:69 release = pkg_resources.get_distribution('Flask').version70except 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!'71 print('Flask must be installed to build the documentation.')72 print('Install from source using `pip install -e .` in a virtualenv.')73 sys.exit(1)60del pkg_resources7475if 'dev' in release:63 release = release.split('dev')[0] + 'dev'76 release = ''.join(release.partition('dev')[:2])7778version = '.'.join(release.split('.')[:2])7980# The language for content autogenerated by Sphinx. Refer to documentation81# for a list of supported languages.
30 unmodified lines
112# -- Options for HTML output ---------------------------------------------------113114# The theme to use for HTML and HTML Help pages. Major themes that come with115# Sphinx are currently 'default' and 'sphinxdoc'.102html_theme = 'flask'116# html_theme = 'default'117118# Theme options are theme-specific and customize the look and feel of a theme119# further. For a list of options available for each theme, see the120# documentation.107html_theme_options = {108 'touch_icon': 'touch-icon.png'109}121# html_theme_options = {}122123# Add any paths that contain custom themes here, relative to this directory.124html_theme_path = ['_themes']125
10 unmodified lines
136137# The name of an image file (within the static path) to use as favicon of the138# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32139# pixels large.128html_favicon = "flask-favicon.ico"140html_favicon = '_static/flask-favicon.ico'141142# Add any paths that contain custom static files (such as style sheets) here,143# relative to this directory. They are copied after the builtin static files,144# so a file named "default.css" will overwrite the builtin "default.css".
8 unmodified lines
153#html_use_smartypants = True154155# Custom sidebar templates, maps document names to template names.156html_sidebars = {145 'index': ['sidebarintro.html', 'sourcelink.html', 'searchbox.html'],146 '**': ['sidebarlogo.html', 'localtoc.html', 'relations.html',147 'sourcelink.html', 'searchbox.html']157 'index': [158 'sidebarintro.html',159 'sourcelink.html',160 'searchbox.html'161 ],162 '**': [163 'sidebarlogo.html',164 'localtoc.html',165 'relations.html',166 'sourcelink.html',167 'searchbox.html'168 ]169}170171# Additional templates that should be rendered to pages, maps page names to172# template names.
33 unmodified lines
206207# Grouping the document tree into LaTeX files. List of tuples208# (source start file, target name, title, author, documentclass [howto/manual]).209latex_documents = [189 ('latexindex', 'Flask.tex', u'Flask Documentation',190 u'Armin Ronacher', 'manual'),210 ('latexindex', 'Flask.tex', u'Flask Documentation', u'Armin Ronacher', 'manual'),211]212213# Documents to append as an appendix to all manuals.214#latex_appendices = []
1 unmodified line
216# If false, no module index is generated.217latex_use_modindex = False218219latex_elements = {200 'fontpkg': r'\usepackage{mathpazo}',201 'papersize': 'a4paper',202 'pointsize': '12pt',203 'preamble': r'\usepackage{flaskstyle}'220 'fontpkg': r'\usepackage{mathpazo}',221 'papersize': 'a4paper',222 'pointsize': '12pt',223 'preamble': r'\usepackage{flaskstyle}'224}225latex_use_parts = True226227latex_additional_files = ['flaskstyle.sty', 'logo.pdf']
13 unmodified lines
241242# The scheme of the identifier. Typical schemes are ISBN or URL.243#epub_scheme = ''244225# The unique identifier of the text. This can be a ISBN number245# The unique identifier of the text. This can be an ISBN number246# or the project homepage.247#epub_identifier = ''248249# A unique identification for the text.
13 unmodified lines
263# The depth of the table of contents in toc.ncx.264#epub_tocdepth = 3265266intersphinx_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/': None267 'python': ('https://docs.python.org/3/', None),268 'werkzeug': ('http://werkzeug.pocoo.org/docs/', None),269 'click': ('http://click.pocoo.org/', None),270 'jinja': ('http://jinja.pocoo.org/docs/', None),271 'sqlalchemy': ('https://docs.sqlalchemy.org/en/latest/', None),272 'wtforms': ('https://wtforms.readthedocs.io/en/latest/', None),273 'blinker': ('https://pythonhosted.org/blinker/', None)274}275256pygments_style = 'flask_theme_support.FlaskyStyle'257258# fall back if theme is not there276try:277 __import__('flask_theme_support')261except 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 '-' * 74278 pygments_style = 'flask_theme_support.FlaskyStyle'279 html_theme = 'flask'280 html_theme_options = {281 'touch_icon': 'touch-icon.png'282 }283except ImportError:284 print('-' * 74)285 print('Warning: Flask themes unavailable. Building with default theme')286 print('If you want the Flask themes, run this command and build again:')287 print()288 print(' git submodule update --init')289 print('-' * 74)290269 pygments_style = 'tango'270 html_theme = 'default'271 html_theme_options = {}291273292# unwrap decorators293def unwrap_decorators():294 import sphinx.util.inspect as inspect295 import functools
15 unmodified lines
modified:docs/config.rst+36 added-19 removed
42 unmodified lines
43 DEBUG=True,44 SECRET_KEY='...'45 )4647.. admonition:: Debug Mode with the ``flask`` Script4849 If you use the :command:`flask` script to start a local development50 server, to enable the debug mode, you need to export the ``FLASK_DEBUG``51 environment variable before running the server::5253 $ export FLASK_DEBUG=154 $ flask run5556 (On Windows you need to use ``set`` instead of ``export``).57 58 ``app.debug`` and ``app.config['DEBUG']`` are not compatible with 59   the :command:`flask` script. They only worked when using ``Flask.run()``60 method.61 62Builtin Configuration Values63----------------------------6465The following configuration values are used internally by Flask:6667.. tabularcolumns:: |p{6.5cm}|p{8.5cm}|6869================================= =========================================55``DEBUG`` enable/disable debug mode70``DEBUG`` enable/disable debug mode when using 71 ``Flask.run()`` method to start server72``TESTING`` enable/disable testing mode73``PROPAGATE_EXCEPTIONS`` explicitly enable or disable the74 propagation of exceptions. If not set or75 explicitly set to ``None`` this is
55 unmodified lines
131 help. Setting a ``SERVER_NAME`` also132 by default enables URL generation133 without a request context but with an134 application context.119``APPLICATION_ROOT`` If the application does not occupy120 a whole domain or subdomain this can121 be set to the path where the application122 is configured to live. This is for123 session cookie as path value. If124 domains are used, this should be125 ``None``.135``APPLICATION_ROOT`` The path value used for the session136 cookie if ``SESSION_COOKIE_PATH`` isn't137 set. If it's also ``None`` ``'/'`` is used.138 Note that to actually serve your Flask139 app under a subpath you need to tell140 your WSGI container the ``SCRIPT_NAME``141 WSGI environment variable.142``MAX_CONTENT_LENGTH`` If set to a value in bytes, Flask will143 reject incoming requests with a144 content length greater than this by145 returning a 413 status code.146``SEND_FILE_MAX_AGE_DEFAULT`` Default cache control max age to use with147 :meth:`~flask.Flask.send_static_file` (the148 default static file handler) and133 :func:`~flask.send_file`, in134 seconds. Override this value on a per-file149 :func:`~flask.send_file`, as150 :class:`datetime.timedelta` or as seconds.151 Override this value on a per-file152 basis using the153 :meth:`~flask.Flask.get_send_file_max_age`154 hook on :class:`~flask.Flask` or155 :class:`~flask.Blueprint`,
36 unmodified lines
192 caches. You can override the default193 behavior by changing this variable.194 This is not recommended but might give195 you a performance improvement on the179 cost of cachability.180``JSONIFY_PRETTYPRINT_REGULAR`` If this is set to ``True`` (the default)181 jsonify responses will be pretty printed182 if they are not requested by an183 XMLHttpRequest object (controlled by184 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 checks
49 unmodified lines
254255.. versionadded:: 0.10256 ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_PRETTYPRINT_REGULAR``257242.. versionadded:: 1.0258.. versionadded:: 0.11259 ``SESSION_REFRESH_EACH_REQUEST``, ``TEMPLATES_AUTO_RELOAD``,260 ``LOGGER_HANDLER_POLICY``, ``EXPLAIN_TEMPLATE_LOADING``261262Configuring from Files
12 unmodified lines
275 app.config.from_envvar('YOURAPPLICATION_SETTINGS')276277This first loads the configuration from the278`yourapplication.default_settings` module and then overrides the values263with the contents of the file the :envvar:``YOURAPPLICATION_SETTINGS``279with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS`280environment variable points to. This environment variable can be set on281Linux or OS X with the export command in the shell before starting the282server::283
39 unmodified lines
3232. 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.326327.. _config-dev-prod:328329Development / Production330------------------------331
13 unmodified lines
345there are alternative ways as well. For example you could use imports or346subclassing.347348What is very popular in the Django world is to make the import explicit in332the config file by adding an ``from yourapplication.default_settings349the config file by adding ``from yourapplication.default_settings350import *`` to the top of the file and then overriding the changes by hand.351You could also inspect an environment variable like352``YOURAPPLICATION_MODE`` and set that to `production`, `development` etc353and import different hardcoded files based on that.
126 unmodified lines
modified:docs/errorhandling.rst+55 added-13 removed
26 unmodified lines
2728But there is more you can do, and we will cover some better setups to deal29with errors.3031Error Logging Tools32-------------------3334Sending error mails, even if just for critical ones, can become35overwhelming if enough users are hitting the error and log files are36typically never looked at. This is why we recommend using `Sentry37<https://www.getsentry.com/>`_ for dealing with application errors. It's38available as an Open Source project `on GitHub39<https://github.com/getsentry/sentry>`__ and is also available as a `hosted version40<https://getsentry.com/signup/>`_ which you can try for free. Sentry41aggregates duplicate errors, captures the full stack trace and local42variables for debugging, and sends you mails based on new errors or43frequency thresholds.4445To use Sentry you need to install the `raven` client::4647 $ pip install raven4849And then add this to your Flask app::5051 from raven.contrib.flask import Sentry52 sentry = Sentry(app, dsn='YOUR_DSN_HERE')5354Or if you are using factories you can also init it later::5556 from raven.contrib.flask import Sentry57 sentry = Sentry(dsn='YOUR_DSN_HERE')5859 def create_app():60 app = Flask(__name__)61 sentry.init_app(app)62 ...63 return app6465The `YOUR_DSN_HERE` value needs to be replaced with the DSN value you get66from your Sentry installation.6768Afterwards failures are automatically reported to Sentry and from there69you can receive error notifications.7071.. _error-handlers:7273Error handlers74--------------
1 unmodified line
76You might want to show custom error pages to the user when an error occurs.77This can be done by registering error handlers.7879Error handlers are normal :ref:`views` but instead of being registered for40routes they are registered for exceptions that are rised while trying to80routes, they are registered for exceptions that are raised while trying to81do something else.8283Registering84```````````
3 unmodified lines
8889 @app.errorhandler(werkzeug.exceptions.BadRequest)90 def handle_bad_request(e):91 return 'bad request!'52 9293 app.register_error_handler(400, lambda e: 'bad request!')9495Those two ways are equivalent, but the first one is more clear and leaves96you with a function to call on your whim (and in tests). Note that97:exc:`werkzeug.exceptions.HTTPException` subclasses like98:exc:`~werkzeug.exceptions.BadRequest` from the example and their HTTP codes59are interchangable when handed to the registration methods or decorator99are interchangeable when handed to the registration methods or decorator100(``BadRequest.code == 400``).10162You are however not limited to a :exc:`~werkzeug.exceptions.HTTPException`63or its code but can register a handler for every exception class you like.102You are however not limited to :exc:`~werkzeug.exceptions.HTTPException`103or HTTP status codes but can register a handler for every exception class you104like.10565.. versionchanged:: 1.0106.. versionchanged:: 0.1110767 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.110111Handling112````````113114Once an exception instance is raised, its class hierarchy is traversed,115and searched for in the exception classes for which handlers are registered.116The most specific handler is selected.11777E.g. if a instance of :exc:`ConnectionRefusedError` is raised, and a handler118E.g. if an instance of :exc:`ConnectionRefusedError` is raised, and a handler119is registered for :exc:`ConnectionError` and :exc:`ConnectionRefusedError`,120the more specific :exc:`ConnectionRefusedError` handler is called on the121exception instance, and its response is shown to the user.122
47 unmodified lines
170-----------------171172Even if you get mails, you probably also want to log warnings. It's a173good idea to keep as much information around that might be required to133debug a problem. By default as of Flask 1.0, errors are logged to your174debug a problem. By default as of Flask 0.11, errors are logged to your175webserver's log automatically. Warnings however are not. Please note176that Flask itself will not issue any warnings in the core system, so it's177your responsibility to warn in the code if something seems odd.178
36 unmodified lines
215A formatter can be instantiated with a format string. Note that216tracebacks are appended to the log entry automatically. You don't have to217do that in the log formatter format string.218178Here some example setups:219Here are some example setups:220221Email222`````223
51 unmodified lines
275+------------------+----------------------------------------------------+276| ``%(lineno)d`` | Source line number where the logging call was |277| | issued (if available). |278+------------------+----------------------------------------------------+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 lines
modified:docs/extensiondev.rst+41 added-45 removed
27 unmodified lines
28"Flask" somewhere in that name and that you check the capitalization.29This is how users can then register dependencies to your extension in30their :file:`setup.py` files.3132Flask sets up a redirect package called :data:`flask.ext` where users33should import the extensions from. If you for instance have a package34called ``flask_something`` users would import it as35``flask.ext.something``. This is done to transition from the old36namespace packages. See :ref:`ext-import-transition` for more details.3738But how do extensions look like themselves? An extension has to ensure32But what do extensions look like themselves? An extension has to ensure33that it works with multiple Flask application instances at once. This is34a requirement because many people will use patterns like the35:ref:`app-factories` pattern to create their application as needed to aid36unittests and to support multiple configurations. Because of that it is
311 unmodified lines
348new releases. These approved extensions are listed on the `Flask349Extension Registry`_ and marked appropriately. If you want your own350extension to be approved you have to follow these guidelines:3513580. An approved Flask extension requires a maintainer. In the event an359 extension author would like to move beyond the project, the project should360 find a new maintainer including full source hosting transition and PyPI361 access. If no maintainer is available, give access to the Flask core team.3621. An approved Flask extension must provide exactly one package or module363 named ``flask_extensionname``.3642. It must ship a testing suite that can either be invoked with ``make test``365 or ``python setup.py test``. For test suites invoked with ``make366 test`` the extension has to ensure that all dependencies for the test367 are installed automatically. If tests are invoked with ``python setup.py368 test``, test dependencies can be specified in the `setup.py` file. The369 test suite also has to be part of the distribution.3703. APIs of approved extensions will be checked for the following371 characteristics:3520. An approved Flask extension requires a maintainer. In the event an353 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.3561. An approved Flask extension must provide exactly one package or module357 named ``flask_extensionname``.3582. 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.py362 test``, test dependencies can be specified in the :file:`setup.py` file. The363 test suite also has to be part of the distribution.3643. APIs of approved extensions will be checked for the following365 characteristics:366367 - an approved extension has to support multiple applications368 running in the same Python process.369 - it must be possible to use the factory pattern for creating370 applications.3713784. The extension must be BSD/MIT/WTFPL licensed.3795. The naming scheme for official extensions is *Flask-ExtensionName* or380 *ExtensionName-Flask*.3816. Approved extensions must define all their dependencies in the382 `setup.py` file unless a dependency cannot be met because it is not383 available on PyPI.3847. The extension must have documentation that uses one of the two Flask385 themes for Sphinx documentation.3868. The ``zip_safe`` flag in the setup script must be set to ``False``,3724. The license must be BSD/MIT/WTFPL licensed.3735. The naming scheme for official extensions is *Flask-ExtensionName* or374 *ExtensionName-Flask*.3756. Approved extensions must define all their dependencies in the376 :file:`setup.py` file unless a dependency cannot be met because it is not377 available on PyPI.3787. The extension must have documentation that uses one of the two Flask379 themes for Sphinx documentation.3808. The setup.py description (and thus the PyPI description) has to381 link to the documentation, website (if there is one) and there382 must be a link to automatically install the development version383 (``PackageName==dev``).3849. The ``zip_safe`` flag in the setup script must be set to ``False``,385 even if the extension would be safe for zipping.3889. An extension currently has to support Python 2.7, Python 3.3 and higher.38610. An extension currently has to support Python 2.7, Python 3.3 and higher.387388391.. _ext-import-transition:389390Extension Import Transition391---------------------------392396For a while we recommended using namespace packages for Flask extensions.397This turned out to be problematic in practice because many different398competing namespace package systems exist and pip would automatically399switch between different systems and this caused a lot of problems for400users.393In early versions of Flask we recommended using namespace packages for Flask394extensions, of the form ``flaskext.foo``. This turned out to be problematic in395practice because it meant that multiple ``flaskext`` packages coexist.396Consequently we have recommended to name extensions ``flask_foo`` over397``flaskext.foo`` for a long time.398402Instead we now recommend naming packages ``flask_foo`` instead of the now403deprecated ``flaskext.foo``. Flask 0.8 introduces a redirect import404system that lets uses import from ``flask.ext.foo`` and it will try405``flask_foo`` first and if that fails ``flaskext.foo``.399Flask 0.8 introduced a redirect import system as a compatibility aid for app400developers: Importing ``flask.ext.foo`` would try ``flask_foo`` and401``flaskext.foo`` in that order.402407Flask extensions should urge users to import from ``flask_foo``408instead of ``flask.ext.foo`` or ``flaskext_foo`` so that extensions can409transition to the new package name without affecting users.403As of Flask 0.11, most Flask extensions have transitioned to the new naming404schema. The ``flask.ext.foo`` compatibility alias is still in Flask 0.11 but is405now deprecated -- you should use ``flask_foo``.406407412.. _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:23Flask Extensions4================56Flask extensions extend the functionality of Flask in various different
12 unmodified lines
1920Extensions typically have documentation that goes along that shows how to21use it. There are no general rules in how extensions are supposed to22behave but they are imported from common locations. If you have an21extension called ``Flask-Foo`` or ``Foo-Flask`` it will be always22importable from ``flask.ext.foo``::23extension called ``Flask-Foo`` or ``Foo-Flask`` it should be always24importable from ``flask_foo``::2524 from flask.ext import foo26 import flask_foo2728Building Extensions29-------------------3031While `Flask Extension Registry`_ contains many Flask extensions, you may not find32an extension that fits your need. If this is the case, you can always create your own. 33Consider reading :ref:`extension-dev` to develop your own Flask extension.3435Flask Before 0.836----------------3738If you are using Flask 0.7 or earlier the :data:`flask.ext` package will not
13 unmodified lines
5253Once the ``flaskext_compat`` module is activated the :data:`flask.ext` will54exist and you can start importing from there.555657.. _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.py
modified:docs/htmlfaq.rst+1 added-1 removed
28 unmodified lines
29the (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 from31accidentally creating invalid XHTML. There are XML based template engines,32such as Kid and the popular Genshi, but they often come with a larger33runtime overhead and, are not as straightforward to use because they have33runtime overhead and are not as straightforward to use because they have34to obey XML rules.3536The majority of users, however, assumed they were properly using XHTML.37They wrote an XHTML doctype at the top of the document and self-closed all
170 unmodified lines
modified:docs/installation.rst+116 added-117 removed
1 unmodified line
23Installation4============56Flask depends on some external libraries, like `Werkzeug7<http://werkzeug.pocoo.org/>`_ and `Jinja2 <http://jinja.pocoo.org/>`_.8Werkzeug is a toolkit for WSGI, the standard Python interface between web9applications and a variety of servers for both development and deployment.10Jinja2 renders templates.6Python Version7--------------812So how do you get all that on your computer quickly? There are many ways you13could do that, but the most kick-ass method is virtualenv, so let's have a look14at that first.9We recommend using the latest version of Python 3. Flask supports Python 3.310and newer, Python 2.6 and newer, and PyPy.1116You will need Python 2.6 or newer to get started, so be sure to have an17up-to-date Python 2.x installation. For using Flask with Python 3 have a18look at :ref:`python3-support`.12Dependencies13------------1420.. _virtualenv:15These distributions will be installed automatically when installing Flask.1622virtualenv23----------17* `Werkzeug`_ implements WSGI, the standard Python interface between18 applications and servers.19* `Jinja`_ is a template language that renders the pages your application20 serves.21* `MarkupSafe`_ comes with Jinja. It escapes untrusted input when rendering22 templates to avoid injection attacks.23* `ItsDangerous`_ securely signs data to ensure its integrity. This is used24 to protect Flask's session cookie.25* `Click`_ is a framework for writing command line applications. It provides26 the ``flask`` command and allows adding custom management commands.2725Virtualenv is probably what you want to use during development, and if you have26shell access to your production machines, you'll probably want to use it there,27too.28.. _Werkzeug: http://werkzeug.pocoo.org/29.. _Jinja: http://jinja.pocoo.org/30.. _MarkupSafe: https://pypi.python.org/pypi/MarkupSafe31.. _ItsDangerous: https://pythonhosted.org/itsdangerous/32.. _Click: http://click.pocoo.org/3329What problem does virtualenv solve? If you like Python as much as I do,30chances are you want to use it for other projects besides Flask-based web31applications. But the more projects you have, the more likely it is that you32will be working with different versions of Python itself, or at least different33versions of Python libraries. Let's face it: quite often libraries break34backwards compatibility, and it's unlikely that any serious application will35have zero dependencies. So what do you do if two or more of your projects have36conflicting dependencies?34Optional dependencies35~~~~~~~~~~~~~~~~~~~~~3638Virtualenv to the rescue! Virtualenv enables multiple side-by-side39installations of Python, one for each project. It doesn't actually install40separate copies of Python, but it does provide a clever way to keep different41project environments isolated. Let's see how virtualenv works.37These distributions will not be installed automatically. Flask will detect and38use them if you install them.3943If you are on Mac OS X or Linux, chances are that one of the following two44commands will work for you::40* `Blinker`_ provides support for :ref:`signals`.41* `SimpleJSON`_ is a fast JSON implementation that is compatible with42 Python's ``json`` module. It is preferred for JSON operations if it is43 installed.4446 $ sudo easy_install virtualenv45.. _Blinker: https://pythonhosted.org/blinker/46.. _SimpleJSON: https://simplejson.readthedocs.io/4748or even better::48Virtual environments49--------------------5050 $ sudo pip install virtualenv51Use a virtual environment to manage the dependencies for your project, both in52development and in production.5352One of these will probably install virtualenv on your system. Maybe it's even53in your package manager. If you use Ubuntu, try::54What problem does a virtual environment solve? The more Python projects you55have, the more likely it is that you need to work with different versions of56Python libraries, or even Python itself. Newer versions of libraries for one57project can break compatibility in another project.5855 $ sudo apt-get install python-virtualenv59Virtual environments are independent groups of Python libraries, one for each60project. Packages installed for one project will not affect other projects or61the operating system's packages.6257If you are on Windows and don't have the :command:`easy_install` command, you must58install it first. Check the :ref:`windows-easy-install` section for more59information about how to do that. Once you have it installed, run the same60commands as above, but without the :command:`sudo` prefix.63Python 3 comes bundled with the :mod:`venv` module to create virtual64environments. If you're using a modern version of Python, you can continue on65to the next section.6662Once you have virtualenv installed, just fire up a shell and create63your own environment. I usually create a project folder and a :file:`venv`64folder within::67If you're using Python 2, see :ref:`install-install-virtualenv` first.6866 $ mkdir myproject67 $ cd myproject68 $ virtualenv venv69 New python executable in venv/bin/python70 Installing setuptools, pip............done.69.. _install-create-env:7072Now, whenever you want to work on a project, you only have to activate the73corresponding environment. On OS X and Linux, do the following::71Create an environment72~~~~~~~~~~~~~~~~~~~~~7375 $ . venv/bin/activate74Create a project folder and a :file:`venv` folder within:7577If you are a Windows user, the following command is for you::76.. code-block:: sh7779 $ venv\scripts\activate78 mkdir myproject79 cd myproject80 python3 -m venv venv8181Either way, you should now be using your virtualenv (notice how the prompt of82your shell has changed to show the active environment).82On Windows:8384And if you want to go back to the real world, use the following command::84.. code-block:: bat8586 $ deactivate86 py -3 -m venv venv8788After doing this, the prompt of your shell should be as familiar as before.88If you needed to install virtualenv because you are on an older version of89Python, use the following command instead:9090Now, let's move on. Enter the following command to get Flask activated in your91virtualenv::91.. code-block:: sh9293 $ pip install Flask93 virtualenv venv9495A few seconds later and you are good to go.95On Windows:9697.. code-block:: bat9898System-Wide Installation99------------------------99 \Python27\Scripts\virtualenv.exe venv100101This is possible as well, though I do not recommend it. Just run102:command:`pip` with root privileges::101Activate the environment102~~~~~~~~~~~~~~~~~~~~~~~~103104 $ sudo pip install Flask104Before you work on your project, activate the corresponding environment:105106(On Windows systems, run it in a command-prompt window with administrator107privileges, and leave out :command:`sudo`.)106.. code-block:: sh107108 . venv/bin/activate109110Living on the Edge111------------------110On Windows:111113If you want to work with the latest version of Flask, there are two ways: you114can either let :command:`pip` pull in the development version, or you can tell115it to operate on a git checkout. Either way, virtualenv is recommended.112.. code-block:: bat113117Get the git checkout in a new virtualenv and run in development mode::114 venv\Scripts\activate115119 $ git clone http://github.com/mitsuhiko/flask.git120 Initialized empty Git repository in ~/dev/flask/.git/121 $ cd flask122 $ virtualenv venv123 New python executable in venv/bin/python124 Installing setuptools, pip............done.125 $ . venv/bin/activate126 $ python setup.py develop127 ...128 Finished processing dependencies for Flask116Your shell prompt will change to show the name of the activated environment.117130This will pull in the dependencies and activate the git head as the current131version inside the virtualenv. Then all you have to do is run ``git pull132origin`` to update to the latest version.118Install Flask119-------------120121Within the activated environment, use the following command to install Flask:122135.. _windows-easy-install:123.. code-block:: sh124137`pip` and `setuptools` on Windows138---------------------------------125 pip install Flask126140Sometimes getting the standard "Python packaging tools" like *pip*, *setuptools*141and *virtualenv* can be a little trickier, but nothing very hard. The two crucial142packages you will need are setuptools and pip - these will let you install143anything else (like virtualenv). Fortunately there are two "bootstrap scripts"144you can run to install either.127Living on the edge128~~~~~~~~~~~~~~~~~~129146If you don't currently have either, then `get-pip.py` will install both for you147(you won't need to run ez_setup.py).130If you want to work with the latest Flask code before it's released, install or131update the code from the master branch:132149`get-pip.py`_133.. code-block:: sh134151To install the latest setuptools, you can use its bootstrap file:135 pip install -U https://github.com/pallets/flask/archive/master.tar.gz136153`ez_setup.py`_137.. _install-install-virtualenv:138155Either should be double-clickable once you download them. If you already have pip,156you can upgrade them by running::139Install virtualenv140------------------141158 > pip install --upgrade pip setuptools142If you are using Python 2, the venv module is not available. Instead,143install `virtualenv`_.144160Most often, once you pull up a command prompt you want to be able to type :command:`pip`161and :command:`python` which will run those things, but this might not automatically happen162on Windows, because it doesn't know where those executables are (give either a try!).145On Linux, virtualenv is provided by your package manager:146164To fix this, you should be able to navigate to your Python install directory165(e.g :file:`C:\Python27`), then go to :file:`Tools`, then :file:`Scripts`; then find the166:file:`win_add2path.py` file and run that. Open a **new** Command Prompt and167check that you can now just type :command:`python` to bring up the interpreter.147.. code-block:: sh148169Finally, to install `virtualenv`_, you can simply run::149 # Debian, Ubuntu150 sudo apt-get install python-virtualenv151171 > pip install virtualenv152 # CentOS, Fedora153 sudo yum install python-virtualenv154173Then you can be off on your way following the installation instructions above.155 # Arch156 sudo pacman -S python-virtualenv157175.. _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.py158If you are on Mac OS X or Windows, download `get-pip.py`_, then:159160.. code-block:: sh161162 sudo python2 Downloads/get-pip.py163 sudo python2 -m pip install virtualenv164165On Windows, as an administrator:166167.. code-block:: bat168169 \Python27\python.exe Downloads\get-pip.py170 \Python27\python.exe -m pip install virtualenv171172Now you can continue to :ref:`install-create-env`.173174.. _virtualenv: https://virtualenv.pypa.io/175.. _get-pip.py: https://bootstrap.pypa.io/get-pip.py
modified:docs/python3.rst+14 added-25 removed
1 unmodified line
23Python 3 Support4================56Flask and all of its dependencies support Python 3 so you can in theory7start working on it already. There are however a few things you should be8aware of before you start using Python 3 for your next project.6Flask, its dependencies, and most Flask extensions support Python 3.7You should start using Python 3 for your next project,8but there are a few things to be aware of.910If you want to use Flask with Python 3 you will need to use Python 3.3 or11higher. 3.2 and older are *not* supported.10You need to use Python 3.3 or higher. 3.2 and older are *not* supported.1113In addition to that you need to use the latest and greatest versions of14`itsdangerous`, `Jinja2` and `Werkzeug`. Flask 0.10 and Werkzeug 0.9 were15the first versions to introduce Python 3 support.12You should use the latest versions of all Flask-related packages.13Flask 0.10 and Werkzeug 0.9 were the first versions to introduce Python 3 support.1417Some of the decisions made in regards to unicode and byte utilization on18Python 3 make it hard to write low level code. This mainly affects WSGI19middlewares and interacting with the WSGI provided information. Werkzeug20wraps all that information in high-level helpers but some of those were21specifically added for the Python 3 support and are quite new.15Python 3 changed how unicode and bytes are handled, which complicates how low16level code handles HTTP data. This mainly affects WSGI middleware interacting17with the WSGI ``environ`` data. Werkzeug wraps that information in high-level18helpers, so encoding issues should not affect you.1923Unless you require absolute compatibility, you should be fine with Python 324nowadays. Most libraries and Flask extensions have been ported by now and25using Flask with Python 3 is generally a smooth ride. However, keep in mind26that most libraries (including Werkzeug and Flask) might not quite as stable27on Python 3 yet. You might therefore sometimes run into bugs that are28usually encoding-related.2930The majority of the upgrade pain is in the lower-level libraries like31Flask and Werkzeug and not in the actual high-level application code. For32instance all of the Flask examples that are in the Flask repository work33out of the box on both 2.x and 3.x and did not require a single line of34code changed.20The majority of the upgrade work is in the lower-level libraries like21Flask and Werkzeug, not the high-level application code.22For example, all of the examples in the Flask repository work on both Python 2 and 323and did not require a single line of code changed.
modified:docs/quickstart.rst+166 added-207 removed
24 unmodified lines
251. First we imported the :class:`~flask.Flask` class. An instance of this26 class will be our WSGI application.272. 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 lines
364. 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.3940Just save it as :file:`hello.py` (or something similar) and run it with your Python41interpreter. Make sure to not call your application :file:`flask.py` because this42would conflict with Flask itself.40Just save it as :file:`hello.py` or something similar. Make sure to not call41your application :file:`flask.py` because this would conflict with Flask42itself.4344To run the application you can either use the :command:`flask` command or45python's :option:`-m` switch with Flask::45python's ``-m`` switch with Flask. Before you can do that you need46to tell your terminal the application to work with by exporting the47``FLASK_APP`` environment variable::4849 $ export FLASK_APP=hello.py47 $ flask -a hello run50 $ flask run51 * Running on http://127.0.0.1:5000/5250or alternatively::53If you are on Windows, the environment variable syntax depends on command line54interpreter. On Command Prompt::5556 C:\path\to\app>set FLASK_APP=hello.py5758And on PowerShell::5960 PS C:\path\to\app> $env:FLASK_APP = "hello.py"6162Alternatively you can use :command:`python -m flask`::6364 $ export FLASK_APP=hello.py52 $ python -m flask -a hello run65 $ python -m flask run66 * Running on http://127.0.0.1:5000/6768This launches a very simple builtin server, which is good enough for testing69but probably not what you want to use in production. For deployment options see
14 unmodified lines
84 If you have the debugger disabled or trust the users on your network,85 you can make the server publicly available simply by adding86 ``--host=0.0.0.0`` to the command line::8775 flask -a hello run --host=0.0.0.088 flask run --host=0.0.0.08990 This tells your operating system to listen on all public IPs.919293What to do if the Server does not Start94---------------------------------------9583In case the ``python -m flask`` fails or :command:`flask` does not exist,96In case the :command:`python -m flask` fails or :command:`flask` does not exist,97there are multiple reasons this might be the case. First of all you need98to look at the error message.99100Old Version of Flask101````````````````````10290Versions of Flask older than 1.0 use to have different ways to start the103Versions of Flask older than 0.11 use to have different ways to start the104application. In short, the :command:`flask` command did not exist, and92neither did ``python -m flask``. In that case you have two options:105neither did :command:`python -m flask`. In that case you have two options:106either upgrade to newer Flask versions or have a look at the :ref:`server`107docs to see the alternative method for running a server.10896Python older 2.797````````````````9899In case you have a version of Python older than 2.7 ``python -m flask``100does not work. You can either use :command:`flask` or ``python -m101flask.cli`` as an alternative. This is because Python before 2.7 does no102permit packages to act as executable modules. For more information see103:ref:`cli`.104109Invalid Import Name110```````````````````111108The :option:`-a` argument to :command:`flask` is the name of the module to import. In109case that module is incorrectly named you will get an import error upon110start (or if debug is enabled when you navigate to the application). It111will tell you what it tried to import and why it failed.112The ``FLASK_APP`` environment variable is the name of the module to import at113:command:`flask run`. In case that module is incorrectly named you will get an114import error upon start (or if debug is enabled when you navigate to the115application). It will tell you what it tried to import and why it failed.116117The most common reason is a typo or because you did not actually create an118``app`` object.119
1 unmodified line
121122Debug Mode123----------124125(Want to just log errors and stack traces? See :ref:`application-errors`)126127The :command:`flask` script is nice to start a local development server, but128you would have to restart it manually after each change to your code.129That is not very nice and Flask can do better. If you enable debug130support the server will reload itself on code changes, and it will also131provide you with a helpful debugger if things go wrong.132127There are different ways to enable the debug mode. The most obvious one128is the :option:`--debug` parameter to the :command:`flask` command::133To enable debug mode you can export the ``FLASK_DEBUG`` environment variable134before running the server::135130 flask --debug -a hello run136 $ export FLASK_DEBUG=1137 $ flask run138139(On Windows you need to use ``set`` instead of ``export``).140141This does the following things:1421431. it activates the debugger1442. it activates the automatic reloader
14 unmodified lines
159 :align: center160 :class: screenshot161 :alt: screenshot of debugger in action162163More information on using the debugger can be found in the `Werkzeug 164documentation`_.165166.. _Werkzeug documentation: http://werkzeug.pocoo.org/docs/debug/#using-the-debugger167168Have another debugger in mind? See :ref:`working-with-debuggers`.169170171Routing172-------173160Modern web applications have beautiful URLs. This helps people remember161the URLs, which is especially handy for applications that are used from162mobile devices with slower network connections. If the user can directly163go to the desired page without having to hit the index page it is more164likely they will like the page and come back next time.174Modern web applications use meaningful URLs to help users. Users are more175likely to like a page and come back if the page uses a meaningful URL they can176remember and use to directly visit a page.177166As you have seen above, the :meth:`~flask.Flask.route` decorator is used to167bind a function to a URL. Here are some basic examples::178Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::179180 @app.route('/')181 def index():182 return 'Index Page'
1 unmodified line
184 @app.route('/hello')185 def hello():186 return 'Hello, World'187177But there is more to it! You can make certain parts of the URL dynamic and178attach multiple rules to a function.188You can do more! You can make parts of the URL dynamic and attach multiple189rules to a function.190191Variable Rules192``````````````193183To add variable parts to a URL you can mark these special sections as184``<variable_name>``. Such a part is then passed as a keyword argument to your185function. Optionally a converter can be used by specifying a rule with186``<converter:variable_name>``. Here are some nice examples::194You can add variable sections to a URL by marking sections with195``<variable_name>``. Your function then receives the ``<variable_name>``196as a keyword argument. Optionally, you can use a converter to specify the type197of the argument like ``<converter:variable_name>``. ::198199 @app.route('/user/<username>')200 def show_user_profile(username):201 # show the user profile for that user
3 unmodified lines
205 def show_post(post_id):206 # show the post with the given id, the id is an integer207 return 'Post %d' % post_id208198The following converters exist:209 @app.route('/path/<path:subpath>')210 def show_subpath(subpath):211 # show the subpath after /path/212 return 'Subpath %s' % subpath213200=========== ===============================================201`string` accepts any text without a slash (the default)202`int` accepts integers203`float` like `int` but for floating point values204`path` like the default but also accepts slashes205=========== ===============================================214Converter types:215207.. admonition:: Unique URLs / Redirection Behavior216========== ==========================================217``string`` (default) accepts any text without a slash218``int`` accepts positive integers219``float`` accepts positive floating point values220``path`` like ``string`` but also accepts slashes221``uuid`` accepts UUID strings222========== ==========================================223209 Flask's URL rules are based on Werkzeug's routing module. The idea210 behind that module is to ensure beautiful and unique URLs based on211 precedents laid down by Apache and earlier HTTP servers.224Unique URLs / Redirection Behavior225``````````````````````````````````226213 Take these two rules::227Take these two rules::228215 @app.route('/projects/')216 def projects():217 return 'The project page'229 @app.route('/projects/')230 def projects():231 return 'The project page'232219 @app.route('/about')220 def about():221 return 'The about page'233 @app.route('/about')234 def about():235 return 'The about page'236223 Though they look rather similar, they differ in their use of the trailing224 slash in the URL *definition*. In the first case, the canonical URL for the225 `projects` endpoint has a trailing slash. In that sense, it is similar to226 a folder on a filesystem. Accessing it without a trailing slash will cause227 Flask to redirect to the canonical URL with the trailing slash.237Though they look similar, they differ in their use of the trailing slash in238the URL. In the first case, the canonical URL for the ``projects`` endpoint239uses a trailing slash. It's similar to a folder in a file system; if you240access the URL without a trailing slash, Flask redirects you to the241canonical URL with the trailing slash.242229 In the second case, however, the URL is defined without a trailing slash,230 rather like the pathname of a file on UNIX-like systems. Accessing the URL231 with a trailing slash will produce a 404 "Not Found" error.243In the second case, however, the URL definition lacks a trailing slash,244like the pathname of a file on UNIX-like systems. Accessing the URL with a245trailing slash produces a 404 “Not Found” error.246233 This behavior allows relative URLs to continue working even if the trailing234 slash is omitted, consistent with how Apache and other servers work. Also,235 the URLs will stay unique, which helps search engines avoid indexing the236 same page twice.247This behavior allows relative URLs to continue working even if the trailing248slash is omitted, consistent with how Apache and other servers work. Also,249the URLs will stay unique, which helps search engines avoid indexing the250same page twice.251238252.. _url-building:253254URL Building255````````````256244If it can match URLs, can Flask also generate them? Of course it can. To245build a URL to a specific function you can use the :func:`~flask.url_for`246function. It accepts the name of the function as first argument and a number247of keyword arguments, each corresponding to the variable part of the URL rule.248Unknown variable parts are appended to the URL as query parameters. Here are249some examples:257To build a URL to a specific function, use the :func:`~flask.url_for` function.258It accepts the name of the function as its first argument and any number of259keyword arguments, each corresponding to a variable part of the URL rule.260Unknown variable parts are appended to the URL as query parameters.261251>>> from flask import Flask, url_for252>>> app = Flask(__name__)253>>> @app.route('/')254... def index(): pass255...256>>> @app.route('/login')257... def login(): pass258...259>>> @app.route('/user/<username>')260... def profile(username): pass261...262>>> with app.test_request_context():263... print url_for('index')264... print url_for('login')265... print url_for('login', next='/')266... print url_for('profile', username='John Doe')267...268/269/login270/login?next=/271/user/John%20Doe272273(This also uses the :meth:`~flask.Flask.test_request_context` method, explained274below. It tells Flask to behave as though it is handling a request, even275though we are interacting with it through a Python shell. Have a look at the276explanation below. :ref:`context-locals`).277262Why would you want to build URLs using the URL reversing function263:func:`~flask.url_for` instead of hard-coding them into your templates?280There are three good reasons for this:2642821. Reversing is often more descriptive than hard-coding the URLs. More283 importantly, it allows you to change URLs in one go, without having to284 remember to change URLs all over the place.2852. URL building will handle escaping of special characters and Unicode286 data transparently for you, so you don't have to deal with them.2873. If your application is placed outside the URL root (say, in288 ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will handle289 that properly for you.2651. Reversing is often more descriptive than hard-coding the URLs.2662. You can change your URLs in one go instead of needing to remember to267 manually change hard-coded URLs.2683. URL building handles escaping of special characters and Unicode data269 transparently.2704. If your application is placed outside the URL root, for example, in271 ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly272 handles that for you.273274For example, here we use the :meth:`~flask.Flask.test_request_context` method275to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`276tells Flask to behave as though it's handling a request even while we use a277Python shell. See :ref:`context-locals`. ::278279 from flask import Flask, url_for280281 app = Flask(__name__)282283 @app.route('/')284 def index():285 return 'index'286287 @app.route('/login')288 def login():289 return 'login'290291 @app.route('/user/<username>')292 def profile(username):293 return '{}'s profile'.format(username)294295 with app.test_request_context():296 print(url_for('index'))297 print(url_for('login'))298 print(url_for('login', next='/'))299 print(url_for('profile', username='John Doe'))300301 /302 /login303 /login?next=/304 /user/John%20Doe305306HTTP Methods307````````````308295HTTP (the protocol web applications are speaking) knows different methods for296accessing URLs. By default, a route only answers to ``GET`` requests, but that297can be changed by providing the `methods` argument to the298:meth:`~flask.Flask.route` decorator. Here are some examples::309Web applications use different HTTP methods when accessing URLs. You should310familiarize yourself with the HTTP methods as you work with Flask. By default,311a route only answers to ``GET`` requests. You can use the ``methods`` argument312of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.313::314300 from flask import request301315 @app.route('/login', methods=['GET', 'POST'])316 def login():317 if request.method == 'POST':318 do_the_login()319 else:320 show_the_login_form()321309If ``GET`` is present, ``HEAD`` will be added automatically for you. You310don't have to deal with that. It will also make sure that ``HEAD`` requests311are handled as the `HTTP RFC`_ (the document describing the HTTP312protocol) demands, so you can completely ignore that part of the HTTP313specification. Likewise, as of Flask 0.6, ``OPTIONS`` is implemented for you314automatically as well.322If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method323and handles ``HEAD`` requests according to the the `HTTP RFC`_. Likewise,324``OPTIONS`` is automatically implemented for you.325316You have no idea what an HTTP method is? Worry not, here is a quick317introduction to HTTP methods and why they matter:326.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt327319The HTTP method (also often called "the verb") tells the server what the320clients wants to *do* with the requested page. The following methods are321very common:322323``GET``324 The browser tells the server to just *get* the information stored on325 that page and send it. This is probably the most common method.326327``HEAD``328 The browser tells the server to get the information, but it is only329 interested in the *headers*, not the content of the page. An330 application is supposed to handle that as if a ``GET`` request was331 received but to not deliver the actual content. In Flask you don't332 have to deal with that at all, the underlying Werkzeug library handles333 that for you.334335``POST``336 The browser tells the server that it wants to *post* some new337 information to that URL and that the server must ensure the data is338 stored and only stored once. This is how HTML forms usually339 transmit data to the server.340341``PUT``342 Similar to ``POST`` but the server might trigger the store procedure343 multiple times by overwriting the old values more than once. Now you344 might be asking why this is useful, but there are some good reasons345 to do it this way. Consider that the connection is lost during346 transmission: in this situation a system between the browser and the347 server might receive the request safely a second time without breaking348 things. With ``POST`` that would not be possible because it must only349 be triggered once.350351``DELETE``352 Remove the information at the given location.353354``OPTIONS``355 Provides a quick way for a client to figure out which methods are356 supported by this URL. Starting with Flask 0.6, this is implemented357 for you automatically.358359Now the interesting part is that in HTML4 and XHTML1, the only methods a360form can submit to the server are ``GET`` and ``POST``. But with JavaScript361and future HTML standards you can use the other methods as well. Furthermore362HTTP has become quite popular lately and browsers are no longer the only363clients that are using HTTP. For instance, many revision control systems364use it.365366.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt367328Static Files329------------330331Dynamic web applications also need static files. That's usually where
69 unmodified lines
401know how that works, head over to the :ref:`template-inheritance` pattern402documentation. Basically template inheritance makes it possible to keep403certain elements on each page (like header, navigation and footer).404445Automatic escaping is enabled, so if `name` contains HTML it will be escaped405Automatic escaping is enabled, so if ``name`` contains HTML it will be escaped406automatically. If you can trust a variable and you know that it will be407safe HTML (for example because it came from a module that converts wiki408markup to HTML) you can mark it as safe by using the409:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the410template. Head over to the Jinja 2 documentation for more examples.411452Here is a basic introduction to how the :class:`~jinja2.Markup` class works:412Here is a basic introduction to how the :class:`~jinja2.Markup` class works::413454>>> from flask import Markup455>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'456Markup(u'<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')457>>> Markup.escape('<blink>hacker</blink>')458Markup(u'&lt;blink&gt;hacker&lt;/blink&gt;')459>>> Markup('<em>Marked up</em> &raquo; HTML').striptags()460u'Marked up \xbb HTML'414 >>> from flask import Markup415 >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'416 Markup(u'<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')417 >>> Markup.escape('<blink>hacker</blink>')418 Markup(u'&lt;blink&gt;hacker&lt;/blink&gt;')419 >>> Markup('<em>Marked up</em> &raquo; HTML').striptags()420 u'Marked up \xbb HTML'421422.. versionchanged:: 0.5423424 Autoescaping is no longer enabled for all templates. The following
68 unmodified lines
493The Request Object494``````````````````495496The request object is documented in the API section and we will not cover537it here in detail (see :class:`~flask.request`). Here is a broad overview of497it here in detail (see :class:`~flask.Request`). Here is a broad overview of498some of the most common operations. First of all you have to import it from539the `flask` module::499the ``flask`` module::500501 from flask import request502503The current request method is available by using the544:attr:`~flask.request.method` attribute. To access form data (data504:attr:`~flask.Request.method` attribute. To access form data (data505transmitted in a ``POST`` or ``PUT`` request) you can use the546:attr:`~flask.request.form` attribute. Here is a full example of the two506:attr:`~flask.Request.form` attribute. Here is a full example of the two507attributes mentioned above::508509 @app.route('/login', methods=['POST', 'GET'])510 def login():
7 unmodified lines
518 # the code below is executed if the request method519 # was GET or the credentials were invalid520 return render_template('login.html', error=error)521562What happens if the key does not exist in the `form` attribute? In that522What happens if the key does not exist in the ``form`` attribute? In that523case a special :exc:`KeyError` is raised. You can catch it like a524standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request525error page is shown instead. So for many situations you don't have to526deal with that problem.527528To access parameters submitted in the URL (``?key=value``) you can use the569:attr:`~flask.request.args` attribute::529:attr:`~flask.Request.args` attribute::530531 searchword = request.args.get('key', '')532533We recommend accessing URL parameters with `get` or by catching the534:exc:`KeyError` because users might change the URL and presenting them a 400535bad request page in that case is not user friendly.536537For a full list of methods and attributes of the request object, head over578to the :class:`~flask.request` documentation.538to the :class:`~flask.Request` documentation.539540541File Uploads542````````````
137 unmodified lines
680 default parameters.6813. If a tuple is returned the items in the tuple can provide extra682 information. Such tuples have to be in the form ``(response, status,683 headers)`` or ``(response, headers)`` where at least one item has724 to be in the tuple. The `status` value will override the status code725 and `headers` can be a list or dictionary of additional header values.684 to be in the tuple. The ``status`` value will override the status code685 and ``headers`` can be a list or dictionary of additional header values.6864. If none of that works, Flask will assume the return value is a687 valid WSGI application and convert that into a response object.688689If you want to get hold of the resulting response object inside the view690you can use the :func:`~flask.make_response` function.691732Imagine you have a view like this:692Imagine you have a view like this::693734.. sourcecode:: python735694 @app.errorhandler(404)695 def not_found(error):696 return render_template('error.html'), 404697698You just need to wrap the return expression with699:func:`~flask.make_response` and get the response object to modify it, then742return it:700return it::701744.. sourcecode:: python745702 @app.errorhandler(404)703 def not_found(error):704 resp = make_response(render_template('error.html'), 404)705 resp.headers['X-Something'] = 'A value'
29 unmodified lines
735 if request.method == 'POST':736 session['username'] = request.form['username']737 return redirect(url_for('index'))738 return '''783 <form action="" method="post">739 <form method="post">740 <p><input type=text name=username>741 <p><input type=submit value=Login>742 </form>743 '''
14 unmodified lines
758759 The problem with random is that it's hard to judge what is truly random. And760 a secret key should be as random as possible. Your operating system761 has ways to generate pretty random stuff based on a cryptographic806 random generator which can be used to get such a key:762 random generator which can be used to get such a key::763808 >>> import os809 >>> os.urandom(24)810 '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'764 >>> import os765 >>> os.urandom(24)766 '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'767812 Just take that thing and copy/paste it into your code and you're done.768 Just take that thing and copy/paste it into your code and you're done.769770A note on cookie-based sessions: Flask will take the values you put into the771session object and serialize them into a cookie. If you are finding some772values do not persist across requests, cookies are indeed enabled, and you are773not getting a clear error message, check the size of the cookie in your page774responses compared to the size supported by web browsers.775776Besides the default client-side based sessions, if you want to handle777sessions on the server-side instead, there are several778Flask extensions that support this.779780Message Flashing781----------------782
67 unmodified lines
modified:docs/reqcontext.rst+9 added-8 removed
67 unmodified lines
68 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)7576The method :meth:`~Flask.request_context` returns a new
41 unmodified lines
118 unhandled exception down the road or if a before-request handler was119 not executed yet or at all (for example in test environments sometimes120 you might want to not execute before-request callbacks).121122Now what happens on errors? In production mode if an exception is not123caught, the 500 internal server handler is called. In development mode124however the exception is not further processed and bubbles up to the WSGI122Now what happens on errors? If you are not in debug mode and an exception is not 123caught, the 500 internal server handler is called. In debug mode 124however the exception is not further processed and bubbles up to the WSGI 125server. That way things like the interactive debugger can provide helpful126debug information.127128An important change in 0.7 is that the internal server error is now no
84 unmodified lines
213214Starting with Flask 0.7 you have finer control over that behavior by215setting the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable. By216default it's linked to the setting of ``DEBUG``. If the application is in217debug mode the context is preserved, in production mode it's not.217debug mode the context is preserved. If debug mode is set to off, the context218is not preserved.219219Do not force activate ``PRESERVE_CONTEXT_ON_EXCEPTION`` in production mode220as it will cause your application to leak memory on exceptions. However220Do not force activate ``PRESERVE_CONTEXT_ON_EXCEPTION`` if debug mode is set to off221as it will cause your application to leak memory on exceptions. However,222it can be useful during development to get the same error preserving222behavior as in development mode when attempting to debug an error that223behavior as debug mode when attempting to debug an error that224only occurs under production settings.
modified:docs/security.rst+10 added-79 removed
13 unmodified lines
14it JavaScript) into the context of a website. To remedy this, developers15have to properly escape text so that it cannot include arbitrary HTML16tags. For more information on that have a look at the Wikipedia article17on `Cross-Site Scripting18<http://en.wikipedia.org/wiki/Cross-site_scripting>`_.18<https://en.wikipedia.org/wiki/Cross-site_scripting>`_.1920Flask configures Jinja2 to automatically escape all values unless21explicitly told otherwise. This should rule out all XSS problems caused22in templates, but there are still other places where you have to be
49 unmodified lines
7273Say you have a specific URL that, when you sent ``POST`` requests to will74delete a user's profile (say ``http://example.com/user/delete``). If an75attacker now creates a page that sends a post request to that page with76some JavaScript they just has to trick some users to load that page and76some JavaScript they just have to trick some users to load that page and77their profiles will end up being deleted.7879Imagine you were to run Facebook with millions of concurrent users and80someone would send out links to images of little kittens. When users
13 unmodified lines
9495JSON Security96-------------9798.. admonition:: ECMAScript 5 Changes98In Flask 0.10 and lower, :func:`~flask.jsonify` did not serialize top-level99arrays to JSON. This was because of a security vulnerability in ECMAScript 4.100100 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.104105JSON itself is a high-level serialization format, so there is barely106anything that could cause security problems, right? You can't declare107recursive structures that could cause problems and the only thing that108could possibly break are very large responses that can cause some kind of109denial of service at the receiver's side.110111However there is a catch. Due to how browsers work the CSRF issue comes112up with JSON unfortunately. Fortunately there is also a weird part of the113JavaScript specification that can be used to solve that problem easily and114Flask is kinda doing that for you by preventing you from doing dangerous115stuff. Unfortunately that protection is only there for116:func:`~flask.jsonify` so you are still at risk when using other ways to117generate JSON.118119So what is the issue and how to avoid it? The problem are arrays at120top-level in JSON. Imagine you send the following data out in a JSON121request. Say that's exporting the names and email addresses of all your122friends for a part of the user interface that is written in JavaScript.123Not very uncommon:124125.. sourcecode:: javascript126127 [128 {"username": "admin",129 "email": "admin@localhost"}130 ]131132And it is doing that of course only as long as you are logged in and only133for you. And it is doing that for all ``GET`` requests to a certain URL,134say the URL for that request is135``http://example.com/api/get_friends.json``.136137So now what happens if a clever hacker is embedding this to his website138and social engineers a victim to visiting his site:139140.. sourcecode:: html141142 <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>160161If you know a bit of JavaScript internals you might know that it's162possible to patch constructors and register callbacks for setters. An163attacker can use this (like above) to get all the data you exported in164your JSON file. The browser will totally ignore the :mimetype:`application/json`165mimetype if :mimetype:`text/javascript` is defined as content type in the script166tag and evaluate that as JavaScript. Because top-level array elements are167allowed (albeit useless) and we hooked in our own constructor, after that168page loaded the data from the JSON response is in the `captured` array.169170Because it is a syntax error in JavaScript to have an object literal171(``{...}``) toplevel an attacker could not just do a request to an172external URL with the script tag to load up the data. So what Flask does173is to only allow objects as toplevel elements when using174:func:`~flask.jsonify`. Make sure to do the same when using an ordinary175JSON generate function.101ECMAScript 5 closed this vulnerability, so only extremely old browsers are102still vulnerable. All of these browsers have `other more serious103vulnerabilities104<https://github.com/pallets/flask/issues/248#issuecomment-59934857>`_, so105this behavior was changed and :func:`~flask.jsonify` now supports serializing106arrays.
modified:docs/server.rst+10 added-8 removed
3 unmodified lines
4==================56.. currentmodule:: flask78Starting with Flask 1.0 there are multiple built-in ways to run a8Starting with Flask 0.11 there are multiple built-in ways to run a9development server. The best one is the :command:`flask` command line utility10but you can also continue using the :meth:`Flask.run` method.1112Command Line
2 unmodified lines
15The :command:`flask` command line script (:ref:`cli`) is strongly recommended for16development because it provides a superior reload experience due to how it17loads the application. The basic usage is like this::1819 $ flask -a my_application --debug run19 $ export FLASK_APP=my_application20 $ export FLASK_DEBUG=121 $ flask run2223This will enable the debugger, the reloader and then start the server on24*http://localhost:5000/*.2526The individual features of the server can be controlled by passing more27arguments to the ``run`` option. For instance the reloader can be28disabled::2928 $ flask -a my_application --debug run --no-reload30 $ flask run --no-reload3132In Code33-------34
6 unmodified lines
41 if __name__ == '__main__':42 app.run()4344This works well for the common case but it does not work well for43development which is why from Flask 1.0 onwards the :command:`flask` method is44recommended. The reason for this is that due to how the reload mechanism45works there are some bizarre side-effects (like executing certain code46twice, sometimes crashing without message or dying when a syntax or47import error happens).45development which is why from Flask 0.11 onwards the :command:`flask`46method is recommended. The reason for this is that due to how the reload47mechanism works there are some bizarre side-effects (like executing48certain code twice, sometimes crashing without message or dying when a49syntax or import error happens).5051It is however still a perfectly valid method for invoking a non automatic52reloading application.
modified:docs/shell.rst+1 added-1 removed
27 unmodified lines
2829Command Line Interface30----------------------3132Starting with Flask 1.0 the recommended way to work with the shell is the32Starting 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.34For instance the shell is automatically initialized with a loaded35application context.36
67 unmodified lines
modified:docs/signals.rst+6 added-168 removed
17 unmodified lines
18more. Also keep in mind that signals are intended to notify subscribers19and should not encourage subscribers to modify data. You will notice that20there are signals that appear to do the same thing like some of the21builtin decorators do (eg: :data:`~flask.request_started` is very similar22to :meth:`~flask.Flask.before_request`). There are however difference in23how they work. The core :meth:`~flask.Flask.before_request` handler for24example is executed in a specific order and is able to abort the request22to :meth:`~flask.Flask.before_request`). However, there are differences in23how they work. The core :meth:`~flask.Flask.before_request` handler, for24example, is executed in a specific order and is able to abort the request25early by returning a response. In contrast all signal handlers are26executed in undefined order and do not modify any data.2728The big advantage of signals over handlers is that you can safely29subscribe to them for just a split second. These temporary30subscriptions are helpful for unittesting for example. Say you want to30subscriptions are helpful for unit testing for example. Say you want to31know what templates were rendered as part of a request: signals allow you32to do exactly that.3334Subscribing to Signals
9 unmodified lines
44signal. When you subscribe to a signal, be sure to also provide a sender45unless you really want to listen for signals from all applications. This is46especially true if you are developing an extension.4748For example, here is a helper context manager that can be used in a unittest48For example, here is a helper context manager that can be used in a unit test49to determine which templates were rendered and what variables were passed50to the template::5152 from flask import template_rendered
130 unmodified lines
183184Core Signals185------------186187.. when modifying this list, also update the one in api.rst187Take a look at :ref:`core-signals-list` for a list of all builtin signals.188189The following signals exist in Flask:189191.. data:: flask.template_rendered192 :noindex:193194 This signal is sent when a template was successfully rendered. The195 signal is invoked with the instance of the template as `template`196 and the context as dictionary (named `context`).197198 Example subscriber::199200 def log_template_renders(sender, template, context, **extra):201 sender.logger.debug('Rendering template "%s" with context %s',202 template.name or 'string template',203 context)204205 from flask import template_rendered206 template_rendered.connect(log_template_renders, app)207208.. data:: flask.request_started209 :noindex:210211 This signal is sent when the request context is set up, before212 any request processing happens. Because the request context is already213 bound, the subscriber can access the request with the standard global214 proxies such as :class:`~flask.request`.215216 Example subscriber::217218 def log_request(sender, **extra):219 sender.logger.debug('Request context is set up')220221 from flask import request_started222 request_started.connect(log_request, app)223224.. data:: flask.request_finished225 :noindex:226227 This signal is sent right before the response is sent to the client.228 It is passed the response to be sent named `response`.229230 Example subscriber::231232 def log_response(sender, response, **extra):233 sender.logger.debug('Request context is about to close down. '234 'Response: %s', response)235236 from flask import request_finished237 request_finished.connect(log_response, app)238239.. data:: flask.got_request_exception240 :noindex:241242 This signal is sent when an exception happens during request processing.243 It is sent *before* the standard exception handling kicks in and even244 in debug mode, where no exception handling happens. The exception245 itself is passed to the subscriber as `exception`.246247 Example subscriber::248249 def log_exception(sender, exception, **extra):250 sender.logger.debug('Got exception during processing: %s', exception)251252 from flask import got_request_exception253 got_request_exception.connect(log_exception, app)254255.. data:: flask.request_tearing_down256 :noindex:257258 This signal is sent when the request is tearing down. This is always259 called, even if an exception is caused. Currently functions listening260 to this signal are called after the regular teardown handlers, but this261 is not something you can rely on.262263 Example subscriber::264265 def close_db_connection(sender, **extra):266 session.close()267268 from flask import request_tearing_down269 request_tearing_down.connect(close_db_connection, app)270271 As of Flask 0.9, this will also be passed an `exc` keyword argument272 that has a reference to the exception that caused the teardown if273 there was one.274275.. data:: flask.appcontext_tearing_down276 :noindex:277278 This signal is sent when the app context is tearing down. This is always279 called, even if an exception is caused. Currently functions listening280 to this signal are called after the regular teardown handlers, but this281 is not something you can rely on.282283 Example subscriber::284285 def close_db_connection(sender, **extra):286 session.close()287288 from flask import appcontext_tearing_down289 appcontext_tearing_down.connect(close_db_connection, app)290291 This will also be passed an `exc` keyword argument that has a reference292 to the exception that caused the teardown if there was one.293294.. data:: flask.appcontext_pushed295 :noindex:296297 This signal is sent when an application context is pushed. The sender298 is the application. This is usually useful for unittests in order to299 temporarily hook in information. For instance it can be used to300 set a resource early onto the `g` object.301302 Example usage::303304 from contextlib import contextmanager305 from flask import appcontext_pushed306307 @contextmanager308 def user_set(app, user):309 def handler(sender, **kwargs):310 g.user = user311 with appcontext_pushed.connected_to(handler, app):312 yield313314 And in the testcode::315316 def test_user_me(self):317 with user_set(app, 'john'):318 c = app.test_client()319 resp = c.get('/users/me')320 assert resp.data == 'username=john'321322 .. versionadded:: 0.10323324.. data:: flask.appcontext_popped325 :noindex:326327 This signal is sent when an application context is popped. The sender328 is the application. This usually falls in line with the329 :data:`appcontext_tearing_down` signal.330331 .. versionadded:: 0.10332333334.. data:: flask.message_flashed335 :noindex:336337 This signal is sent when the application is flashing a message. The338 messages is sent as `message` keyword argument and the category as339 `category`.340341 Example subscriber::342343 recorded = []344 def record(sender, message, category, **extra):345 recorded.append((message, category))346347 from flask import message_flashed348 message_flashed.connect(record, app)349350 .. versionadded:: 0.10351190.. _blinker: https://pypi.python.org/pypi/blinker
modified:docs/styleguide.rst+1 added-1 removed
165 unmodified lines
166 is on its own line.167 """168169Module header:170 The module header consists of an utf-8 encoding declaration (if non170 The module header consists of a utf-8 encoding declaration (if non171 ASCII letters are used, but it is recommended all the time) and a172 standard docstring::173174 # -*- coding: utf-8 -*-
26 unmodified lines
modified:docs/templating.rst+5 added-2 removed
16 unmodified lines
1718Unless customized, Jinja2 is configured by Flask as follows:1920- autoescaping is enabled for all templates ending in ``.html``,21 ``.htm``, ``.xml`` as well as ``.xhtml``21 ``.htm``, ``.xml`` as well as ``.xhtml`` when using22 :func:`~flask.templating.render_template`.23- autoescaping is enabled for all strings when using24 :func:`~flask.templating.render_template_string`.25- a template has the ability to opt in/out autoescaping with the26 ``{% autoescape %}`` tag.27- Flask inserts a couple of global functions and helpers into the28 Jinja2 context, additionally to the values that are present by
102 unmodified lines
131:ref:`xss`)132133Sometimes however you will need to disable autoescaping in templates.134This can be the case if you want to explicitly inject HTML into pages, for132example if they come from a system that generate secure HTML like a135example if they come from a system that generates secure HTML like a136markdown to HTML converter.137138There are three ways to accomplish that:139
86 unmodified lines
modified:docs/testing.rst+120 added-98 removed
3 unmodified lines
4==========================56 **Something that is untested is broken.**78The origin of this quote is unknown and while it is not entirely correct, it is also9not far from the truth. Untested applications make it hard to8The origin of this quote is unknown and while it is not entirely correct, it9is also not far from the truth. Untested applications make it hard to10improve existing code and developers of untested applications tend to11become pretty paranoid. If an application has automated tests, you can12safely make changes and instantly know if anything breaks.1314Flask provides a way to test your application by exposing the Werkzeug15test :class:`~werkzeug.test.Client` and handling the context locals for you.16You can then use that with your favourite testing solution. In this documentation17we will use the :mod:`unittest` package that comes pre-installed with Python.16You can then use that with your favourite testing solution.1718In this documentation we will use the `pytest`_ package as the base19framework for our tests. You can install it with ``pip``, like so::2021 pip install pytest2223.. _pytest:24 https://pytest.org2526The Application27---------------2829First, we need an application to test; we will use the application from30the :ref:`tutorial`. If you don't have that application yet, get the24sources from `the examples`_.31source code from `the examples`_.3233.. _the examples:27 https://github.com/mitsuhiko/flask/tree/master/examples/flaskr/34 https://github.com/pallets/flask/tree/master/examples/flaskr/3536The Testing Skeleton37--------------------3832In order to test the application, we add a second module33(:file:`flaskr_tests.py`) and create a unittest skeleton there::39We begin by adding a tests directory under the application root. Then40create a Python file to store our tests (:file:`test_flaskr.py`). When we41format the filename like ``test_*.py``, it will be auto-discoverable by42pytest.4344Next, we create a `pytest fixture`_ called45:func:`client` that configures46the application for testing and initializes a new database.::4748 import os36 import flaskr37 import unittest49 import tempfile5040 class FlaskrTestCase(unittest.TestCase):51 import pytest5242 def setUp(self):43 self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()44 flaskr.app.config['TESTING'] = True45 self.app = flaskr.app.test_client()46 with flaskr.app.app_context():47 flaskr.init_db()53 from flaskr import flaskr5449 def tearDown(self):50 os.close(self.db_fd)51 os.unlink(flaskr.app.config['DATABASE'])5553 if __name__ == '__main__':54 unittest.main()56 @pytest.fixture57 def client():58 db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()59 flaskr.app.config['TESTING'] = True60 client = flaskr.app.test_client()6156The code in the :meth:`~unittest.TestCase.setUp` method creates a new test57client and initializes a new database. This function is called before58each individual test function is run. To delete the database after the59test, we close the file and remove it from the filesystem in the60:meth:`~unittest.TestCase.tearDown` method. Additionally during setup the61``TESTING`` config flag is activated. What it does is disable the error62catching during request handling so that you get better error reports when63performing test requests against the application.62 with flaskr.app.app_context():63 flaskr.init_db()6465This test client will give us a simple interface to the application. We can66trigger test requests to the application, and the client will also keep track67of cookies for us.65 yield client6667 os.close(db_fd)68 os.unlink(flaskr.app.config['DATABASE'])6970This client fixture will be called by each individual test. It gives us a71simple interface to the application, where we can trigger test requests to the72application. The client will also keep track of cookies for us.7374During setup, the ``TESTING`` config flag is activated. What75this does is disable error catching during request handling, so that76you get better error reports when performing test requests against the77application.7869Because SQLite3 is filesystem-based we can easily use the tempfile module79Because SQLite3 is filesystem-based, we can easily use the :mod:`tempfile` module80to create a temporary database and initialize it. The81:func:`~tempfile.mkstemp` function does two things for us: it returns a82low-level file handle and a random file name, the latter we use as83database name. We just have to keep the `db_fd` around so that we can use84the :func:`os.close` function to close the file.8586To delete the database after the test, the fixture closes the file and removes87it from the filesystem.8889If we now run the test suite, we should see the following output::9078 $ python flaskr_tests.py91 $ pytest9280 ----------------------------------------------------------------------81 Ran 0 tests in 0.000s93 ================ test session starts ================94 rootdir: ./flask/examples/flaskr, inifile: setup.cfg95 collected 0 items9683 OK97 =========== no tests ran in 0.07 seconds ============9885Even though it did not run any actual tests, we already know that our flaskr99Even though it did not run any actual tests, we already know that our ``flaskr``100application is syntactically valid, otherwise the import would have died101with an exception.102103.. _pytest fixture:104 https://docs.pytest.org/en/latest/fixture.html105106The First Test107--------------108109Now it's time to start testing the functionality of the application.110Let's check that the application shows "No entries here so far" if we94access the root of the application (``/``). To do this, we add a new95test method to our class, like this::111access the root of the application (``/``). To do this, we add a new112test function to :file:`test_flaskr.py`, like this::11397 class FlaskrTestCase(unittest.TestCase):114 def test_empty_db(client):115 """Start with a blank database."""11699 def setUp(self):100 self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()101 self.app = flaskr.app.test_client()102 flaskr.init_db()117 rv = client.get('/')118 assert b'No entries here so far' in rv.data119104 def tearDown(self):105 os.close(self.db_fd)106 os.unlink(flaskr.app.config['DATABASE'])107108 def test_empty_db(self):109 rv = self.app.get('/')110 assert b'No entries here so far' in rv.data111120Notice that our test functions begin with the word `test`; this allows113:mod:`unittest` to automatically identify the method as a test to run.121`pytest`_ to automatically identify the function as a test to run.122115By using `self.app.get` we can send an HTTP ``GET`` request to the application with123By using ``client.get`` we can send an HTTP ``GET`` request to the application with124the given path. The return value will be a :class:`~flask.Flask.response_class` object.125We can now use the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect126the return value (as string) from the application. In this case, we ensure that127``'No entries here so far'`` is part of the output.128129Run it again and you should see one passing test::130123 $ python flaskr_tests.py124 .125 ----------------------------------------------------------------------126 Ran 1 test in 0.034s131 $ pytest -v132128 OK133 ================ test session starts ================134 rootdir: ./flask/examples/flaskr, inifile: setup.cfg135 collected 1 items136137 tests/test_flaskr.py::test_empty_db PASSED138139 ============= 1 passed in 0.10 seconds ==============140141Logging In and Out142------------------143144The majority of the functionality of our application is only available for
1 unmodified line
146of the application. To do this, we fire some requests to the login and logout147pages with the required form data (username and password). And because the148login and logout pages redirect, we tell the client to `follow_redirects`.149139Add the following two methods to your `FlaskrTestCase` class::150Add the following two functions to your :file:`test_flaskr.py` file::151141 def login(self, username, password):142 return self.app.post('/login', data=dict(143 username=username,144 password=password145 ), follow_redirects=True)152 def login(client, username, password):153 return client.post('/login', data=dict(154 username=username,155 password=password156 ), follow_redirects=True)157147 def logout(self):148 return self.app.get('/logout', follow_redirects=True)158159 def logout(client):160 return client.get('/logout', follow_redirects=True)161162Now we can easily test that logging in and out works and that it fails with151invalid credentials. Add this new test to the class::163invalid credentials. Add this new test function::164153 def test_login_logout(self):154 rv = self.login('admin', 'default')155 assert 'You were logged in' in rv.data156 rv = self.logout()157 assert 'You were logged out' in rv.data158 rv = self.login('adminx', 'default')159 assert 'Invalid username' in rv.data160 rv = self.login('admin', 'defaultx')161 assert 'Invalid password' in rv.data165 def test_login_logout(client):166 """Make sure login and logout works."""167168 rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])169 assert b'You were logged in' in rv.data170171 rv = logout(client)172 assert b'You were logged out' in rv.data173174 rv = login(client, flaskr.app.config['USERNAME'] + 'x', flaskr.app.config['PASSWORD'])175 assert b'Invalid username' in rv.data176177 rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'] + 'x')178 assert b'Invalid password' in rv.data179180Test Adding Messages181--------------------182166We should also test that adding messages works. Add a new test method183We should also test that adding messages works. Add a new test function184like this::185169 def test_messages(self):170 self.login('admin', 'default')171 rv = self.app.post('/add', data=dict(186 def test_messages(client):187 """Test that messages work."""188189 login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])190 rv = client.post('/add', data=dict(191 title='<Hello>',192 text='<strong>HTML</strong> allowed here'193 ), follow_redirects=True)175 assert 'No entries here so far' not in rv.data176 assert '&lt;Hello&gt;' in rv.data177 assert '<strong>HTML</strong> allowed here' in rv.data194 assert b'No entries here so far' not in rv.data195 assert b'&lt;Hello&gt;' in rv.data196 assert b'<strong>HTML</strong> allowed here' in rv.data197198Here we check that HTML is allowed in the text but not in the title,199which is the intended behavior.200201Running that should now give us three passing tests::202184 $ python flaskr_tests.py185 ...186 ----------------------------------------------------------------------187 Ran 3 tests in 0.332s203 $ pytest -v204189 OK205 ================ test session starts ================206 rootdir: ./flask/examples/flaskr, inifile: setup.cfg207 collected 3 items208209 tests/test_flaskr.py::test_empty_db PASSED210 tests/test_flaskr.py::test_login_logout PASSED211 tests/test_flaskr.py::test_messages PASSED212213 ============= 3 passed in 0.23 seconds ==============214215For more complex tests with headers and status codes, check out the216`MiniTwit Example`_ from the sources which contains a larger test217suite.218195219.. _MiniTwit Example:197 https://github.com/mitsuhiko/flask/tree/master/examples/minitwit/220 https://github.com/pallets/flask/tree/master/examples/minitwit/221199222Other Testing Tricks223--------------------224225Besides using the test client as shown above, there is also the
3 unmodified lines
229:class:`~flask.g` and :class:`~flask.session` objects like in view230functions. Here is a full example that demonstrates this approach::231232 import flask211 233234 app = flask.Flask(__name__)235236 with app.test_request_context('/?name=Peter'):237 assert flask.request.path == '/'
6 unmodified lines
244there does not seem to be a good way to do that, consider switching to245application factories (see :ref:`app-factories`).246247Note however that if you are using a test request context, the226:meth:`~flask.Flask.before_request` functions are not automatically called227same for :meth:`~flask.Flask.after_request` functions. However248:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`249functions are not called automatically. However250:meth:`~flask.Flask.teardown_request` functions are indeed executed when251the test request context leaves the ``with`` block. If you do want the252:meth:`~flask.Flask.before_request` functions to be called as well, you253need to call :meth:`~flask.Flask.preprocess_request` yourself::
41 unmodified lines
295 g.user = user296 return user297298For a test it would be nice to override this user from the outside without277having to change some code. This can trivially be accomplished with299having to change some code. This can be accomplished with300hooking the :data:`flask.appcontext_pushed` signal::301302 from contextlib import contextmanager303 from flask import appcontext_pushed, g
74 unmodified lines
modified:docs/upgrading.rst+92 added-19 removed
12 unmodified lines
13This section of the documentation enumerates all the changes in Flask from14release to release and how you can change your code to have a painless15updating experience.1617If you want to use the :command:`easy_install` command to upgrade your Flask18installation, make sure to pass it the :option:`-U` parameter::17Use the :command:`pip` command to upgrade your existing Flask installation by18providing the ``--upgrade`` parameter::1920 $ easy_install -U Flask20 $ pip install --upgrade Flask2122.. _upgrading-to-10:22.. _upgrading-to-012:2324Version 1.025-----------24Version 0.1225------------2627Changes to send_file28````````````````````2930The ``filename`` is no longer automatically inferred from file-like objects.31This means that the following code will no longer automatically have32``X-Sendfile`` support, etag generation or MIME-type guessing::3334 response = send_file(open('/path/to/file.txt'))3536Any of the following is functionally equivalent::3738 fname = '/path/to/file.txt'3940 # Just pass the filepath directly41 response = send_file(fname)4243 # Set the MIME-type and ETag explicitly44 response = send_file(open(fname), mimetype='text/plain')45 response.set_etag(...)4647 # 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(...)5152The reason for this is that some file-like objects have an invalid or even53misleading ``name`` attribute. Silently swallowing errors in such cases was not54a satisfying solution.5556Additionally the default of falling back to ``application/octet-stream`` has57been restricted. If Flask can't guess one or the user didn't provide one, the58function fails if no filename information was provided.5960.. _upgrading-to-011:6162Version 0.1163------------64650.11 is an odd release in the Flask release cycle because it was supposed66to be the 1.0 release. However because there was such a long lead time up67to the release we decided to push out a 0.11 release first with some68changes removed to make the transition easier. If you have been tracking69the master branch which was 1.0 you might see some unexpected changes.7071In case you did track the master branch you will notice that :command:`flask --app`72is removed now. You need to use the environment variable to specify an73application.7475Debugging76`````````7727Flask 1.0 removed the ``debug_log_format`` attribute from Flask78Flask 0.11 removed the ``debug_log_format`` attribute from Flask79applications. Instead the new ``LOGGER_HANDLER_POLICY`` configuration can80be used to disable the default log handlers and custom log handlers can be81set up.8283Error handling84``````````````8586The behavior of error handlers was changed.87The 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.90Now the inheritance hierarchy takes precedence and handlers for more91specific exception classes are executed instead of more general ones.92See :ref:`error-handlers` for specifics.9394Trying to register a handler on an instance now raises :exc:`ValueError`.9596.. note::9798 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.46 47 Trying to register a handler on an instance now raises :exc:`ValueError`.102103Templating104``````````105106The :func:`~flask.templating.render_template_string` function has changed to107autoescape template variables by default. This better matches the behavior108of :func:`~flask.templating.render_template`.109110Extension imports111`````````````````112113Extension imports of the form ``flask.ext.foo`` are deprecated, you should use114``flask_foo``.115116The old form still works, but Flask will issue a117``flask.exthook.ExtDeprecationWarning`` for each extension you import the old118way. We also provide a migration utility called `flask-ext-migrate119<https://github.com/pallets/flask-ext-migrate>`_ that is supposed to120automatically rewrite your imports for this.121122.. _upgrading-to-010:123124Version 0.10125------------
16 unmodified lines
142when there is no request context yet but an application context. The old143``flask.Flask.request_globals_class`` attribute was renamed to144:attr:`flask.Flask.app_ctx_globals_class`.14573.. _Flask-OldSessions: http://pythonhosted.org/Flask-OldSessions/146.. _Flask-OldSessions: https://pythonhosted.org/Flask-OldSessions/147148Version 0.9149-----------150
19 unmodified lines
170Version 0.8171-----------172173Flask introduced a new session interface system. We also noticed that101there was a naming collision between `flask.session` the module that174there was a naming collision between ``flask.session`` the module that175implements sessions and :data:`flask.session` which is the global session176object. With that introduction we moved the implementation details for177the session system into a new module called :mod:`flask.sessions`. If you178used the previously undocumented session support we urge you to upgrade.
18 unmodified lines
197applications with Flask. Because we want to make upgrading as easy as198possible we tried to counter the problems arising from these changes by199providing a script that can ease the transition.200128The script scans your whole application and generates an unified diff with201The script scans your whole application and generates a unified diff with202changes it assumes are safe to apply. However as this is an automated203tool it won't be able to find all use cases and it might miss some. We204internally spread a lot of deprecation warnings all over the place to make205it easy to find pieces of code that it was unable to upgrade.
8 unmodified lines
214215To apply the upgrade script do the following:2162171. Download the script: `flask-07-upgrade.py145 <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>`_2192. Run it in the directory of your application::220221 python flask-07-upgrade.py > patchfile.diff222
13 unmodified lines
236Please note that deprecation warnings are disabled by default starting237with Python 2.7. In order to see the deprecation warnings that might be238emitted you have to enabled them with the :mod:`warnings` module.239167If you are working with windows and you lack the `patch` command line240If you are working with windows and you lack the ``patch`` command line241utility you can get it as part of various Unix runtime environments for242windows including cygwin, msysgit or ming32. Also source control systems243like svn, hg or git have builtin support for applying unified diffs as244generated by the tool. Check the manual of your version control system
8 unmodified lines
253before, you should catch them with :exc:`RuntimeError` now.254255Additionally the :func:`~flask.send_file` function is now issuing256deprecation warnings if you depend on functionality that will be removed184in Flask 1.0. Previously it was possible to use etags and mimetypes257in Flask 0.11. Previously it was possible to use etags and mimetypes258when file objects were passed. This was unreliable and caused issues259for a few setups. If you get a deprecation warning, make sure to260update your application to work with either filenames there or disable261etag attaching and attach them yourself.
91 unmodified lines
353 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 endpoint284 `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 lines
371 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.374302If you continue to use the `Module` object which is deprecated, Flask will375If you continue to use the ``Module`` object which is deprecated, Flask will376restore the previous behavior as good as possible. However we strongly377recommend upgrading to the new blueprints as they provide a lot of useful378improvement such as the ability to attach a blueprint multiple times,379blueprint specific error handlers and a lot more.
11 unmodified lines
391change the order.392393Another change that breaks backwards compatibility is that context394processors will no longer override values passed directly to the template322rendering function. If for example `request` is as variable passed395rendering function. If for example ``request`` is as variable passed396directly to the template, the default context processor will not override397it with the current request object. This makes it easier to extend398context processors later to inject additional variables without breaking399existing template not expecting them.
17 unmodified lines
417 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.348- 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.424425Version 0.4
47 unmodified lines
added:examples/flaskr/flaskr/static/style.css+18 added
1body { font-family: sans-serif; background: #eee; }2a, h1, h2 { color: #377BA8; }3h1, h2 { font-family: 'Georgia', serif; margin: 0; }4h1 { border-bottom: 2px solid #eee; }5h2 { font-size: 1.2em; }67.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
1from .flaskr import app
added:examples/flaskr/flaskr/flaskr.py+110 added
1# -*- coding: utf-8 -*-2"""3 Flaskr4 ~~~~~~56 A microblog example application written as Flask tutorial with7 Flask and sqlite3.89 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213import os14from sqlite3 import dbapi2 as sqlite315from flask import Flask, request, session, g, redirect, url_for, abort, \16 render_template, flash171819# create our little application :)20app = Flask(__name__)2122# Load default config and override config from an environment variable23app.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))30app.config.from_envvar('FLASKR_SETTINGS', silent=True)313233def connect_db():34 """Connects to the specific database."""35 rv = sqlite3.connect(app.config['DATABASE'])36 rv.row_factory = sqlite3.Row37 return rv383940def 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()464748@app.cli.command('initdb')49def initdb_command():50 """Creates the database tables."""51 init_db()52 print('Initialized the database.')535455def 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_db626364@app.teardown_appcontext65def 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()697071@app.route('/')72def 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)777879@app.route('/add', methods=['POST'])80def 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'))899091@app.route('/login', methods=['GET', 'POST'])92def 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)104105106@app.route('/logout')107def 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
1drop table if exists entries;2create 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
1body { font-family: sans-serif; background: #eee; }2a, h1, h2 { color: #377BA8; }3h1, h2 { font-family: 'Georgia', serif; margin: 0; }4h1 { border-bottom: 2px solid #eee; }5h2 { font-size: 1.2em; }67.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+72 added
1# -*- coding: utf-8 -*-2"""3 Flaskr Tests4 ~~~~~~~~~~~~56 Tests the Flaskr application.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import os13import tempfile14import pytest15from flaskr import flaskr161718@pytest.fixture19def client():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 yield client26 os.close(db_fd)27 os.unlink(flaskr.app.config['DATABASE'])282930def login(client, username, password):31 return client.post('/login', data=dict(32 username=username,33 password=password34 ), follow_redirects=True)353637def logout(client):38 return client.get('/logout', follow_redirects=True)394041def test_empty_db(client):42 """Start with a blank database."""43 rv = client.get('/')44 assert b'No entries here so far' in rv.data454647def test_login_logout(client):48 """Make sure login and logout works"""49 rv = login(client, flaskr.app.config['USERNAME'],50 flaskr.app.config['PASSWORD'])51 assert b'You were logged in' in rv.data52 rv = logout(client)53 assert b'You were logged out' in rv.data54 rv = login(client, flaskr.app.config['USERNAME'] + 'x',55 flaskr.app.config['PASSWORD'])56 assert b'Invalid username' in rv.data57 rv = login(client, flaskr.app.config['USERNAME'],58 flaskr.app.config['PASSWORD'] + 'x')59 assert b'Invalid password' in rv.data606162def test_messages(client):63 """Test that messages work"""64 login(client, flaskr.app.config['USERNAME'],65 flaskr.app.config['PASSWORD'])66 rv = client.post('/add', data=dict(67 title='<Hello>',68 text='<strong>HTML</strong> allowed here'69 ), follow_redirects=True)70 assert b'No entries here so far' not in rv.data71 assert b'&lt;Hello&gt;' in rv.data72 assert b'<strong>HTML</strong> allowed here' in rv.data
modified:examples/flaskr/.gitignore+1 added
1flaskr.db2.eggs/
deleted:examples/flaskr/flaskr.py-110 removed
1# -*- coding: utf-8 -*-2"""3 Flaskr4 ~~~~~~56 A microblog example application written as Flask tutorial with7 Flask and sqlite3.89 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213import os14from sqlite3 import dbapi2 as sqlite315from flask import Flask, request, session, g, redirect, url_for, abort, \16 render_template, flash171819# create our little application :)20app = Flask(__name__)2122# Load default config and override config from an environment variable23app.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))30app.config.from_envvar('FLASKR_SETTINGS', silent=True)313233def connect_db():34 """Connects to the specific database."""35 rv = sqlite3.connect(app.config['DATABASE'])36 rv.row_factory = sqlite3.Row37 return rv383940def 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()464748@app.cli.command('initdb')49def initdb_command():50 """Creates the database tables."""51 init_db()52 print('Initialized the database.')535455def 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_db626364@app.teardown_appcontext65def 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()697071@app.route('/')72def 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)777879@app.route('/add', methods=['POST'])80def 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'))899091@app.route('/login', methods=['GET', 'POST'])92def 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)104105106@app.route('/logout')107def 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
1graft flaskr/templates2graft flaskr/static3include flaskr/schema.sql
modified:examples/flaskr/README+13 added-5 removed
11 unmodified lines
12 1. edit the configuration in the flaskr.py file or13 export an FLASKR_SETTINGS environment variable14 pointing to a configuration file.1516 2. initialize the database with this command:16 2. install the app from the root of the project directory1718 flask --app=flaskr initdb18 pip install --editable .1920 3. now you can run flaskr:20 3. Instruct flask to use the right application2122 flask --app=flaskr run22 export FLASK_APP=flaskr2324 4. initialize the database with this command:2526 flask initdb2728 5. now you can run flaskr:2930 flask run3132 the application will greet you on33 http://localhost:5000/3435 ~ Is it tested?3629 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
1drop table if exists entries;2create 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]2test=pytest
added:examples/flaskr/setup.py+16 added
1from setuptools import setup23setup(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 ~~~~~~~~~~~~56 Tests the Flaskr application.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1314import os15import flaskr16import tempfile171819@pytest.fixture20def 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()2627 def teardown():28 os.close(db_fd)29 os.unlink(flaskr.app.config['DATABASE'])30 request.addfinalizer(teardown)3132 return client333435def login(client, username, password):36 return client.post('/login', data=dict(37 username=username,38 password=password39 ), follow_redirects=True)404142def logout(client):43 return client.get('/logout', follow_redirects=True)444546def test_empty_db(client):47 """Start with a blank database."""48 rv = client.get('/')49 assert b'No entries here so far' in rv.data505152def 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.data656667def 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'&lt;Hello&gt;' in rv.data77 assert b'<strong>HTML</strong> allowed here' in rv.data
modified:examples/jqueryexample/jqueryexample.py+3 added
21 unmodified lines
2223@app.route('/')24def index():25 return render_template('index.html')2627if __name__ == '__main__':28 app.run()
added:examples/minitwit/minitwit/static/style.css+178 added
1body {2 background: #CAECE9;3 font-family: 'Trebuchet MS', sans-serif;4 font-size: 14px;5}67a {8 color: #26776F;9}1011a:hover {12 color: #333;13}1415input[type="text"],16input[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}2627input[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}3839div.page {40 background: white;41 border: 1px solid #6ECCC4;42 width: 700px;43 margin: 30px auto;44}4546div.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}5556div.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}6566div.page div.navigation a {67 color: #444;68 font-weight: bold;69}7071div.page h2 {72 margin: 0 0 15px 0;73 color: #105751;74 text-shadow: 0 1px 2px #ccc;75}7677div.page div.body {78 padding: 10px;79}8081div.page div.footer {82 background: #eee;83 color: #888;84 padding: 5px 10px;85 font-size: 12px;86}8788div.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}9697div.page ul.messages {98 list-style: none;99 margin: 0;100 padding: 0;101}102103div.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}112113div.page ul.messages p {114 margin: 0;115}116117div.page ul.messages li img {118 float: left;119 padding: 0 10px 0 0;120}121122div.page ul.messages li small {123 font-size: 0.9em;124 color: #888;125}126127div.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}135136div.page div.twitbox h3 {137 margin: 0;138 font-size: 1em;139 color: #2C7E76;140}141142div.page div.twitbox p {143 margin: 0;144}145146div.page div.twitbox input[type="text"] {147 width: 585px;148}149150div.page div.twitbox input[type="submit"] {151 width: 70px;152 margin-left: 5px;153}154155ul.flashes {156 list-style: none;157 margin: 10px 10px 0 10px;158 padding: 0;159}160161ul.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}169170div.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 &mdash; 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>&mdash; {{ 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
1from .minitwit import app
added:examples/minitwit/minitwit/minitwit.py+256 added
1# -*- coding: utf-8 -*-2"""3 MiniTwit4 ~~~~~~~~56 A microblogging application written with Flask and sqlite3.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import time13from sqlite3 import dbapi2 as sqlite314from hashlib import md515from datetime import datetime16from flask import Flask, request, session, url_for, redirect, \17 render_template, abort, g, flash, _app_ctx_stack18from werkzeug import check_password_hash, generate_password_hash192021# configuration22DATABASE = '/tmp/minitwit.db'23PER_PAGE = 3024DEBUG = True25SECRET_KEY = 'development key'2627# create our little application :)28app = Flask(__name__)29app.config.from_object(__name__)30app.config.from_envvar('MINITWIT_SETTINGS', silent=True)313233def 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_db424344@app.teardown_appcontext45def 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()505152def 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()585960@app.cli.command('initdb')61def initdb_command():62 """Creates the database tables."""63 init_db()64 print('Initialized the database.')656667def 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 rv727374def 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 None798081def format_datetime(timestamp):82 """Format a timestamp for display."""83 return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d @ %H:%M')848586def 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)909192@app.before_request93def 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)9899100@app.route('/')101def 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]))116117118@app.route('/public')119def 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]))125126127@app.route('/<username>')128def 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)146147148@app.route('/<username>/follow')149def 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))162163164@app.route('/<username>/unfollow')165def 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))178179180@app.route('/add_message', methods=['POST'])181def 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'))193194195@app.route('/login', methods=['GET', 'POST'])196def 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)214215216@app.route('/register', methods=['GET', 'POST'])217def 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)244245246@app.route('/logout')247def 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'))252253254# add some filters to jinja255app.jinja_env.filters['datetimeformat'] = format_datetime256app.jinja_env.filters['gravatar'] = gravatar_url
added:examples/minitwit/minitwit/schema.sql+21 added
1drop table if exists user;2create 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);89drop table if exists follower;10create table follower (11 who_id integer,12 whom_id integer13);1415drop table if exists message;16create 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
1body {2 background: #CAECE9;3 font-family: 'Trebuchet MS', sans-serif;4 font-size: 14px;5}67a {8 color: #26776F;9}1011a:hover {12 color: #333;13}1415input[type="text"],16input[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}2627input[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}3839div.page {40 background: white;41 border: 1px solid #6ECCC4;42 width: 700px;43 margin: 30px auto;44}4546div.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}5556div.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}6566div.page div.navigation a {67 color: #444;68 font-weight: bold;69}7071div.page h2 {72 margin: 0 0 15px 0;73 color: #105751;74 text-shadow: 0 1px 2px #ccc;75}7677div.page div.body {78 padding: 10px;79}8081div.page div.footer {82 background: #eee;83 color: #888;84 padding: 5px 10px;85 font-size: 12px;86}8788div.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}9697div.page ul.messages {98 list-style: none;99 margin: 0;100 padding: 0;101}102103div.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}112113div.page ul.messages p {114 margin: 0;115}116117div.page ul.messages li img {118 float: left;119 padding: 0 10px 0 0;120}121122div.page ul.messages li small {123 font-size: 0.9em;124 color: #888;125}126127div.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}135136div.page div.twitbox h3 {137 margin: 0;138 font-size: 1em;139 color: #2C7E76;140}141142div.page div.twitbox p {143 margin: 0;144}145146div.page div.twitbox input[type="text"] {147 width: 585px;148}149150div.page div.twitbox input[type="submit"] {151 width: 70px;152 margin-left: 5px;153}154155ul.flashes {156 list-style: none;157 margin: 10px 10px 0 10px;158 padding: 0;159}160161ul.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}169170div.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 &mdash; 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>&mdash; {{ message.pub_date|datetimeformat }}</small>45 {% else %}46 <li><em>There's no message so far.</em>47 {% endfor %}48 </ul>49{% endblock %}
added:examples/minitwit/tests/test_minitwit.py+149 added
1# -*- coding: utf-8 -*-2"""3 MiniTwit Tests4 ~~~~~~~~~~~~~~56 Tests the MiniTwit application.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import os12import tempfile13import pytest14from minitwit import minitwit151617@pytest.fixture18def client():19 db_fd, minitwit.app.config['DATABASE'] = tempfile.mkstemp()20 client = minitwit.app.test_client()21 with minitwit.app.app_context():22 minitwit.init_db()2324 yield client2526 os.close(db_fd)27 os.unlink(minitwit.app.config['DATABASE'])282930def register(client, username, password, password2=None, email=None):31 """Helper function to register a user"""32 if password2 is None:33 password2 = password34 if email is None:35 email = username + '@example.com'36 return client.post('/register', data={37 'username': username,38 'password': password,39 'password2': password2,40 'email': email,41 }, follow_redirects=True)424344def login(client, username, password):45 """Helper function to login"""46 return client.post('/login', data={47 'username': username,48 'password': password49 }, follow_redirects=True)505152def register_and_login(client, username, password):53 """Registers and logs in in one go"""54 register(client, username, password)55 return login(client, username, password)565758def logout(client):59 """Helper function to logout"""60 return client.get('/logout', follow_redirects=True)616263def add_message(client, text):64 """Records a message"""65 rv = client.post('/add_message', data={'text': text},66 follow_redirects=True)67 if text:68 assert b'Your message was recorded' in rv.data69 return rv707172def test_register(client):73 """Make sure registering works"""74 rv = register(client, 'user1', 'default')75 assert b'You were successfully registered ' \76 b'and can login now' in rv.data77 rv = register(client, 'user1', 'default')78 assert b'The username is already taken' in rv.data79 rv = register(client, '', 'default')80 assert b'You have to enter a username' in rv.data81 rv = register(client, 'meh', '')82 assert b'You have to enter a password' in rv.data83 rv = register(client, 'meh', 'x', 'y')84 assert b'The two passwords do not match' in rv.data85 rv = register(client, 'meh', 'foo', email='broken')86 assert b'You have to enter a valid email address' in rv.data878889def test_login_logout(client):90 """Make sure logging in and logging out works"""91 rv = register_and_login(client, 'user1', 'default')92 assert b'You were logged in' in rv.data93 rv = logout(client)94 assert b'You were logged out' in rv.data95 rv = login(client, 'user1', 'wrongpassword')96 assert b'Invalid password' in rv.data97 rv = login(client, 'user2', 'wrongpassword')98 assert b'Invalid username' in rv.data99100101def test_message_recording(client):102 """Check if adding messages works"""103 register_and_login(client, 'foo', 'default')104 add_message(client, 'test message 1')105 add_message(client, '<test message 2>')106 rv = client.get('/')107 assert b'test message 1' in rv.data108 assert b'&lt;test message 2&gt;' in rv.data109110111def test_timelines(client):112 """Make sure that timelines work"""113 register_and_login(client, 'foo', 'default')114 add_message(client, 'the message by foo')115 logout(client)116 register_and_login(client, 'bar', 'default')117 add_message(client, 'the message by bar')118 rv = client.get('/public')119 assert b'the message by foo' in rv.data120 assert b'the message by bar' in rv.data121122 # bar's timeline should just show bar's message123 rv = client.get('/')124 assert b'the message by foo' not in rv.data125 assert b'the message by bar' in rv.data126127 # now let's follow foo128 rv = client.get('/foo/follow', follow_redirects=True)129 assert b'You are now following &#34;foo&#34;' in rv.data130131 # we should now see foo's message132 rv = client.get('/')133 assert b'the message by foo' in rv.data134 assert b'the message by bar' in rv.data135136 # but on the user's page we only want the user's message137 rv = client.get('/bar')138 assert b'the message by foo' not in rv.data139 assert b'the message by bar' in rv.data140 rv = client.get('/foo')141 assert b'the message by foo' in rv.data142 assert b'the message by bar' not in rv.data143144 # now unfollow and check if that worked145 rv = client.get('/foo/unfollow', follow_redirects=True)146 assert b'You are no longer following &#34;foo&#34;' in rv.data147 rv = client.get('/')148 assert b'the message by foo' not in rv.data149 assert b'the message by bar' in rv.data
added:examples/minitwit/.gitignore+2 added
1minitwit.db2.eggs/
added:examples/minitwit/MANIFEST.in+3 added
1graft minitwit/templates2graft minitwit/static3include minitwit/schema.sql
deleted:examples/minitwit/minitwit.py-256 removed
1# -*- coding: utf-8 -*-2"""3 MiniTwit4 ~~~~~~~~56 A microblogging application written with Flask and sqlite3.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import time13from sqlite3 import dbapi2 as sqlite314from hashlib import md515from datetime import datetime16from flask import Flask, request, session, url_for, redirect, \17 render_template, abort, g, flash, _app_ctx_stack18from werkzeug import check_password_hash, generate_password_hash192021# configuration22DATABASE = '/tmp/minitwit.db'23PER_PAGE = 3024DEBUG = True25SECRET_KEY = 'development key'2627# create our little application :)28app = Flask(__name__)29app.config.from_object(__name__)30app.config.from_envvar('MINITWIT_SETTINGS', silent=True)313233def 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_db424344@app.teardown_appcontext45def 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()505152def 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()585960@app.cli.command('initdb')61def initdb_command():62 """Creates the database tables."""63 init_db()64 print('Initialized the database.')656667def 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 rv727374def 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 None798081def format_datetime(timestamp):82 """Format a timestamp for display."""83 return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d @ %H:%M')848586def gravatar_url(email, size=80):87 """Return the gravatar image for the given email address."""88 return 'http://www.gravatar.com/avatar/%s?d=identicon&s=%d' % \89 (md5(email.strip().lower().encode('utf-8')).hexdigest(), size)909192@app.before_request93def 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)9899100@app.route('/')101def 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]))116117118@app.route('/public')119def 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]))125126127@app.route('/<username>')128def 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)146147148@app.route('/<username>/follow')149def 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))162163164@app.route('/<username>/unfollow')165def 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))178179180@app.route('/add_message', methods=['POST'])181def 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'))193194195@app.route('/login', methods=['GET', 'POST'])196def 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)214215216@app.route('/register', methods=['GET', 'POST'])217def 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)244245246@app.route('/logout')247def 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'))252253254# add some filters to jinja255app.jinja_env.filters['datetimeformat'] = format_datetime256app.jinja_env.filters['gravatar'] = gravatar_url
modified:examples/minitwit/README+13 added-5 removed
12 unmodified lines
13 1. edit the configuration in the minitwit.py file or14 export an MINITWIT_SETTINGS environment variable15 pointing to a configuration file.1617 2. fire up a shell and run this:17 2. install the app from the root of the project directory1819 flask --app=minitwit initdb19 pip install --editable .2021 3. now you can run minitwit:21 3. tell flask about the right application:2223 flask --app=minitwit run23 export FLASK_APP=minitwit2425 4. fire up a shell and run this:2627 flask initdb2829 5. now you can run minitwit:3031 flask run3233 the application will greet you on34 http://localhost:5000/3536 ~ Is it tested?3730 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
1drop table if exists user;2create 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);89drop table if exists follower;10create table follower (11 who_id integer,12 whom_id integer13);1415drop table if exists message;16create 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]2test=pytest
added:examples/minitwit/setup.py+16 added
1from setuptools import setup23setup(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 ~~~~~~~~~~~~~~56 Tests the MiniTwit application.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import os12import minitwit13import tempfile14import pytest151617@pytest.fixture18def 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()2324 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 client303132def 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)444546def login(client, username, password):47 """Helper function to login"""48 return client.post('/login', data={49 'username': username,50 'password': password51 }, follow_redirects=True)525354def 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)585960def logout(client):61 """Helper function to logout"""62 return client.get('/logout', follow_redirects=True)636465def 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 rv727374def 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.data899091def 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.data101102103def 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'&lt;test message 2&gt;' in rv.data111112113def 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.data123124 # 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.data128129 # now let's follow foo130 rv = client.get('/foo/follow', follow_redirects=True)131 assert b'You are now following &#34;foo&#34;' in rv.data132133 # 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.data137138 # 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.data145146 # now unfollow and check if that worked147 rv = client.get('/foo/unfollow', follow_redirects=True)148 assert b'You are no longer following &#34;foo&#34;' 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.data
added:examples/patterns/largerapp/tests/test_largerapp.py+12 added
1from yourapplication import app2import pytest34@pytest.fixture5def client():6 app.config['TESTING'] = True7 client = app.test_client()8 return client910def test_index(client):11 rv = client.get('/')12 assert b"Hello World!" in rv.data
added:examples/patterns/largerapp/yourapplication/static/style.css
added:examples/patterns/largerapp/yourapplication/templates/index.html
added:examples/patterns/largerapp/yourapplication/templates/layout.html
added:examples/patterns/largerapp/yourapplication/templates/login.html
added:examples/patterns/largerapp/yourapplication/__init__.py+4 added
1from flask import Flask2app = Flask(__name__)34import yourapplication.views
added:examples/patterns/largerapp/yourapplication/views.py+5 added
1from yourapplication import app23@app.route('/')4def index():5 return 'Hello World!'
added:examples/patterns/largerapp/setup.py+10 added
1from setuptools import setup23setup(4 name='yourapplication',5 packages=['yourapplication'],6 include_package_data=True,7 install_requires=[8 'flask',9 ],10)
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 });1011 $('a.signout').on('click', function() {12 navigator.id.logout();13 return false;14 });1516 /* 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
1html {2 background: #eee;3}45body {6 font-family: 'Verdana', sans-serif;7 font-size: 15px;8 margin: 30px auto;9 width: 720px;10 background: white;11 padding: 30px;12}1314h1 {15 margin: 0;16}1718h1, h2, a {19 color: #d00;20}2122div.authbar {23 background: #eee;24 padding: 0 15px;25 margin: 10px -15px;26 line-height: 25px;27 height: 25px;28 vertical-align: middle;29}3031div.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 }};910 /* 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
1from flask import Flask, render_template, session, request, abort, g23import requests456app = Flask(__name__)7app.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)13app.config.from_envvar('PERSONA_SETTINGS', silent=True)141516@app.before_request17def get_current_user():18 g.user = None19 email = session.get('email')20 if email is not None:21 g.user = email222324@app.route('/')25def index():26 """Just a generic index page to show."""27 return render_template('index.html')282930@app.route('/_auth/login', methods=['GET', 'POST'])31def 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'4546 abort(400)474849@app.route('/_auth/logout', methods=['POST'])50def 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
1A simple example for integrating [Persona](https://login.persona.org/) into a2Flask application. In addition to Flask, it requires the3[requests](www.python-requests.org/) library.
modified:flask/__init__.py+3 added-3 removed
8 unmodified lines
9 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213__version__ = '0.11.dev0'13__version__ = '0.13-dev'1415# utilities we import from Werkzeug and Jinja2 that are unused16# in the module but are exported as public interface.17from werkzeug.exceptions import abort
15 unmodified lines
33# the signals34from .signals import signals_available, template_rendered, request_started, \35 request_finished, got_request_exception, request_tearing_down, \36 appcontext_tearing_down, appcontext_pushed, \37 appcontext_popped, message_flashed37 appcontext_popped, message_flashed, before_render_template3839# We're not exposing the actual json module but a convenient wrapper around40# it.41from . import json4243# This was the only thing that flask used to export at one point and it had43# This was the only thing that Flask used to export at one point and it had44# a more generic name.45jsonify = json.jsonify4647# backwards compat, goes away in 1.0
2 unmodified lines
modified:flask/_compat.py+19 added-18 removed
23 unmodified lines
24 iterkeys = lambda d: iter(d.keys())25 itervalues = lambda d: iter(d.values())26 iteritems = lambda d: iter(d.items())2728 from inspect import getfullargspec as getargspec29 from io import StringIO3031 def reraise(tp, value, tb=None):32 if value.__traceback__ is not tb:
10 unmodified lines
43 iterkeys = lambda d: d.iterkeys()44 itervalues = lambda d: d.itervalues()45 iteritems = lambda d: d.iteritems()4647 from inspect import getargspec48 from cStringIO import StringIO4950 exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')51
3 unmodified lines
55 return cls565758def with_metaclass(meta, *bases):59 """Create a base class with a metaclass."""60 # This requires a bit of explanation: the basic idea is to make a61 # dummy metaclass for one level of class instantiation that replaces59 # itself with the actual metaclass. Because of internal type checks60 # we also need to make sure that we downgrade the custom metaclass61 # for one level to something closer to type (that's why __call__ and62 # __init__ comes back from type etc.).63 #64 # This has the advantage over six.with_metaclass in that it does not65 # introduce dummy classes into the final MRO.66 class metaclass(meta):67 __call__ = type.__call__68 __init__ = type.__init__62 # itself with the actual metaclass.63 class metaclass(type):64 def __new__(cls, name, this_bases, d):70 if this_bases is None:71 return type.__new__(cls, name, (), d)65 return meta(name, bases, d)73 return metaclass('temporary_class', None, {})66 return type.__new__(metaclass, 'temporary_class', (), {})676869# Certain versions of pypy have a bug where clearing the exception stack77# breaks the __exit__ function in a very peculiar way. This is currently78# true for pypy 2.2.1 for instance. The second level of exception blocks79# is necessary because pypy seems to forget to check if an exception80# happened until the next bytecode instruction?70# breaks the __exit__ function in a very peculiar way. The second level of71# exception blocks is necessary because pypy seems to forget to check if an72# exception happened until the next bytecode instruction?73#74# Relevant PyPy bugfix commit:75# https://bitbucket.org/pypy/pypy/commits/77ecf91c635a287e88e60d8ddb0f4e9df400330176# According to ronan on #pypy IRC, it is released in PyPy2 2.3 and later77# versions.78#79# Ubuntu 14.04 has PyPy 2.2.1, which does exhibit this bug.80BROKEN_PYPY_CTXMGR_EXIT = False81if hasattr(sys, 'pypy_version_info'):82 class _Mgr(object):83 def __enter__(self):84 return self85 def __exit__(self, *args):86 if hasattr(sys, 'exc_clear'):87 # Python 3 (PyPy3) doesn't have exc_clear87 sys.exc_clear()88 sys.exc_clear()89 try:90 try:91 with _Mgr():92 raise AssertionError()
6 unmodified lines
modified:flask/app.py+287 added-188 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11import os12import sys13from threading import Lock13from datetime import timedelta15from itertools import chain14from functools import update_wrapper17from collections import Mapping, deque15from itertools import chain16from threading import Lock1719from werkzeug.datastructures import ImmutableDict20from werkzeug.routing import Map, Rule, RequestRedirect, BuildError21from werkzeug.exceptions import HTTPException, InternalServerError, \22 MethodNotAllowed, BadRequest, default_exceptions18from werkzeug.datastructures import ImmutableDict, Headers19from werkzeug.exceptions import BadRequest, HTTPException, \20 InternalServerError, MethodNotAllowed, default_exceptions21from werkzeug.routing import BuildError, Map, RequestRedirect, Rule2224from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \25 locked_cached_property, _endpoint_from_view_func, find_package26from . import json, cli27from .wrappers import Request, Response28from .config import ConfigAttribute, Config29from .ctx import RequestContext, AppContext, _AppCtxGlobals30from .globals import _request_ctx_stack, request, session, g23from . import cli, json24from ._compat import integer_types, reraise, string_types, text_type25from .config import Config, ConfigAttribute26from .ctx import AppContext, RequestContext, _AppCtxGlobals27from .globals import _request_ctx_stack, g, request, session28from .helpers import _PackageBoundObject, \29 _endpoint_from_view_func, find_package, get_debug_flag, \30 get_flashed_messages, locked_cached_property, url_for31from .sessions import SecureCookieSessionInterface32from .signals import appcontext_tearing_down, got_request_exception, \33 request_finished, request_started, request_tearing_down34from .templating import DispatchingJinjaLoader, Environment, \33 _default_template_ctx_processor34from .signals import request_started, request_finished, got_request_exception, \35 request_tearing_down, appcontext_tearing_down36from ._compat import reraise, string_types, text_type, integer_types, iterkeys35 _default_template_ctx_processor36from .wrappers import Request, Response3738# a lock used for logger initialization39_logger_lock = Lock()40
78 unmodified lines
119 .. versionadded:: 0.8120 The `instance_path` and `instance_relative_config` parameters were121 added.122123 .. versionadded:: 1.0123 .. versionadded:: 0.11124 The `root_path` parameter was added.125126 .. versionadded:: 0.13127 The `host_matching` and `static_host` parameters were added.128129 :param import_name: the name of the application package130 :param static_url_path: can be used to specify a different path for the131 static files on the web. Defaults to the name132 of the `static_folder` folder.133 :param static_folder: the folder with static files that should be served134 at `static_url_path`. Defaults to the ``'static'``135 folder in the root path of the application.136 :param host_matching: sets the app's ``url_map.host_matching`` to the given137 given value. Defaults to False.138 :param static_host: the host to use when adding the static route. Defaults139 to None. Required when using ``host_matching=True``140 with a ``static_folder`` configured.141 :param template_folder: the folder that contains the templates that should142 be used by the application. Defaults to143 ``'templates'`` folder in the root path of the144 application.
21 unmodified lines
166 response_class = Response167168 #: The class that is used for the Jinja environment.169 #:162 #: .. versionadded:: 1.0163 jinja_env_class = Environment170 #: .. versionadded:: 0.11171 jinja_environment = Environment172173 #: The class that is used for the :data:`~flask.g` instance.174 #:175 #: Example use cases for a custom class:176 #:177 #: 1. Store arbitrary attributes on flask.g.178 #: 2. Add a property for lazy per-request database connectors.171 #: 3. Return None instead of AttributeError on expected attributes.179 #: 3. Return None instead of AttributeError on unexpected attributes.180 #: 4. Raise exception if an unexpected attr is set, a "controlled" flask.g.181 #:182 #: In Flask 0.9 this property was called `request_globals_class` but it183 #: was changed in 0.10 to :attr:`app_ctx_globals_class` because the
21 unmodified lines
205 #:206 #: 1. Default values for certain config options.207 #: 2. Access to config values through attributes in addition to keys.208 #:201 #: .. versionadded:: 1.0209 #: .. versionadded:: 0.11210 config_class = Config211212 #: The debug flag. Set this to ``True`` to enable debugging of the213 #: application. In debug mode the debugger will kick in when an unhandled
5 unmodified lines
219 debug = ConfigAttribute('DEBUG')220221 #: The testing flag. Set this to ``True`` to enable the test mode of222 #: Flask extensions (and in the future probably also Flask itself).215 #: For example this might activate unittest helpers that have an223 #: For example this might activate test helpers that have an224 #: additional runtime cost which should not be enabled by default.225 #:226 #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the227 #: default it's implicitly enabled.
25 unmodified lines
253 #: ``timedelta(days=31)``254 permanent_session_lifetime = ConfigAttribute('PERMANENT_SESSION_LIFETIME',255 get_converter=_make_timedelta)256257 #: A :class:`~datetime.timedelta` which is used as default cache_timeout258 #: for the :func:`send_file` functions. The default is 12 hours.259 #:260 #: This attribute can also be configured from the config with the261 #: ``SEND_FILE_MAX_AGE_DEFAULT`` configuration key. This configuration262 #: variable can also be set with an integer value used as seconds.263 #: Defaults to ``timedelta(hours=12)``264 send_file_max_age_default = ConfigAttribute('SEND_FILE_MAX_AGE_DEFAULT',265 get_converter=_make_timedelta)266267 #: Enable this if you want to use the X-Sendfile feature. Keep in268 #: mind that the server has to support this. This only affects files269 #: sent with the :func:`send_file` method.270 #:
25 unmodified lines
296 )297298 #: Default configuration parameters.299 default_config = ImmutableDict({282 'DEBUG': False,300 'DEBUG': get_debug_flag(default=False),301 'TESTING': False,302 'PROPAGATE_EXCEPTIONS': None,303 'PRESERVE_CONTEXT_ON_EXCEPTION': None,304 'SECRET_KEY': None,
9 unmodified lines
314 'SESSION_COOKIE_HTTPONLY': True,315 'SESSION_COOKIE_SECURE': False,316 'SESSION_REFRESH_EACH_REQUEST': True,317 'MAX_CONTENT_LENGTH': None,300 'SEND_FILE_MAX_AGE_DEFAULT': 12 * 60 * 60, # 12 hours318 'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12),319 'TRAP_BAD_REQUEST_ERRORS': False,320 'TRAP_HTTP_EXCEPTIONS': False,321 'EXPLAIN_TEMPLATE_LOADING': False,322 'PREFERRED_URL_SCHEME': 'http',323 'JSON_AS_ASCII': True,324 'JSON_SORT_KEYS': True,307 'JSONIFY_PRETTYPRINT_REGULAR': True,325 'JSONIFY_PRETTYPRINT_REGULAR': False,326 'JSONIFY_MIMETYPE': 'application/json',327 'TEMPLATES_AUTO_RELOAD': None,328 })329330 #: The rule object to use for URL rules created. This is used by
13 unmodified lines
344 #: .. versionadded:: 0.8345 session_interface = SecureCookieSessionInterface()346347 def __init__(self, import_name, static_path=None, static_url_path=None,329 static_folder='static', template_folder='templates',348 static_folder='static', static_host=None,349 host_matching=False, template_folder='templates',350 instance_path=None, instance_relative_config=False,351 root_path=None):352 _PackageBoundObject.__init__(self, import_name,353 template_folder=template_folder,
45 unmodified lines
399 #: special key ``None`` points to a list of tuples where the first item400 #: is the class for the instance check and the second the error handler401 #: function.402 #:383 #: To register a error handler, use the :meth:`errorhandler`403 #: To register an error handler, use the :meth:`errorhandler`404 #: decorator.405 self.error_handler_spec = {None: self._error_handlers}406407 #: A list of functions that are called when :meth:`url_for` raises a
4 unmodified lines
412 #:413 #: .. versionadded:: 0.9414 self.url_build_error_handlers = []415396 #: A dictionary with lists of functions that should be called at the397 #: beginning of the request. The key of the dictionary is the name of398 #: the blueprint this function is active for, ``None`` for all requests.399 #: This can for example be used to open database connections or400 #: getting hold of the currently logged in user. To register a401 #: function here, use the :meth:`before_request` decorator.416 #: A dictionary with lists of functions that will be called at the417 #: beginning of each request. The key of the dictionary is the name of418 #: the blueprint this function is active for, or ``None`` for all419 #: requests. To register a function, use the :meth:`before_request`420 #: decorator.421 self.before_request_funcs = {}422404 #: A lists of functions that should be called at the beginning of the405 #: first request to this instance. To register a function here, use406 #: the :meth:`before_first_request` decorator.423 #: A list of functions that will be called at the beginning of the424 #: first request to this instance. To register a function, use the425 #: :meth:`before_first_request` decorator.426 #:427 #: .. versionadded:: 0.8428 self.before_first_request_funcs = []429430 #: A dictionary with lists of functions that should be called after431 #: each request. The key of the dictionary is the name of the blueprint432 #: this function is active for, ``None`` for all requests. This can for414 #: example be used to open database connections or getting hold of the415 #: currently logged in user. To register a function here, use the416 #: :meth:`after_request` decorator.433 #: example be used to close database connections. To register a function434 #: here, use the :meth:`after_request` decorator.435 self.after_request_funcs = {}436437 #: A dictionary with lists of functions that are called after438 #: each request, even if an exception has occurred. The key of the
14 unmodified lines
453 #:454 #: .. versionadded:: 0.9455 self.teardown_appcontext_funcs = []456439 #: A dictionary with lists of functions that can be used as URL440 #: value processor functions. Whenever a URL is built these functions441 #: are called to modify the dictionary of values in place. The key442 #: ``None`` here is used for application wide443 #: callbacks, otherwise the key is the name of the blueprint.444 #: Each of these functions has the chance to modify the dictionary457 #: A dictionary with lists of functions that are called before the458 #: :attr:`before_request_funcs` functions. The key of the dictionary is459 #: the name of the blueprint this function is active for, or ``None``460 #: for all requests. To register a function, use461 #: :meth:`url_value_preprocessor`.462 #:463 #: .. versionadded:: 0.7464 self.url_value_preprocessors = {}465
21 unmodified lines
487488 #: A list of shell context processor functions that should be run489 #: when a shell context is created.490 #:474 #: .. versionadded:: 1.0491 #: .. versionadded:: 0.11492 self.shell_context_processors = []493494 #: all the attached blueprints in a dictionary by name. Blueprints495 #: can be attached multiple times so this dictionary does not tell
28 unmodified lines
524 #: class ListConverter(BaseConverter):525 #: def to_python(self, value):526 #: return value.split(',')527 #: def to_url(self, values):511 #: return ','.join(BaseConverter.to_url(value)528 #: return ','.join(super(ListConverter, self).to_url(value)529 #: for value in values)530 #:531 #: app = Flask(__name__)532 #: app.url_map.converters['list'] = ListConverter533 self.url_map = Map()534535 self.url_map.host_matching = host_matching536537 # tracks internally if the application already handled at least one538 # request.539 self._got_first_request = False540 self._before_request_lock = Lock()541523 # register the static folder for the application. Do that even524 # if the folder does not exist. First of all it might be created525 # while the server is running (usually happens during development)526 # but also because google appengine stores static files somewhere527 # else when mapped with the .yml file.542 # Add a static route using the provided static_url_path, static_host,543 # and static_folder if there is a configured static_folder.544 # Note we do this without checking if static_folder exists.545 # For one, it might be created while the server is running (e.g. during546 # development). Also, Google App Engine stores static files somewhere547 if self.has_static_folder:548 assert bool(static_host) == host_matching, 'Invalid static_host/host_matching combination'549 self.add_url_rule(self.static_url_path + '/<path:filename>',530 endpoint='static',550 endpoint='static', host=static_host,551 view_func=self.send_static_file)552553 #: The click command line context for this application. Commands554 #: registered here show up in the :command:`flask` command once the555 #: application has been discovered. The default commands are556 #: provided by Flask itself and can be overridden.557 #:558 #: This is an instance of a :class:`click.Group` object.539 self.cli = cli.AppGroup(self)559 self.cli = cli.AppGroup(self.name)560561 def _get_error_handlers(self):562 from warnings import warn563 warn(DeprecationWarning('error_handlers is deprecated, use the '
128 unmodified lines
692 the Jinja2 globals and filters after initialization. Override693 this function to customize the behavior.694695 .. versionadded:: 0.5676 .. versionchanged:: 1.0696 .. versionchanged:: 0.11697 ``Environment.auto_reload`` set in accordance with698 ``TEMPLATES_AUTO_RELOAD`` configuration option.699 """700 options = dict(self.jinja_options)
3 unmodified lines
704 if self.config['TEMPLATES_AUTO_RELOAD'] is not None:705 options['auto_reload'] = self.config['TEMPLATES_AUTO_RELOAD']706 else:707 options['auto_reload'] = self.debug688 rv = self.jinja_env_class(self, **options)708 rv = self.jinja_environment(self, **options)709 rv.globals.update(710 url_for=url_for,711 get_flashed_messages=get_flashed_messages,712 config=self.config,
30 unmodified lines
743 """744745 def select_jinja_autoescape(self, filename):746 """Returns ``True`` if autoescaping should be active for the given727 template name.747 template name. If no template name is given, returns `True`.748749 .. versionadded:: 0.5750 """751 if filename is None:732 return False752 return True753 return filename.endswith(('.html', '.htm', '.xml', '.xhtml'))754755 def update_template_context(self, context):756 """Update the template context with some commonly used variables.
24 unmodified lines
781 """Returns the shell context for an interactive shell for this782 application. This runs all the registered shell context783 processors.784765 .. versionadded:: 1.0785 .. versionadded:: 0.11786 """787 rv = {'app': self, 'g': g}788 for processor in self.shell_context_processors:789 rv.update(processor())790 return rv791792 def run(self, host=None, port=None, debug=None, **options):773 """Runs the application on a local development server. If the774 :attr:`debug` flag is set the server will automatically reload793 """Runs the application on a local development server.794795 Do not use ``run()`` in a production setting. It is not intended to796 meet security and performance requirements for a production server.797 Instead, see :ref:`deployment` for WSGI server recommendations.798799 If the :attr:`debug` flag is set the server will automatically reload800 for code changes and show a debugger in case an exception happened.801802 If you want to run the application in debug mode, but disable the803 code execution on the interactive debugger, you can pass
1 unmodified line
805 traceback screen active, but disable code execution.806807 It is not recommended to use this function for development with808 automatic reloading as this is badly supported. Instead you should784 be using the :command:`flask` command line script's ``runserver``785 support.809 be using the :command:`flask` command line script's ``run`` support.810811 .. admonition:: Keep in Mind812813 Flask will suppress any server error with a generic error page
8 unmodified lines
822 The default port is now picked from the ``SERVER_NAME`` variable.823824 :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to825 have the server available externally as well. Defaults to802 ``'127.0.0.1'``.826 ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config827 variable if present.828 :param port: the port of the webserver. Defaults to ``5000`` or the829 port defined in the ``SERVER_NAME`` config variable if830 present.831 :param debug: if given, enable or disable debug mode.
2 unmodified lines
834 Werkzeug server. See835 :func:`werkzeug.serving.run_simple` for more836 information.837 """838 # Change this into a no-op if the server is invoked from the839 # command line. Have a look at cli.py for more information.840 if os.environ.get('FLASK_RUN_FROM_CLI_SERVER') == '1':841 from .debughelpers import explain_ignored_app_run842 explain_ignored_app_run()843 return844845 from werkzeug.serving import run_simple814 if host is None:815 host = '127.0.0.1'816 if port is None:817 server_name = self.config['SERVER_NAME']818 if server_name and ':' in server_name:819 port = int(server_name.rsplit(':', 1)[1])820 else:821 port = 5000846 _host = '127.0.0.1'847 _port = 5000848 server_name = self.config.get("SERVER_NAME")849 sn_host, sn_port = None, None850 if server_name:851 sn_host, _, sn_port = server_name.partition(':')852 host = host or sn_host or _host853 port = int(port or sn_port or _port)854 if debug is not None:855 self.debug = bool(debug)856 options.setdefault('use_reloader', self.debug)857 options.setdefault('use_debugger', self.debug)858 try:859 run_simple(host, port, self, **options)860 finally:861 # reset the first request information if the development server830 # resetted normally. This makes it possible to restart the server862 # reset normally. This makes it possible to restart the server863 # without reloader and that stuff from an interactive shell.864 self._got_first_request = False865866 def test_client(self, use_cookies=True, **kwargs):
25 unmodified lines
892893 from flask.testing import FlaskClient894895 class CustomClient(FlaskClient):864 def __init__(self, authentication=None, *args, **kwargs):865 FlaskClient.__init__(*args, **kwargs)866 self._authentication = authentication896 def __init__(self, *args, **kwargs):897 self._authentication = kwargs.pop("authentication")898 super(CustomClient,self).__init__( *args, **kwargs)899900 app.test_client_class = CustomClient901 client = app.test_client(authentication='Basic ....')902
6 unmodified lines
909 The `use_cookies` parameter was added as well as the ability910 to override the client to be used by setting the911 :attr:`test_client_class` attribute.912881 .. versionchanged:: 1.0913 .. versionchanged:: 0.11914 Added `**kwargs` to support passing additional keyword arguments to915 the constructor of :attr:`test_client_class`.916 """917 cls = self.test_client_class
52 unmodified lines
970971 def iter_blueprints(self):972 """Iterates over all blueprints by the order they were registered.973942 .. versionadded:: 1.0974 .. versionadded:: 0.11975 """976 return iter(self._blueprint_order)977978 @setupmethod947 def add_url_rule(self, rule, endpoint=None, view_func=None, **options):979 def add_url_rule(self, rule, endpoint=None, view_func=None, provide_automatic_options=None, **options):980 """Connects a URL rule. Works exactly like the :meth:`route`981 decorator. If a view_func is provided it will be registered with the982 endpoint.983
31 unmodified lines
1015 itself assumes the name of the view function as1016 endpoint1017 :param view_func: the function to call when serving a request to the1018 provided endpoint1019 :param provide_automatic_options: controls whether the ``OPTIONS``1020 method should be added automatically. This can also be controlled1021 by setting the ``view_func.provide_automatic_options = False``1022 before adding the rule.1023 :param options: the options to be forwarded to the underlying1024 :class:`~werkzeug.routing.Rule` object. A change1025 to Werkzeug is handling of method options. methods1026 is a list of methods this rule should be limited
21 unmodified lines
1048 required_methods = set(getattr(view_func, 'required_methods', ()))10491050 # starting with Flask 0.8 the view_func object can disable and1051 # force-enable the automatic options handling.1052 if provide_automatic_options is None:1016 provide_automatic_options = getattr(view_func,1017 'provide_automatic_options', None)1053 provide_automatic_options = getattr(view_func,1054 'provide_automatic_options', None)10551056 if provide_automatic_options is None:1057 if 'OPTIONS' not in methods:1058 provide_automatic_options = True
67 unmodified lines
1126 if isinstance(exc_class_or_code, integer_types):1127 exc_class = default_exceptions[exc_class_or_code]1128 else:1129 exc_class = exc_class_or_code1093 11301131 assert issubclass(exc_class, Exception)1095 11321133 if issubclass(exc_class, HTTPException):1134 return exc_class, exc_class.code1135 else:1136 return exc_class, None1100 11371138 @setupmethod1139 def errorhandler(self, code_or_exception):1103 """A decorator that is used to register a function give a given1140 """A decorator that is used to register a function given an1141 error code. Example::11421143 @app.errorhandler(404)1144 def page_not_found(error):
29 unmodified lines
1174 One can now additionally also register custom exception types1175 that do not necessarily have to be a subclass of the1176 :class:`~werkzeug.exceptions.HTTPException` class.11771141 :param code: the code as integer for the handler1178 :param code_or_exception: the code as integer for the handler, or1179 an arbitrary exception1180 """1181 def decorator(f):1182 self._register_error_handler(None, code_or_exception, f)1183 return f
19 unmodified lines
1203 raise ValueError(1204 'Tried to register a handler for an exception instance {0!r}. '1205 'Handlers can only be registered for exception classes or HTTP error codes.'1206 .format(code_or_exception))1169 12071208 exc_class, code = self._get_exc_class_and_code(code_or_exception)1171 12091210 handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})1211 handlers[exc_class] = f12121213 @setupmethod
95 unmodified lines
13091310 @setupmethod1311 def before_request(self, f):1312 """Registers a function to run before each request.1313 1314 For example, this can be used to open a database connection, or to load1315 the logged in user from the session.13161276 The function will be called without any arguments.1277 If the function returns a non-None value, it's handled as1278 if it was the return value from the view and further1279 request handling is stopped.1317 The function will be called without any arguments. If it returns a1318 non-None value, the value is handled as if it was the return value from1319 the view, and further request handling is stopped.1320 """1321 self.before_request_funcs.setdefault(None, []).append(f)1322 return f1323
47 unmodified lines
1371 that they will fail. If they do execute code that might fail they1372 will have to surround the execution of these code by try/except1373 statements and log occurring errors.13741335 When a teardown function was called because of a exception it will1375 When a teardown function was called because of an exception it will1376 be passed an error object.13771378 The return values of teardown functions are ignored.1379
47 unmodified lines
1427 @setupmethod1428 def shell_context_processor(self, f):1429 """Registers a shell context processor function.14301391 .. versionadded:: 1.01431 .. versionadded:: 0.111432 """1433 self.shell_context_processors.append(f)1434 return f14351436 @setupmethod1437 def url_value_preprocessor(self, f):1398 """Registers a function as URL value preprocessor for all view1399 functions of the application. It's called before the view functions1400 are called and can modify the url values provided.1438 """Register a URL value preprocessor function for all view1439 functions in the application. These functions will be called before the1440 :meth:`before_request` functions.1441 1442 The function can modify the values captured from the matched url before1443 they are passed to the view. For example, this can be used to pop a1444 common language code value and place it in ``g`` rather than pass it to1445 every view.1446 1447 The function is passed the endpoint name and values dict. The return1448 value is ignored.1449 """1450 self.url_value_preprocessors.setdefault(None, []).append(f)1451 return f1452
6 unmodified lines
1459 self.url_default_functions.setdefault(None, []).append(f)1460 return f14611462 def _find_error_handler(self, e):1415 """Finds a registered error handler for the request’s blueprint.1416 Otherwise falls back to the app, returns None if not a suitable1417 handler is found.1463 """Find a registered error handler for a request in this order:1464 blueprint handler for a specific code, app handler for a specific code,1465 blueprint generic HTTPException handler, app generic HTTPException handler,1466 and returns None if a suitable handler is not found.1467 """1468 exc_class, code = self._get_exc_class_and_code(type(e))14691470 def find_handler(handler_map):1471 if not handler_map:1472 return1424 queue = deque(exc_class.__mro__)1425 # Protect from geniuses who might create circular references in1426 # __mro__1427 done = set()14731429 while queue:1430 cls = queue.popleft()1431 if cls in done:1432 continue1433 done.add(cls)1474 for cls in exc_class.__mro__:1475 handler = handler_map.get(cls)1476 if handler is not None:1477 # cache for next time exc_class is raised1478 handler_map[exc_class] = handler1479 return handler14801440 queue.extend(cls.__mro__)1481 # check for any in blueprint or app1482 for name, c in ((request.blueprint, code), (None, code),1483 (request.blueprint, None), (None, None)):1484 handler = find_handler(self.error_handler_spec.get(name, {}).get(c))14851442 # try blueprint handlers1443 handler = find_handler(self.error_handler_spec1444 .get(request.blueprint, {})1445 .get(code))1446 if handler is not None:1447 return handler1486 if handler:1487 return handler14881449 # fall back to app handlers1450 return find_handler(self.error_handler_spec[None].get(code))14511489 def handle_http_exception(self, e):1490 """Handles an HTTP exception. By default this will invoke the1491 registered error handlers and fall back to returning the1492 exception as response.
3 unmodified lines
1496 # Proxy exceptions don't have error codes. We want to always return1497 # those unchanged as errors1498 if e.code is None:1499 return e1463 15001501 handler = self._find_error_handler(e)1502 if handler is None:1503 return e1504 return handler(e)
34 unmodified lines
1539 # ensure not to trash sys.exc_info() at that point in case someone1540 # wants the traceback preserved in handle_http_exception. Of course1541 # we cannot prevent users from trashing it themselves in a custom1542 # trap_http_exception method so that's their fault then.1506 15431544 if isinstance(e, HTTPException) and not self.trap_http_exception(e):1545 return self.handle_http_exception(e)15461547 handler = self._find_error_handler(e)1511 15481549 if handler is None:1550 reraise(exc_type, exc_value, tb)1551 return handler(e)1552
23 unmodified lines
15761577 self.log_exception((exc_type, exc_value, tb))1578 if handler is None:1579 return InternalServerError()1543 return handler(e)1580 return self.finalize_request(handler(e), from_error_handler=True)15811582 def log_exception(self, exc_info):1583 """Logs an exception. This is called by :meth:`handle_exception`1584 if debugging is disabled and right before the handler is called.
59 unmodified lines
1644 if rv is None:1645 rv = self.dispatch_request()1646 except Exception as e:1647 rv = self.handle_user_exception(e)1648 return self.finalize_request(rv)16491650 def finalize_request(self, rv, from_error_handler=False):1651 """Given the return value from a view function this finalizes1652 the request by converting it into a response and invoking the1653 postprocessing functions. This is invoked for both normal1654 request dispatching as well as error handlers.16551656 Because this means that it might be called as a result of a1657 failure a special safe mode is available which can be enabled1658 with the `from_error_handler` flag. If enabled, failures in1659 response processing will be logged and otherwise ignored.16601661 :internal:1662 """1663 response = self.make_response(rv)1664 try:1612 response = self.process_response(response)1613 request_finished.send(self, response=response)1665 response = self.process_response(response)1666 request_finished.send(self, response=response)1667 except Exception:1668 if not from_error_handler:1669 raise1670 self.logger.exception('Request finalizing failed with an '1671 'error while handling an error')1672 return response16731674 def try_trigger_before_first_request_functions(self):1675 """Called before each request and will ensure that it triggers
44 unmodified lines
1720 """1721 return False17221723 def make_response(self, rv):1666 """Converts the return value from a view function to a real1667 response object that is an instance of :attr:`response_class`.1724 """Convert the return value from a view function to an instance of1725 :attr:`response_class`.17261669 The following types are allowed for `rv`:1727 :param rv: the return value from the view function. The view function1728 must return a response. Returning ``None``, or the view ending1729 without returning, is not allowed. The following types are allowed1730 for ``view_rv``:17311671 .. tabularcolumns:: |p{3.5cm}|p{9.5cm}|1732 ``str`` (``unicode`` in Python 2)1733 A response object is created with the string encoded to UTF-81734 as the body.1735 1736 ``bytes`` (``str`` in Python 2)1737 A response object is created with the bytes as the body.1738 1739 ``tuple``1740 Either ``(body, status, headers)``, ``(body, status)``, or1741 ``(body, headers)``, where ``body`` is any of the other types1742 allowed here, ``status`` is a string or an integer, and1743 ``headers`` is a dictionary or a list of ``(key, value)``1744 tuples. If ``body`` is a :attr:`response_class` instance,1745 ``status`` overwrites the exiting value and ``headers`` are1746 extended.1747 1748 :attr:`response_class`1749 The object is returned unchanged.1750 1751 other :class:`~werkzeug.wrappers.Response` class1752 The object is coerced to :attr:`response_class`.1753 1754 :func:`callable`1755 The function is called as a WSGI application. The result is1756 used to create a response object.17571673 ======================= ===========================================1674 :attr:`response_class` the object is returned unchanged1675 :class:`str` a response object is created with the1676 string as body1677 :class:`unicode` a response object is created with the1678 string encoded to utf-8 as body1679 a WSGI function the function is called as WSGI application1680 and buffered as response object1681 :class:`tuple` A tuple in the form ``(response, status,1682 headers)`` or ``(response, headers)``1683 where `response` is any of the1684 types defined here, `status` is a string1685 or an integer and `headers` is a list or1686 a dictionary with header values.1687 ======================= ===========================================16881689 :param rv: the return value from the view function16901758 .. versionchanged:: 0.91759 Previously a tuple was interpreted as the arguments for the1760 response object.1761 """1695 status_or_headers = headers = None1696 if isinstance(rv, tuple):1697 rv, status_or_headers, headers = rv + (None,) * (3 - len(rv))17621699 if rv is None:1700 raise ValueError('View function did not return a response')1763 status = headers = None17641702 if isinstance(status_or_headers, (dict, list)):1703 headers, status_or_headers = status_or_headers, None1765 # unpack tuple returns1766 if isinstance(rv, (tuple, list)):1767 len_rv = len(rv)17681769 # a 3-tuple is unpacked directly1770 if len_rv == 3:1771 rv, status, headers = rv1772 # decide if a 2-tuple has status or headers1773 elif len_rv == 2:1774 if isinstance(rv[1], (Headers, dict, tuple, list)):1775 rv, headers = rv1776 else:1777 rv, status = rv1778 # other sized tuples are not allowed1779 else:1780 raise TypeError(1781 'The view function did not return a valid response tuple.'1782 ' The tuple must have the form (body, status, headers),'1783 ' (body, status), or (body, headers).'1784 )17851786 # the body must not be None1787 if rv is None:1788 raise TypeError(1789 'The view function did not return a valid response. The'1790 ' function either returned None or ended without a return'1791 ' statement.'1792 )17931794 # make sure the body is an instance of the response class1795 if not isinstance(rv, self.response_class):1706 # When we create a response object directly, we let the constructor1707 # set the headers and status. We do this because there can be1708 # some extra logic involved when creating these objects with1709 # specific values (like default content type selection).1796 if isinstance(rv, (text_type, bytes, bytearray)):1711 rv = self.response_class(rv, headers=headers,1712 status=status_or_headers)1713 headers = status_or_headers = None1797 # let the response class set the status and headers instead of1798 # waiting to do it manually, so that the class can handle any1799 # special logic1800 rv = self.response_class(rv, status=status, headers=headers)1801 status = headers = None1802 else:1803 # evaluate a WSGI callable, or coerce a different response1804 # class to the correct type1805 try:1715 rv = self.response_class.force_type(rv, request.environ)1806 rv = self.response_class.force_type(rv, request.environ)1807 except TypeError as e:1808 new_error = TypeError(1809 '{e}\nThe view function did not return a valid'1810 ' response. The return type must be a string, tuple,'1811 ' Response instance, or WSGI callable, but it was a'1812 ' {rv.__class__.__name__}.'.format(e=e, rv=rv)1813 )1814 reraise(TypeError, new_error, sys.exc_info()[2])18151816 # prefer the status if it was provided1717 if status_or_headers is not None:1718 if isinstance(status_or_headers, string_types):1719 rv.status = status_or_headers1817 if status is not None:1818 if isinstance(status, (text_type, bytes, bytearray)):1819 rv.status = status1820 else:1721 rv.status_code = status_or_headers1821 rv.status_code = status18221823 # extend existing headers with provided headers1824 if headers:1825 rv.headers.extend(headers)18261827 return rv
42 unmodified lines
1870 try:1871 rv = handler(error, endpoint, values)1872 if rv is not None:1873 return rv1772 except BuildError as error:1773 pass1874 except BuildError as e:1875 # make error available outside except block (py3)1876 error = e18771878 # At this point we want to reraise the exception. If the error is1879 # still the same one we can reraise it with the original traceback,1880 # otherwise we raise it from here.
1 unmodified line
1882 reraise(exc_type, exc_value, tb)1883 raise error18841885 def preprocess_request(self):1783 """Called before the actual request dispatching and will1784 call each :meth:`before_request` decorated function, passing no1785 arguments.1786 If any of these functions returns a value, it's handled as1787 if it was the return value from the view and further1788 request handling is stopped.17891790 This also triggers the :meth:`url_value_processor` functions before1791 the actual :meth:`before_request` functions are called.1886 """Called before the request is dispatched. Calls1887 :attr:`url_value_preprocessors` registered with the app and the1888 current blueprint (if any). Then calls :attr:`before_request_funcs`1889 registered with the app and the blueprint.1890 1891 If any :meth:`before_request` handler returns a non-None value, the1892 value is handled as if it was the return value from the view, and1893 further request handling is stopped.1894 """18951896 bp = _request_ctx_stack.top.request.blueprint18971898 funcs = self.url_value_preprocessors.get(None, ())1899 if bp is not None and bp in self.url_value_preprocessors:
151 unmodified lines
2051 a list of headers and an optional2052 exception context to start the response2053 """2054 ctx = self.request_context(environ)1952 ctx.push()2055 error = None2056 try:2057 try:2058 ctx.push()2059 response = self.full_dispatch_request()2060 except Exception as e:2061 error = e1959 response = self.make_response(self.handle_exception(e))2062 response = self.handle_exception(e)2063 except:2064 error = sys.exc_info()[1]2065 raise2066 return response(environ, start_response)2067 finally:2068 if self.should_ignore_error(error):2069 error = None2070 ctx.auto_pop(error)20711966 @property1967 def modules(self):1968 from warnings import warn1969 warn(DeprecationWarning('Flask.modules is deprecated, use '1970 'Flask.blueprints instead'), stacklevel=2)1971 return self.blueprints19722072 def __call__(self, environ, start_response):2073 """Shortcut for :attr:`wsgi_app`."""2074 return self.wsgi_app(environ, start_response)2075
5 unmodified lines
modified:flask/blueprints.py+8 added-2 removed
87 unmodified lines
8889 warn_on_modifications = False90 _got_registered_once = False9192 #: Blueprint local JSON decoder class to use.93 #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_encoder`.94 json_encoder = None95 #: Blueprint local JSON decoder class to use.96 #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_decoder`.97 json_decoder = None9899 def __init__(self, name, import_name, static_folder=None,100 static_url_path=None, template_folder=None,101 url_prefix=None, subdomain=None, url_defaults=None,102 root_path=None):
4 unmodified lines
107 self.subdomain = subdomain108 self.static_folder = static_folder109 self.static_url_path = static_url_path110 self.deferred_functions = []104 self.view_functions = {}111 if url_defaults is None:112 url_defaults = {}113 self.url_values_defaults = url_defaults114
298 unmodified lines
413 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.416411 .. 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+229 added-106 removed
1# -*- coding: utf-8 -*-2"""3 flask.run3 flask.cli4 ~~~~~~~~~56 A simple command line application to run flask apps.7
2 unmodified lines
10"""1112import os13import sys14from threading import Lock, Thread14import traceback15from functools import update_wrapper16from operator import attrgetter17from threading import Lock, Thread1819import click2021from . import __version__22from ._compat import iteritems, reraise23from .globals import current_app24from .helpers import get_debug_flag25from ._compat import getargspec262728class NoAppException(click.UsageError):29 """Raised if an application cannot be found or loaded."""303126def find_best_app(module):32def find_best_app(script_info, module):33 """Given a module instance this tries to find the best possible34 application in the module or raises an exception.35 """36 from . import Flask3738 # Search for the most common names first.33 for attr_name in 'app', 'application':39 for attr_name in ('app', 'application'):40 app = getattr(module, attr_name, None)35 if app is not None and isinstance(app, Flask):41 if isinstance(app, Flask):42 return app4344 # Otherwise find the only object that is a Flask instance.39 matches = [v for k, v in iteritems(module.__dict__)40 if isinstance(v, Flask)]45 matches = [46 v for k, v in iteritems(module.__dict__) if isinstance(v, Flask)47 ]4849 if len(matches) == 1:50 return matches[0]44 raise NoAppException('Failed to find application in module "%s". Are '45 'you sure it contains a Flask application? Maybe '46 'you wrapped it in a WSGI middleware or you are '47 'using a factory function.' % module.__name__)51 elif len(matches) > 1:52 raise NoAppException(53 'Auto-detected multiple Flask applications in module "{module}".'54 ' Use "FLASK_APP={module}:name" to specify the correct'55 ' one.'.format(module=module.__name__)56 )5758 # Search for app factory callables.59 for attr_name in ('create_app', 'make_app'):60 app_factory = getattr(module, attr_name, None)6162 if callable(app_factory):63 try:64 app = call_factory(app_factory, script_info)65 if isinstance(app, Flask):66 return app67 except TypeError:68 raise NoAppException(69 'Auto-detected "{callable}()" in module "{module}", but '70 'could not call it without specifying arguments.'.format(71 callable=attr_name, module=module.__name__72 )73 )7475 raise NoAppException(76 'Failed to find application in module "{module}". Are you sure '77 'it contains a Flask application? Maybe you wrapped it in a WSGI '78 'middleware.'.format(module=module.__name__)79 )808182def call_factory(func, script_info):83 """Checks if the given app factory function has an argument named 84 ``script_info`` or just a single argument and calls the function passing 85 ``script_info`` if so. Otherwise, calls the function without any arguments86 and returns the result.87 """88 arguments = getargspec(func).args89 if 'script_info' in arguments:90 return func(script_info=script_info)91 elif len(arguments) == 1:92 return func(script_info)93 return func()949596def prepare_exec_for_file(filename):97 """Given a filename this will try to calculate the python path, add it98 to the search path and return the actual module name that is expected.99 """100 module = []101102 # Chop off file extensions or package markers57 if filename.endswith('.py'):58 filename = filename[:-3]59 elif os.path.split(filename)[1] == '__init__.py':103 if os.path.split(filename)[1] == '__init__.py':104 filename = os.path.dirname(filename)105 elif filename.endswith('.py'):106 filename = filename[:-3]107 else:108 raise NoAppException('The file provided (%s) does exist but is not a '109 'valid Python file. This means that it cannot '110 'be used as application. Please change the '
10 unmodified lines
121 sys.path.insert(0, dirpath)122 return '.'.join(module[::-1])12312479def locate_app(app_id):125def locate_app(script_info, app_id):126 """Attempts to locate the application."""127 __traceback_hide__ = True128 if ':' in app_id:129 module, app_obj = app_id.split(':', 1)130 else:131 module = app_id132 app_obj = None133134 try:88 __import__(module)135 __import__(module)136 except ImportError:137 # Reraise the ImportError if it occurred within the imported module.138 # Determine this by checking whether the trace has a depth > 1.139 if sys.exc_info()[-1].tb_next:140 stack_trace = traceback.format_exc()141 raise NoAppException('There was an error trying to import'142 ' the app (%s):\n%s' % (module, stack_trace))143 else:144 raise NoAppException('The file/path provided (%s) does not appear'145 ' to exist. Please verify the path is '146 'correct. If app is not on PYTHONPATH, '147 'ensure the extension is .py' % module)148149 mod = sys.modules[module]150 if app_obj is None:91 app = find_best_app(mod)151 app = find_best_app(script_info, mod)152 else:153 app = getattr(mod, app_obj, None)154 if app is None:155 raise RuntimeError('Failed to find application in module "%s"'
1 unmodified line
157158 return app159160161def find_default_import_path():162 app = os.environ.get('FLASK_APP')163 if app is None:164 return165 if os.path.isfile(app):166 return prepare_exec_for_file(app)167 return app168169170def get_version(ctx, param, value):171 if not value or ctx.resilient_parsing:172 return173 message = 'Flask %(version)s\nPython %(python_version)s'174 click.echo(message % {175 'version': __version__,176 'python_version': sys.version,177 }, color=ctx.color)178 ctx.exit()179180version_option = click.Option(['--version'],181 help='Show the flask version',182 expose_value=False,183 callback=get_version,184 is_flag=True, is_eager=True)185186class DispatchingApp(object):102 """Special application that dispatches to a flask application which187 """Special application that dispatches to a Flask application which188 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 case189 it is recorded and shown as part of the WSGI handling which in case190 of the Werkzeug debugger means that it shows up in the browser.191 """192193 def __init__(self, loader, use_eager_loading=False):
45 unmodified lines
239240class ScriptInfo(object):241 """Help object to deal with Flask applications. This is usually not242 necessary to interface with as it's used internally in the dispatching158 to click.243 to click. In future versions of Flask this object will most likely play244 a bigger role. Typically it's created automatically by the245 :class:`FlaskGroup` but you can also manually create it and pass it246 onwards as click object.247 """248161 def __init__(self, app_import_path=None, debug=None, create_app=None):162 #: The application import path249 def __init__(self, app_import_path=None, create_app=None):250 if create_app is None:251 if app_import_path is None:252 app_import_path = find_default_import_path()253 self.app_import_path = app_import_path254 else:255 app_import_path = None256257 #: Optionally the import path for the Flask application.258 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 = debug259 #: Optionally a function that is passed the script info to create260 #: the instance of the application.261 self.create_app = create_app262 #: A dictionary with arbitrary data that can be associated with
9 unmodified lines
272 __traceback_hide__ = True273 if self._loaded_app is not None:274 return self._loaded_app275 if self.create_app is not None:184 rv = self.create_app(self)276 rv = call_factory(self.create_app, self)277 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.')190 rv = locate_app(self.app_import_path)191 if self.debug is not None:192 rv.debug = self.debug278 if not self.app_import_path:279 raise NoAppException(280 'Could not locate Flask application. You did not provide '281 'the FLASK_APP environment variable.\n\nFor more '282 'information see '283 'http://flask.pocoo.org/docs/latest/quickstart/')284 rv = locate_app(self, self.app_import_path)285 debug = get_debug_flag()286 if debug is not None:287 rv.debug = debug288 self._loaded_app = rv289 return rv290291
12 unmodified lines
304 return __ctx.invoke(f, *args, **kwargs)305 return update_wrapper(decorator, f)306307213def set_debug_value(ctx, param, value):214 ctx.ensure_object(ScriptInfo).debug = value215216217def 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 = value224225226debug_option = click.Option(['--debug/--no-debug'],227 help='Enable or disable debug mode.',228 default=None, callback=set_debug_value)229230231app_option = click.Option(['-a', '--app'],232 help='The application to run',233 callback=set_app_value, is_eager=True)234235308class AppGroup(click.Group):309 """This works similar to a regular click :class:`~click.Group` but it310 changes the behavior of the :meth:`command` decorator so that it311 automatically wraps the functions in :func:`with_appcontext`.
32 unmodified lines
344 For information as of why this is useful see :ref:`custom-scripts`.345346 :param add_default_commands: if this is True then the default run and347 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.348 :param add_version_option: adds the ``--version`` option.349 :param create_app: an optional callback that is passed the script info350 and returns the loaded app.351 """352284 def __init__(self, add_default_commands=True, add_app_option=None,285 add_debug_option=True, create_app=None, **extra):353 def __init__(self, add_default_commands=True, create_app=None,354 add_version_option=True, **extra):355 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)356357 if add_version_option:358 params.append(version_option)359360 AppGroup.__init__(self, params=params, **extra)361 self.create_app = create_app362363 if add_default_commands:364 self.add_command(run_command)365 self.add_command(shell_command)366 self.add_command(routes_command)367368 self._loaded_plugin_commands = False369370 def _load_plugin_commands(self):371 if self._loaded_plugin_commands:372 return373 try:374 import pkg_resources375 except ImportError:376 self._loaded_plugin_commands = True377 return378379 for ep in pkg_resources.iter_entry_points('flask.commands'):380 self.add_command(ep.load(), ep.name)381 self._loaded_plugin_commands = True382383 def get_command(self, ctx, name):384 self._load_plugin_commands()385386 # We load built-in commands first as these should always be the387 # same no matter what the app does. If the app does want to388 # override this it needs to make a custom instance of this group389 # and not attach the default commands.
12 unmodified lines
402 except NoAppException:403 pass404405 def list_commands(self, ctx):406 self._load_plugin_commands()407408 # The commands available is the list of both the application (if409 # available) plus the builtin commands.410 rv = set(click.Group.list_commands(self, ctx))411 info = ctx.ensure_object(ScriptInfo)
3 unmodified lines
415 # Here we intentionally swallow all exceptions as we don't416 # want the help page to break if the app does not exist.417 # If someone attempts to use the command we try to create418 # the app again and this will give us the error.333 pass419 # However, we will not do so silently because that would confuse420 # users.421 traceback.print_exc()422 return sorted(rv)423424 def main(self, *args, **kwargs):425 obj = kwargs.get('obj')
3 unmodified lines
429 kwargs.setdefault('auto_envvar_prefix', 'FLASK')430 return AppGroup.main(self, *args, **kwargs)431432345def 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.350351 :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.')359360 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 value366367 kwargs['callback'] = callback368 kwargs.setdefault('is_eager', True)369 return click.option(*args, **kwargs)370371433@click.command('run', short_help='Runs a development server.')434@click.option('--host', '-h', default='127.0.0.1',435 help='The interface to bind to.')436@click.option('--port', '-p', default=5000,
23 unmodified lines
460 The reloader and debugger are by default enabled if the debug flag of461 Flask is enabled and disabled otherwise.462 """463 from werkzeug.serving import run_simple464465 # Set a global flag that indicates that we were invoked from the466 # command line interface provided server command. This is detected467 # by Flask.run to make the call into a no-op. This is necessary to468 # avoid ugly errors when the script that is loaded here also attempts469 # to start a server.470 os.environ['FLASK_RUN_FROM_CLI_SERVER'] = '1'471472 debug = get_debug_flag()473 if reload is None:404 reload = info.debug474 reload = bool(debug)475 if debugger is None:406 debugger = info.debug476 debugger = bool(debug)477 if eager_loading is None:478 eager_loading = not reload479480 app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)481412 # Extra startup messages. This depends a but on Werkzeug internals to482 # Extra startup messages. This depends a bit on Werkzeug internals to483 # not double execute when the reloader kicks in.484 if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':485 # If we have an import path we can print it out now which can help486 # people understand what's being served. If we do not have an487 # import path because the app was loaded through a callback then488 # we won't print anything.489 if info.app_import_path is not None:490 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'))491 if debug is not None:492 print(' * Forcing debug mode %s' % (debug and 'on' or 'off'))493494 run_simple(host, port, app, use_reloader=reload,495 use_debugger=debugger, threaded=with_threads)496
31 unmodified lines
528529 code.interact(banner=banner, local=ctx)530531532@click.command('routes', short_help='Show the routes for the app.')533@click.option(534 '--sort', '-s',535 type=click.Choice(('endpoint', 'methods', 'rule', 'match')),536 default='endpoint',537 help=(538 'Method to sort routes by. "match" is the order that Flask will match '539 'routes when dispatching a request.'540 )541)542@click.option(543 '--all-methods',544 is_flag=True,545 help="Show HEAD and OPTIONS methods."546)547@with_appcontext548def routes_command(sort, all_methods):549 """Show all registered routes with endpoints and methods."""550551 rules = list(current_app.url_map.iter_rules())552 ignored_methods = set(() if all_methods else ('HEAD', 'OPTIONS'))553554 if sort in ('endpoint', 'rule'):555 rules = sorted(rules, key=attrgetter(sort))556 elif sort == 'methods':557 rules = sorted(rules, key=lambda rule: sorted(rule.methods))558559 rule_methods = [560 ', '.join(sorted(rule.methods - ignored_methods)) for rule in rules561 ]562563 headers = ('Endpoint', 'Methods', 'Rule')564 widths = (565 max(len(rule.endpoint) for rule in rules),566 max(len(methods) for methods in rule_methods),567 max(len(rule.rule) for rule in rules),568 )569 widths = [max(len(h), w) for h, w in zip(headers, widths)]570 row = '{{0:<{0}}} {{1:<{1}}} {{2:<{2}}}'.format(*widths)571572 click.echo(row.format(*headers).strip())573 click.echo(row.format(*('-' * width for width in widths)))574575 for rule, methods in zip(rules, rule_methods):576 click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())577578579cli = FlaskGroup(help="""\580This shell command acts as general utility script for Flask applications.581465It loads the application configured (either through the FLASK_APP environment466variable or the --app parameter) and then provides commands either provided467by the application or Flask itself.582It loads the application configured (through the FLASK_APP environment583variable) and then provides commands either provided by the application or584Flask itself.585586The most useful commands are the "run" and "shell" command.587588Example usage:589473 flask --app=hello --debug run474""")590\b591 %(prefix)s%(cmd)s FLASK_APP=hello.py592 %(prefix)s%(cmd)s FLASK_DEBUG=1593 %(prefix)sflask run594""" % {595 'cmd': os.name == 'posix' and 'export' or 'set',596 'prefix': os.name == 'posix' and '$ ' or '',597})598599600def main(as_module=False):601 this_module = __package__ + '.cli'
20 unmodified lines
modified:flask/config.py+13 added-8 removed
124 unmodified lines
125 filename = os.path.join(self.root_path, filename)126 d = types.ModuleType('config')127 d.__file__ = filename128 try:129 with open(filename) as config_file:129 with open(filename, mode='rb') as config_file:130 exec(compile(config_file.read(), filename, 'exec'), d.__dict__)131 except IOError as e:132 if silent and e.errno in (errno.ENOENT, errno.EISDIR):133 return False
8 unmodified lines
142143 - a string: in this case the object with that name will be imported144 - an actual object reference: that object is used directly145146 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.150148 Just the uppercase variables in that object are stored in the config.149 Example usage::151 Example of module-based configuration::152153 app.config.from_object('yourapplication.default_config')154 from yourapplication import default_config155 app.config.from_object(default_config)
2 unmodified lines
158 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.161162 See :ref:`config-dev-prod` for an example of class-based configuration163 using :meth:`from_object`.164165 :param obj: an import name or object166 """167 if isinstance(obj, string_types):168 obj = import_string(obj)
11 unmodified lines
180 root path.181 :param silent: set to ``True`` if you want silent failure for missing182 files.183179 .. versionadded:: 1.0184 .. versionadded:: 0.11185 """186 filename = os.path.join(self.root_path, filename)187188 try:
9 unmodified lines
198 def from_mapping(self, *mapping, **kwargs):199 """Updates the config like :meth:`update` ignoring items with non-upper200 keys.201197 .. versionadded:: 1.0202 .. versionadded:: 0.11203 """204 mappings = []205 if len(mapping) == 1:206 if hasattr(mapping[0], 'items'):
19 unmodified lines
226 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_')229225 The resulting dictionary `image_store` would look like::230 The resulting dictionary `image_store_config` would look like::231232 {233 'type': 'fs',234 'path': '/var/app/images',
8 unmodified lines
243 dictionary should be lowercase244 :param trim_namespace: a flag indicating if the keys of the resulting245 dictionary should not include the namespace246242 .. versionadded:: 1.0247 .. versionadded:: 0.11248 """249 rv = {}250 for k, v in iteritems(self):251 if not k.startswith(namespace):
12 unmodified lines
modified:flask/ctx.py+46 added-35 removed
7 unmodified lines
8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112from __future__ import with_statement1312import sys13from functools import update_wrapper1415from werkzeug.exceptions import HTTPException
12 unmodified lines
2829 def get(self, name, default=None):30 return self.__dict__.get(name, default)3132 def pop(self, name, default=_sentinel):33 if default is _sentinel:34 return self.__dict__.pop(name)35 else:36 return self.__dict__.pop(name, default)3738 def setdefault(self, name, default=None):39 return self.__dict__.setdefault(name, default)4041 def __contains__(self, item):42 return item in self.__dict__4344 def __iter__(self):
135 unmodified lines
180 appcontext_pushed.send(self.app)181182 def pop(self, exc=_sentinel):183 """Pops the app context."""184 try:177 self._refcnt -= 1178 if self._refcnt <= 0:179 if exc is _sentinel:180 exc = sys.exc_info()[1]181 self.app.do_teardown_appcontext(exc)182 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 lines
342 Added the `exc` argument.343 """344 app_ctx = self._implicit_app_ctx_stack.pop()345346 try:337 clear_request = False338 if not self._implicit_app_ctx_stack:339 self.preserved = False340 self._preserved_exc = None341 if exc is _sentinel:342 exc = sys.exc_info()[1]343 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)354345 # If this interpreter supports clearing the exception information346 # we do that now. This will only go into effect on Python 2.x,347 # on 3.x it disappears automatically at the end of the exception348 # stack.349 if hasattr(sys, 'exc_clear'):350 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()361352 request_close = getattr(self.request, 'close', None)353 if request_close is not None:354 request_close()355 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()368357 rv = _request_ctx_stack.pop()358 assert rv is self, 'Popped wrong request context. (%r instead of %r)' \359 % (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'] = None373361 # get rid of circular dependencies at the end of the request362 # so that we don't require the GC to be active.363 if clear_request:364 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)377366 # Get rid of the app as well if necessary.367 if app_ctx is not None:368 app_ctx.pop(exc)378 assert rv is self, 'Popped wrong request context. ' \379 '(%r instead of %r)' % (rv, self)380381 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 lines
modified:flask/debughelpers.py+12 added
6 unmodified lines
78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import os12from warnings import warn1314from ._compat import implements_to_string, text_type15from .app import Flask16from .blueprints import Blueprint17from .globals import _request_ctx_stack
137 unmodified lines
155 info.append(' Maybe you did not place a template in the right folder?')156 info.append(' See http://flask.pocoo.org/docs/blueprints/#templates')157158 app.logger.info('\n'.join(info))159160161def explain_ignored_app_run():162 if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':163 warn(Warning('Silently ignoring app.run() because the '164 'application is run from the flask command line '165 'executable. Consider putting app.run() behind an '166 'if __name__ == "__main__" guard to silence this '167 'warning.'), stacklevel=3)
modified:flask/exthook.py+25 added-2 removed
19 unmodified lines
20 :license: BSD, see LICENSE for more details.21"""22import sys23import os24import warnings25from ._compat import reraise262728class ExtDeprecationWarning(DeprecationWarning):29 pass3031warnings.simplefilter('always', ExtDeprecationWarning)323334class 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 lines
55 def install(self):56 sys.meta_path[:] = [x for x in sys.meta_path if self != x] + [self]5758 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 self6263 def load_module(self, fullname):64 if fullname in sys.modules:65 return sys.modules[fullname]6667 modname = fullname.split('.', self.prefix_cutoff)[self.prefix_cutoff]6869 warnings.warn(70 "Importing flask.ext.{x} is deprecated, use flask_{x} instead."71 .format(x=modname), ExtDeprecationWarning, stacklevel=272 )7374 for path in self.module_choices:75 realname = path % modname76 try:77 __import__(realname)
19 unmodified lines
97 continue98 module = sys.modules[fullname] = sys.modules[realname]99 if '.' not in modname:100 setattr(sys.modules[self.wrapper_module], modname, module)101102 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 )108109 return module110 raise ImportError('No module named %s' % fullname)111112 def is_important_traceback(self, important_module, tb):
20 unmodified lines
133 # name shows up properly here. Success!134 if module_name == important_module:135 return True136114 # Some python versions will will clean up modules so early that the137 # Some python versions will clean up modules so early that the138 # module name at that point is no longer set. Try guessing from139 # the filename then.140 filename = os.path.abspath(tb.tb_frame.f_code.co_filename)141 test_string = os.path.sep + important_module.replace('.', os.path.sep)
2 unmodified lines
modified:flask/helpers.py+197 added-75 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""1112import os13import socket14import sys15import pkgutil16import posixpath17import mimetypes18from time import time19from zlib import adler3220from threading import RLock21import unicodedata22from werkzeug.routing import BuildError23from functools import update_wrapper2425try:26 from werkzeug.urls import url_quote27except ImportError:28 from urlparse import quote as url_quote2928from werkzeug.datastructures import Headers29from werkzeug.exceptions import NotFound30from werkzeug.datastructures import Headers, Range31from werkzeug.exceptions import BadRequest, NotFound, \32 RequestedRangeNotSatisfiable3334# this was moved in 0.735try:36 from werkzeug.wsgi import wrap_file
18 unmodified lines
55_os_alt_seps = list(sep for sep in [os.path.sep, os.path.altsep]56 if sep not in (None, '/'))575859def get_debug_flag(default=None):60 val = os.environ.get('FLASK_DEBUG')61 if not val:62 return default63 return val.lower() not in ('0', 'false', 'no')646566def _endpoint_from_view_func(view_func):67 """Internal helper that returns the default endpoint for a given68 function. This always is the function name.69 """
39 unmodified lines
109 try:110 gen = iter(generator_or_function)111 except TypeError:112 def decorator(*args, **kwargs):103 gen = generator_or_function()113 gen = generator_or_function(*args, **kwargs)114 return stream_with_context(gen)115 return update_wrapper(decorator, generator_or_function)116117 def generator():
190 unmodified lines
308 method = values.pop('_method', None)309 scheme = values.pop('_scheme', None)310 appctx.app.inject_url_defaults(endpoint, values)311312 # This is not the best way to deal with this but currently the313 # underlying Werkzeug router does not support overriding the scheme on314 # a per build call basis.315 old_scheme = None316 if scheme is not None:317 if not external:318 raise ValueError('When specifying _scheme, _external must be True')319 old_scheme = url_adapter.url_scheme320 url_adapter.url_scheme = scheme321322 try:323 try:308 rv = url_adapter.build(endpoint, values, method=method,309 force_external=external)324 rv = url_adapter.build(endpoint, values, method=method,325 force_external=external)326 finally:327 if old_scheme is not None:328 url_adapter.url_scheme = old_scheme329 except BuildError as error:330 # We need to inject the values again so that the app callback can331 # deal with that sort of stuff.332 values['_external'] = external333 values['_anchor'] = anchor334 values['_method'] = method335 values['_scheme'] = scheme336 return appctx.app.handle_url_build_error(error, endpoint, values)337338 if anchor is not None:339 rv += '#' + url_quote(anchor)
92 unmodified lines
432433434def send_file(filename_or_fp, mimetype=None, as_attachment=False,435 attachment_filename=None, add_etags=True,416 cache_timeout=None, conditional=False):436 cache_timeout=None, conditional=False, last_modified=None):437 """Sends the contents of a file to the client. This will use the438 most efficient method available and configured. By default it will439 try to use the WSGI server's file_wrapper support. Alternatively440 you can set the application's :attr:`~Flask.use_x_sendfile` attribute
5 unmodified lines
446 to send certain files as attachment (HTML for instance). The mimetype447 guessing requires a `filename` or an `attachment_filename` to be448 provided.449450 ETags will also be attached automatically if a `filename` is provided. You451 can turn this off by setting `add_etags=False`.452453 If `conditional=True` and `filename` is provided, this method will try to454 upgrade the response stream to support range requests. This will allow455 the request to be answered with partial content response.456457 Please never pass filenames to this function from user sources;458 you should use :func:`send_from_directory` instead.459460 .. versionadded:: 0.2
10 unmodified lines
471472 .. versionchanged:: 0.9473 cache_timeout pulls its default from application config, when None.474448 :param filename_or_fp: the filename of the file to send. This is449 relative to the :attr:`~Flask.root_path` if a450 relative path is specified.451 Alternatively a file object might be provided452 in which case ``X-Sendfile`` might not work and453 fall back to the traditional method. Make sure454 that the file pointer is positioned at the start455 of data to send before calling :func:`send_file`.456 :param mimetype: the mimetype of the file if provided, otherwise457 auto detection happens.475 .. versionchanged:: 0.12476 The filename is no longer automatically inferred from file objects. If477 you want to use automatic mimetype and etag support, pass a filepath via478 `filename_or_fp` or `attachment_filename`.479480 .. versionchanged:: 0.12481 The `attachment_filename` is preferred over `filename` for MIME-type482 detection.483 484 .. versionchanged:: 0.13485 UTF-8 filenames, as specified in `RFC 2231`_, are supported.486 487 .. _RFC 2231: https://tools.ietf.org/html/rfc2231#section-4488489 :param filename_or_fp: the filename of the file to send.490 This is relative to the :attr:`~Flask.root_path`491 if a relative path is specified.492 Alternatively a file object might be provided in493 which case ``X-Sendfile`` might not work and fall494 back to the traditional method. Make sure that the495 file pointer is positioned at the start of data to496 send before calling :func:`send_file`.497 :param mimetype: the mimetype of the file if provided. If a file path is498 given, auto detection happens as fallback, otherwise an499 error will be raised.500 :param as_attachment: set to ``True`` if you want to send this file with501 a ``Content-Disposition: attachment`` header.502 :param attachment_filename: the filename for the attachment if it503 differs from the file's filename.
3 unmodified lines
507 :param cache_timeout: the timeout in seconds for the headers. When ``None``508 (default), this value is set by509 :meth:`~Flask.get_send_file_max_age` of510 :data:`~flask.current_app`.511 :param last_modified: set the ``Last-Modified`` header to this value,512 a :class:`~datetime.datetime` or timestamp.513 If a file was passed, this overrides its mtime.514 """515 mtime = None516 fsize = None517 if isinstance(filename_or_fp, string_types):518 filename = filename_or_fp519 if not os.path.isabs(filename):520 filename = os.path.join(current_app.root_path, filename)521 file = None522 if attachment_filename is None:523 attachment_filename = os.path.basename(filename)524 else:475 from warnings import warn525 file = filename_or_fp477 filename = getattr(file, 'name', None)526 filename = None527479 # XXX: this behavior is now deprecated because it was unreliable.480 # removed in Flask 1.0481 if not attachment_filename and not mimetype \482 and isinstance(filename, string_types):483 warn(DeprecationWarning('The filename support for file objects '484 'passed to send_file is now deprecated. Pass an '485 'attach_filename if you want mimetypes to be guessed.'),486 stacklevel=2)487 if add_etags:488 warn(DeprecationWarning('In future flask releases etags will no '489 'longer be generated for file objects passed to the send_file '490 'function because this behavior was unreliable. Pass '491 'filenames instead if possible, otherwise attach an etag '492 'yourself based on another value'), stacklevel=2)493494 if filename is not None:495 if not os.path.isabs(filename):496 filename = os.path.join(current_app.root_path, filename)497 if mimetype is None and (filename or attachment_filename):498 mimetype = mimetypes.guess_type(filename or attachment_filename)[0]528 if mimetype is None:529 if attachment_filename is not None:530 mimetype = mimetypes.guess_type(attachment_filename)[0] \500 mimetype = 'application/octet-stream'531 or 'application/octet-stream'532533 if mimetype is None:534 raise ValueError(535 'Unable to infer MIME-type because no filename is available. '536 'Please set either `attachment_filename`, pass a filepath to '537 '`filename_or_fp` or set your own MIME-type via `mimetype`.'538 )539540 headers = Headers()541 if as_attachment:542 if attachment_filename is None:505 if filename is None:506 raise TypeError('filename unavailable, required for '507 'sending as attachment')543 raise TypeError('filename unavailable, required for '544 'sending as attachment')508 attachment_filename = os.path.basename(filename)509 headers.add('Content-Disposition', 'attachment',510 filename=attachment_filename)545546 try:547 attachment_filename = attachment_filename.encode('latin-1')548 except UnicodeEncodeError:549 filenames = {550 'filename': unicodedata.normalize(551 'NFKD', attachment_filename).encode('latin-1', 'ignore'),552 'filename*': "UTF-8''%s" % url_quote(attachment_filename),553 }554 else:555 filenames = {'filename': attachment_filename}556557 headers.add('Content-Disposition', 'attachment', **filenames)558559 if current_app.use_x_sendfile and filename:560 if file is not None:561 file.close()562 headers['X-Sendfile'] = filename516 headers['Content-Length'] = os.path.getsize(filename)563 fsize = os.path.getsize(filename)564 headers['Content-Length'] = fsize565 data = None566 else:567 if file is None:568 file = open(filename, 'rb')569 mtime = os.path.getmtime(filename)522 headers['Content-Length'] = os.path.getsize(filename)570 fsize = os.path.getsize(filename)571 headers['Content-Length'] = fsize572 data = wrap_file(request.environ, file)573574 rv = current_app.response_class(data, mimetype=mimetype, headers=headers,575 direct_passthrough=True)576528 # if we know the file modification date, we can store it as529 # the time of the last modification.530 if mtime is not None:531 rv.last_modified = int(mtime)577 if last_modified is not None:578 rv.last_modified = last_modified579 elif mtime is not None:580 rv.last_modified = mtime581582 rv.cache_control.public = True583 if cache_timeout is None:584 cache_timeout = current_app.get_send_file_max_age(filename)
1 unmodified line
586 rv.cache_control.max_age = cache_timeout587 rv.expires = int(time() + cache_timeout)588589 if add_etags and filename is not None:590 from warnings import warn591592 try:542 rv.set_etag('flask-%s-%s-%s' % (593 rv.set_etag('%s-%s-%s' % (594 os.path.getmtime(filename),595 os.path.getsize(filename),596 adler32(597 filename.encode('utf-8') if isinstance(filename, text_type)
3 unmodified lines
601 except OSError:602 warn('Access %s failed, maybe it does not exist, so ignore etags in '603 'headers' % filename, stacklevel=2)604554 if conditional:605 if conditional:606 if callable(getattr(Range, 'to_content_range_header', None)):607 # Werkzeug supports Range Requests608 # Remove this test when support for Werkzeug <0.12 is dropped609 try:610 rv = rv.make_conditional(request, accept_ranges=True,611 complete_length=fsize)612 except RequestedRangeNotSatisfiable:613 file.close()614 raise615 else:616 rv = rv.make_conditional(request)556 # make sure we don't send x-sendfile for servers that557 # ignore the 304 status code for x-sendfile.558 if rv.status_code == 304:559 rv.headers.pop('x-sendfile', None)617 # make sure we don't send x-sendfile for servers that618 # ignore the 304 status code for x-sendfile.619 if rv.status_code == 304:620 rv.headers.pop('x-sendfile', None)621 return rv622623563def safe_join(directory, filename):564 """Safely join `directory` and `filename`.624def safe_join(directory, *pathnames):625 """Safely join `directory` and zero or more untrusted `pathnames`626 components.627628 Example usage::629630 @app.route('/wiki/<path:filename>')
1 unmodified line
632 filename = safe_join(app.config['WIKI_FOLDER'], filename)633 with open(filename, 'rb') as fd:634 content = fd.read() # Read and process the file content...635574 :param directory: the base directory.575 :param filename: the untrusted filename relative to that directory.576 :raises: :class:`~werkzeug.exceptions.NotFound` if the resulting path577 would fall out of `directory`.636 :param directory: the trusted base directory.637 :param pathnames: the untrusted pathnames relative to that directory.638 :raises: :class:`~werkzeug.exceptions.NotFound` if one or more passed639 paths fall out of its boundaries.640 """579 filename = posixpath.normpath(filename)580 for sep in _os_alt_seps:581 if sep in filename:641642 parts = [directory]643644 for filename in pathnames:645 if filename != '':646 filename = posixpath.normpath(filename)647648 if (649 any(sep in filename for sep in _os_alt_seps)650 or os.path.isabs(filename)651 or filename == '..'652 or filename.startswith('../')653 ):654 raise NotFound()583 if os.path.isabs(filename) or \584 filename == '..' or \585 filename.startswith('../'):586 raise NotFound()587 return os.path.join(directory, filename)655656 parts.append(filename)657658 return posixpath.join(*parts)659660661def send_from_directory(directory, filename, **options):662 """Send a file from a given directory with :func:`send_file`. This663 is a secure way to quickly expose static files from an upload folder664 or something similar.
22 unmodified lines
687 """688 filename = safe_join(directory, filename)689 if not os.path.isabs(filename):690 filename = os.path.join(current_app.root_path, filename)691 try:620 if not os.path.isfile(filename):621 raise NotFound()692 if not os.path.isfile(filename):693 raise NotFound()694 except (TypeError, ValueError):695 raise BadRequest()696 options.setdefault('conditional', True)697 return send_file(filename, **options)698699
171 unmodified lines
871 if self._static_folder is not None:872 return os.path.join(self.root_path, self._static_folder)873 def _set_static_folder(self, value):874 self._static_folder = value801 static_folder = property(_get_static_folder, _set_static_folder)875 static_folder = property(_get_static_folder, _set_static_folder, doc='''876 The absolute path to the configured static folder.877 ''')878 del _get_static_folder, _set_static_folder879880 def _get_static_url_path(self):881 if self._static_url_path is not None:
47 unmodified lines
929 return flask.Flask.get_send_file_max_age(self, name)930931 .. versionadded:: 0.9932 """857 return current_app.config['SEND_FILE_MAX_AGE_DEFAULT']933 return total_seconds(current_app.send_file_max_age_default)934935 def send_static_file(self, filename):936 """Function used internally to send static files from the static937 folder to the browser.
33 unmodified lines
971 """972 if mode not in ('r', 'rb'):973 raise ValueError('Resources can only be opened for reading')974 return open(os.path.join(self.root_path, resource), mode)975976977def total_seconds(td):978 """Returns the total seconds from a timedelta object.979980 :param timedelta td: the timedelta to be converted in seconds981982 :returns: number of seconds983 :rtype: int984 """985 return td.days * 60 * 60 * 24 + td.seconds986987988def is_ip(value):989 """Determine if the given string is an IP address.990991 :param value: value to check992 :type value: str993994 :return: True if string is an IP address995 :rtype: bool996 """997998 for family in (socket.AF_INET, socket.AF_INET6):999 try:1000 socket.inet_pton(family, value)1001 except socket.error:1002 pass1003 else:1004 return True10051006 return False100710081009def patch_vary_header(response, value):1010 """Add a value to the ``Vary`` header if it is not already present."""10111012 header = response.headers.get('Vary', '')1013 headers = [h for h in (h.strip() for h in header.split(',')) if h]1014 lower_value = value.lower()10151016 if not any(h.lower() == lower_value for h in headers):1017 headers.append(value)10181019 updated_header = ', '.join(headers)1020 response.headers['Vary'] = updated_header
modified:flask/json.py+54 added-29 removed
1# -*- coding: utf-8 -*-2"""3 flask.jsonimpl4 ~~~~~~~~~~~~~~3 flask.json4 ~~~~~~~~~~56 Implementation helpers for the JSON support in Flask.78 :copyright: (c) 2015 by Armin Ronacher.
9 unmodified lines
18from jinja2 import Markup1920# Use the same json implementation as itsdangerous on which we21# depend anyways.22try:23 from itsdangerous import simplejson as _json24except ImportError:25 from itsdangerous import json as _json22from itsdangerous import json as _json232425# Figure out if simplejson escapes slashes. This behavior was changed26# from one version to another without reason.
63 unmodified lines
9091def _dump_arg_defaults(kwargs):92 """Inject default arguments for dump functions."""93 if current_app:97 kwargs.setdefault('cls', current_app.json_encoder)94 bp = current_app.blueprints.get(request.blueprint) if request else None95 kwargs.setdefault(96 'cls',97 bp.json_encoder if bp and bp.json_encoder98 else current_app.json_encoder99 )100101 if not current_app.config['JSON_AS_ASCII']:102 kwargs.setdefault('ensure_ascii', False)103104 kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS'])105 else:106 kwargs.setdefault('sort_keys', True)107 kwargs.setdefault('cls', JSONEncoder)
1 unmodified line
109110def _load_arg_defaults(kwargs):111 """Inject default arguments for load functions."""112 if current_app:109 kwargs.setdefault('cls', current_app.json_decoder)113 bp = current_app.blueprints.get(request.blueprint) if request else None114 kwargs.setdefault(115 'cls',116 bp.json_decoder if bp and bp.json_decoder117 else current_app.json_decoder118 )119 else:120 kwargs.setdefault('cls', JSONDecoder)121122
80 unmodified lines
203204205def htmlsafe_dump(obj, fp, **kwargs):206 """Like :func:`htmlsafe_dumps` but writes into a file object."""198 fp.write(unicode(htmlsafe_dumps(obj, **kwargs)))207 fp.write(text_type(htmlsafe_dumps(obj, **kwargs)))208209210def 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.211 """This function wraps :func:`dumps` to add a few enhancements that make212 life easier. It turns the JSON output into a :class:`~flask.Response`213 object with the :mimetype:`application/json` mimetype. For convenience, it214 also converts multiple arguments into an array or multiple keyword arguments215 into a dict. This means that both ``jsonify(1,2,3)`` and216 ``jsonify([1,2,3])`` serialize to ``[1,2,3]``.217218 For clarity, the JSON serialization behavior has the following differences219 from :func:`dumps`:220221 1. Single argument: Passed straight through to :func:`dumps`.222 2. Multiple arguments: Converted to an array before being passed to223 :func:`dumps`.224 3. Multiple keyword arguments: Converted to a dict before being passed to225 :func:`dumps`.226 4. Both args and kwargs: Behavior undefined and will throw an exception.227228 Example usage::229230 from flask import jsonify231
10 unmodified lines
242 "email": "admin@localhost",243 "id": 42244 }245225 For security reasons only objects are supported toplevel. For more226 information about this, have a look at :ref:`json-security`.246228 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.247 .. versionchanged:: 0.11248 Added support for serializing top-level arrays. This introduces a249 security risk in ancient browsers. See :ref:`json-security` for details.250251 This function's response will be pretty printed if the252 ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to True or the253 Flask app is running in debug mode. Compressed (not pretty) formatting254 currently means no indents and no spaces after separators.255256 .. versionadded:: 0.2257 """258259 indent = None260 separators = (',', ':')261240 if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] \241 and not request.is_xhr:262 if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug:263 indent = 2264 separators = (', ', ': ')265245 # 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 rv266 if args and kwargs:267 raise TypeError('jsonify() behavior undefined when passed both args and kwargs')268 elif len(args) == 1: # single args are passed directly to dumps()269 data = args[0]270 else:271 data = args or kwargs272273 return current_app.response_class(274 (dumps(data, indent=indent, separators=separators), '\n'),275 mimetype=current_app.config['JSONIFY_MIMETYPE']276 )277278279def tojson_filter(obj, **kwargs):280 return Markup(htmlsafe_dumps(obj, **kwargs))
modified:flask/logging.py+4 added
85 unmodified lines
86 del logger.handlers[:]87 logger.__class__ = DebugLogger88 logger.addHandler(debug_handler)89 logger.addHandler(prod_handler)9091 # Disable propagation by default92 logger.propagate = False9394 return logger
modified:flask/sessions.py+132 added-70 removed
7 unmodified lines
8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import uuid12import hashlib13import uuid14import warnings14from base64 import b64encode, b64decode15from base64 import b64decode, b64encode16from datetime import datetime16from werkzeug.http import http_date, parse_date1718from itsdangerous import BadSignature, URLSafeTimedSerializer19from werkzeug.datastructures import CallbackDict20from werkzeug.http import http_date, parse_date2122from flask.helpers import patch_vary_header23from . import Markup, json24from ._compat import iteritems, text_type25from .helpers import is_ip, total_seconds2621from itsdangerous import URLSafeTimedSerializer, BadSignature272324def total_seconds(td):25 return td.days * 60 * 60 * 24 + td.seconds262728class SessionMixin(object):29 """Expands a basic dictionary with an accessors that are expected30 by Flask extensions and users for the session.31 """
18 unmodified lines
50 #: long as changes do not happen on mutable structures in the session.51 #: The default mixin implementation just hardcodes ``True`` in.52 modified = True5354 #: the accessed variable indicates whether or not the session object has55 #: been accessed in that request. This allows flask to append a `Vary:56 #: Cookie` header to the response if the session is being accessed. This57 #: allows caching proxy servers, like Varnish, to use both the URL and the58 #: session cookie as keys when caching pages, preventing multiple users59 #: from being served the same cache.60 accessed = True6162def _tag(value):63 if isinstance(value, tuple):64 return {' t': [_tag(x) for x in value]}
28 unmodified lines
9394 def dumps(self, value):95 return json.dumps(_tag(value), separators=(',', ':'))9697 LOADS_MAP = {98 ' t': tuple,99 ' u': uuid.UUID,100 ' b': b64decode,101 ' m': Markup,102 ' d': parse_date,103 }104105 def loads(self, value):106 def object_hook(obj):107 if len(obj) != 1:108 return obj109 the_key, the_value = next(iteritems(obj))95 if the_key == ' t':96 return tuple(the_value)97 elif the_key == ' u':98 return uuid.UUID(the_value)99 elif the_key == ' b':100 return b64decode(the_value)101 elif the_key == ' m':102 return Markup(the_value)103 elif the_key == ' d':104 return parse_date(the_value)110 # Check the key for a corresponding function111 return_function = self.LOADS_MAP.get(the_key)112 if return_function:113 # Pass the value to the function114 return return_function(the_value)115 # Didn't find a function for this object116 return obj117 return json.loads(value, object_hook=object_hook)118119
5 unmodified lines
125126 def __init__(self, initial=None):127 def on_update(self):128 self.modified = True118 CallbackDict.__init__(self, initial, on_update)129 self.accessed = True130131 super(SecureCookieSession, self).__init__(initial, on_update)132 self.modified = False133 self.accessed = False134135 def __getitem__(self, key):136 self.accessed = True137 return super(SecureCookieSession, self).__getitem__(key)138139 def get(self, key, default=None):140 self.accessed = True141 return super(SecureCookieSession, self).get(key, default)142143 def setdefault(self, key, default=None):144 self.accessed = True145 return super(SecureCookieSession, self).setdefault(key, default)146147148class NullSession(SecureCookieSession):149 """Class used to generate nicer error messages if sessions are not150 available. Will still allow read-only access to the empty session151 but fail on setting.
44 unmodified lines
196 #: this type.197 null_session_class = NullSession198199 #: A flag that indicates if the session interface is pickle based.174 #: This can be used by flask extensions to make a decision in regards200 #: This can be used by Flask extensions to make a decision in regards201 #: to how to deal with the session object.202 #:203 #: .. versionadded:: 0.10204 pickle_based = False
19 unmodified lines
224 """225 return isinstance(obj, self.null_session_class)226227 def get_cookie_domain(self, app):202 """Helpful helper method that returns the cookie domain that should203 be used for the session cookie if session cookies are used.228 """Returns the domain that should be set for the session cookie.229 230 Uses ``SESSION_COOKIE_DOMAIN`` if it is configured, otherwise231 falls back to detecting the domain based on ``SERVER_NAME``.232 233 Once detected (or if not set at all), ``SESSION_COOKIE_DOMAIN`` is234 updated to avoid re-running the logic.235 """205 if app.config['SESSION_COOKIE_DOMAIN'] is not None:206 return app.config['SESSION_COOKIE_DOMAIN']207 if app.config['SERVER_NAME'] is not None:208 # chop off the port which is usually not supported by browsers209 rv = '.' + app.config['SERVER_NAME'].rsplit(':', 1)[0]236211 # Google chrome does not like cookies set to .localhost, so212 # we just go with no domain then. Flask documents anyways that213 # cross domain cookies need a fully qualified domain name214 if rv == '.localhost':215 rv = None237 rv = app.config['SESSION_COOKIE_DOMAIN']238217 # If we infer the cookie domain from the server name we need218 # to check if we are in a subpath. In that case we can't219 # set a cross domain cookie.220 if rv is not None:221 path = self.get_cookie_path(app)222 if path != '/':223 rv = rv.lstrip('.')239 # set explicitly, or cached from SERVER_NAME detection240 # if False, return None241 if rv is not None:242 return rv if rv else None243225 return rv244 rv = app.config['SERVER_NAME']245246 # server name not set, cache False to return none next time247 if not rv:248 app.config['SESSION_COOKIE_DOMAIN'] = False249 return None250251 # chop off the port which is usually not supported by browsers252 # remove any leading '.' since we'll add that later253 rv = rv.rsplit(':', 1)[0].lstrip('.')254255 if '.' not in rv:256 # Chrome doesn't allow names without a '.'257 # this should only come up with localhost258 # hack around this by not setting the name, and show a warning259 warnings.warn(260 '"{rv}" is not a valid cookie domain, it must contain a ".".'261 ' Add an entry to your hosts file, for example'262 ' "{rv}.localdomain", and use that instead.'.format(rv=rv)263 )264 app.config['SESSION_COOKIE_DOMAIN'] = False265 return None266267 ip = is_ip(rv)268269 if ip:270 warnings.warn(271 'The session cookie domain is an IP address. This may not work'272 ' as intended in some browsers. Add an entry to your hosts'273 ' file, for example "localhost.localdomain", and use that'274 ' instead.'275 )276277 # if this is not an ip and app is mounted at the root, allow subdomain278 # matching by adding a '.' prefix279 if self.get_cookie_path(app) == '/' and not ip:280 rv = '.' + rv281282 app.config['SESSION_COOKIE_DOMAIN'] = rv283 return rv284285 def get_cookie_path(self, app):286 """Returns the path for which the cookie should be valid. The287 default implementation uses the value from the ``SESSION_COOKIE_PATH``288 config var if it's set, and falls back to ``APPLICATION_ROOT`` or
24 unmodified lines
313 if session.permanent:314 return datetime.utcnow() + app.permanent_session_lifetime315316 def should_set_cookie(self, app, session):259 """Indicates whether a cookie should be set now or not. This is260 used by session backends to figure out if they should emit a261 set-cookie header or not. The default behavior is controlled by262 the ``SESSION_REFRESH_EACH_REQUEST`` config variable. If263 it's set to ``False`` then a cookie is only set if the session is264 modified, if set to ``True`` it's always set if the session is265 permanent.317 """Used by session backends to determine if a ``Set-Cookie`` header318 should be set for this session cookie for this response. If the session319 has been modified, the cookie is set. If the session is permanent and320 the ``SESSION_REFRESH_EACH_REQUEST`` config is true, the cookie is321 always set.322 323 This check is usually skipped if the session was deleted.324267 This check is usually skipped if sessions get deleted.268269 .. versionadded:: 1.0325 .. versionadded:: 0.11326 """271 if session.modified:272 return True273 save_each = app.config['SESSION_REFRESH_EACH_REQUEST']274 return save_each and session.permanent327328 return session.modified or (329 session.permanent and app.config['SESSION_REFRESH_EACH_REQUEST']330 )331332 def open_session(self, app, request):333 """This method has to be implemented and must either return ``None``334 in case the loading failed because of a configuration error or an335 instance of a session object which implements a dictionary like
56 unmodified lines
392 def save_session(self, app, session, response):393 domain = self.get_cookie_domain(app)394 path = self.get_cookie_path(app)395340 # Delete case. If there is no session we bail early.341 # If the session was modified to be empty we remove the342 # whole cookie.396 # If the session is modified to be empty, remove the cookie.397 # If the session is empty, return without setting the cookie.398 if not session:399 if session.modified:345 response.delete_cookie(app.session_cookie_name,346 domain=domain, path=path)400 response.delete_cookie(401 app.session_cookie_name,402 domain=domain,403 path=path404 )405406 return407349 # Modification case. There are upsides and downsides to350 # emitting a set-cookie header each request. The behavior351 # is controlled by the :meth:`should_set_cookie` method352 # which performs a quick check to figure out if the cookie353 # should be set or not. This is controlled by the354 # SESSION_REFRESH_EACH_REQUEST config flag as well as355 # the permanent flag on the session itself.408 # Add a "Vary: Cookie" header if the session was accessed at all.409 if session.accessed:410 patch_vary_header(response, 'Cookie')411412 if not self.should_set_cookie(app, session):413 return414415 httponly = self.get_cookie_httponly(app)416 secure = self.get_cookie_secure(app)417 expires = self.get_expiration_time(app, session)418 val = self.get_signing_serializer(app).dumps(dict(session))363 response.set_cookie(app.session_cookie_name, val,364 expires=expires, httponly=httponly,365 domain=domain, path=path, secure=secure)419 response.set_cookie(420 app.session_cookie_name,421 val,422 expires=expires,423 httponly=httponly,424 domain=domain,425 path=path,426 secure=secure427 )
modified:flask/signals.py+2 added-1 removed
35 unmodified lines
36 connect = disconnect = has_receivers_for = receivers_for = \37 temporarily_connected_to = connected_to = _fail38 del _fail3940# The namespace for code signals. If you are not flask code, do40# The namespace for code signals. If you are not Flask code, do41# not put signals in here. Create your own namespace instead.42_signals = Namespace()434445# Core signals. For usage examples grep the source code or consult46# the API documentation in docs/api.rst as well as docs/signals.rst47template_rendered = _signals.signal('template-rendered')48before_render_template = _signals.signal('before-render-template')49request_started = _signals.signal('request-started')50request_finished = _signals.signal('request-finished')51request_tearing_down = _signals.signal('request-tearing-down')52got_request_exception = _signals.signal('got-request-exception')
4 unmodified lines
modified:flask/templating.py+24 added-13 removed
10 unmodified lines
11from jinja2 import BaseLoader, Environment as BaseEnvironment, \12 TemplateNotFound1314from .globals import _request_ctx_stack, _app_ctx_stack15from .signals import template_rendered15from .signals import template_rendered, before_render_template161718def _default_template_ctx_processor():19 """Default template context processor. Injects `request`,
31 unmodified lines
51 def __init__(self, app):52 self.app = app5354 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)5859 def _get_source_explained(self, environment, template):60 attempts = []57 tmplrv = None61 trv = None6263 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))7170 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)7474 if tmplrv is not None:75 return tmplrv75 if trv is not None:76 return trv77 raise TemplateNotFound(template)7879 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)8687 def _iter_loaders(self, template):88 loader = self.app.jinja_loader89 if loader is not None:90 yield self.app, loader
19 unmodified lines
110111112def _render(template, context, app):113 """Renders the template and fires the signal"""114115 before_render_template.send(app, template=template, context=context)116 rv = template.render(context)117 template_rendered.send(app, template=template, context=context)118 return rv119
15 unmodified lines
135136137def render_template_string(source, **context):138 """Renders a template from the given template source string128 with the given context.139 with the given context. Template variables will be autoescaped.140141 :param source: the source code of the template to be142 rendered143 :param context: the variables that should be available in the
6 unmodified lines
modified:flask/testing.py+19 added-4 removed
8 unmodified lines
9 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213import werkzeug14from contextlib import contextmanager15from werkzeug.test import Client, EnvironBuilder16from flask import _request_ctx_stack17
21 unmodified lines
3940class 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`.4647 .. versionchanged:: 0.1248 `app.test_client()` includes preset default environment, which can be49 set after instantiation of the `app.test_client()` object in50 `client.environ_base`.5152 Basic usage is outlined in the :ref:`testing` chapter.53 """5455 preserve_context = False5657 def __init__(self, *args, **kwargs):58 super(FlaskClient, self).__init__(*args, **kwargs)59 self.environ_base = {60 "REMOTE_ADDR": "127.0.0.1",61 "HTTP_USER_AGENT": "werkzeug/" + werkzeug.__version__62 }6364 @contextmanager65 def session_transaction(self, *args, **kwargs):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.7071 ::72
40 unmodified lines
113114 def open(self, *args, **kwargs):115 kwargs.setdefault('environ_overrides', {}) \116 ['flask._preserve_context'] = self.preserve_context117 kwargs.setdefault('environ_base', self.environ_base)118119 as_tuple = kwargs.pop('as_tuple', False)120 buffered = kwargs.pop('buffered', False)121 follow_redirects = kwargs.pop('follow_redirects', False)
22 unmodified lines
modified:flask/views.py+27 added-19 removed
46 unmodified lines
47 based decorators since those would decorate the view class and not the48 generated view function!49 """5051 #: A for which methods this pluggable view can handle.51 #: A list of methods this view can handle.52 methods = None5354 #: Setting this disables or force-enables the automatic options handling.55 provide_automatic_options = None5657 #: The canonical way to decorate class-based views is to decorate the58 #: return value of as_view(). However since this moves parts of the59 #: logic from the class declaration to the place where it's hooked60 #: into the routing system.
40 unmodified lines
101 view.__name__ = name102 view.__doc__ = cls.__doc__103 view.__module__ = cls.__module__104 view.methods = cls.methods105 view.provide_automatic_options = cls.provide_automatic_options106 return view107108109class MethodViewType(type):110 """Metaclass for :class:`MethodView` that determines what methods the view111 defines.112 """113107 def __new__(cls, name, bases, d):108 rv = type.__new__(cls, name, bases, d)114 def __init__(cls, name, bases, d):115 super(MethodViewType, cls).__init__(name, bases, d)116117 if 'methods' not in d:110 methods = set(rv.methods or [])111 for key in d:112 if key in http_method_funcs:118 methods = set()119120 for key in http_method_funcs:121 if hasattr(cls, key):122 methods.add(key.upper())114 # If we have no method at all in there we don't want to115 # add a method list. (This is for instance the case for116 # the base class or another subclass of a base method view117 # that does not introduce new methods).123124 # If we have no method at all in there we don't want to add a125 # method list. This is for instance the case for the base class126 # or another subclass of a base method view that does not introduce127 # new methods.128 if methods:119 rv.methods = sorted(methods)120 return rv129 cls.methods = methods130131132class MethodView(with_metaclass(MethodViewType, View)):124 """Like a regular class-based view but that dispatches requests to125 particular methods. For instance if you implement a method called126 :meth:`get` it means you will response to ``'GET'`` requests and127 the :meth:`dispatch_request` implementation will automatically128 forward your request to that. Also :attr:`options` is set for you129 automatically::133 """A class-based view that dispatches request methods to the corresponding134 class methods. For example, if you implement a ``get`` method, it will be135 used to handle ``GET`` requests. ::136137 class CounterAPI(MethodView):132138 def get(self):139 return session.get('counter', 0)140141 def post(self):
1 unmodified line
143 return 'OK'144145 app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))146 """147148 def dispatch_request(self, *args, **kwargs):149 meth = getattr(self, request.method.lower(), None)150151 # If the request method is HEAD and we don't have a handler for it152 # retry with GET.153 if meth is None and request.method == 'HEAD':154 meth = getattr(self, 'get', None)155156 assert meth is not None, 'Unimplemented method %r' % request.method157 return meth(*args, **kwargs)
modified:flask/wrappers.py+9 added-7 removed
111 unmodified lines
112 """Indicates if this request is JSON or not. By default a request113 is considered to include JSON data if the mimetype is114 :mimetype:`application/json` or :mimetype:`application/*+json`.115116 .. versionadded:: 1.0116 .. versionadded:: 0.11117 """118 mt = self.mimetype119 if mt == 'application/json':120 return True
1 unmodified line
122 return True123 return False124125 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.132133 :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 rv143144 if not (force or self.is_json):145 return None
60 unmodified lines
modified:scripts/flask-07-upgrade.py+3 added-2 removed
3 unmodified lines
4 flask-07-upgrade5 ~~~~~~~~~~~~~~~~67 This command line script scans a whole application tree and attempts to8 output an unified diff with all the changes that are necessary to easily8 output a unified diff with all the changes that are necessary to easily9 upgrade the application to 0.7 and to not yield deprecation warnings.1011 This will also attempt to find `after_request` functions that don't modify12 the response and appear to be better suited for `teardown_request`.
5 unmodified lines
1819 :copyright: (c) Copyright 2015 by Armin Ronacher.20 :license: see LICENSE for more details.21"""22from __future__ import print_function23import re24import os25import inspect26import difflib
32 unmodified lines
59 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)646566def looks_like_teardown_function(node):67 returns = [x for x in ast.walk(node) if isinstance(x, ast.Return)]
231 unmodified lines
deleted: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 201578from redbaron import RedBaron9import sys101112def 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 red171819def 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())232425def 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 red303132def fix_from_imports(red):33 """34 Converts "from" style imports to not use "flask.ext".3536 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 red646566def 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 pass8485 return red868788def _get_modules(module):89 """90 Takes a list of modules and converts into a string.9192 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:]+[''])]101102 return ''.join(modules_string)103104105def fix_function_calls(red):106 """107 Modifies function calls in the source to reflect import changes.108109 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 pass120121 return red122123124def _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() + "."136137138def 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.")142143144def 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()149150151def 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)159160161if __name__ == "__main__":162 fix()
modified:scripts/flaskext_tester.py+2 added-2 removed
110 unmodified lines
111'''112113114def log(msg, *args):115 print '[EXTTEST]', msg % args115 print('[EXTTEST] ' + (msg % args))116117118class TestResult(object):119
181 unmodified lines
301 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))306307308if __name__ == '__main__':309 main()
modified:scripts/make-release.py+4 added-10 removed
8 unmodified lines
910 :copyright: (c) 2015 by Armin Ronacher.11 :license: BSD, see LICENSE for more details.12"""13from __future__ import print_function14import sys15import os16import re17from datetime import datetime, date
62 unmodified lines
80 info('Setting __init__.py version to %s', version)81 set_filename_version('flask/__init__.py', version, '__version__')828383def set_setup_version(version):84 info('Setting setup.py version to %s', version)85 set_filename_version('setup.py', version, 'version')868784def 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()868788def fail(message, *args):93 print >> sys.stderr, 'Error:', message % args89 print('Error:', message % args, file=sys.stderr)90 sys.exit(1)919293def info(message, *args):98 print >> sys.stderr, message % args94 print(message % args, file=sys.stderr)959697def get_git_tags():98 return set(Popen(['git', 'tag'], stdout=PIPE).communicate()[0].splitlines())
36 unmodified lines
135 if not git_is_clean():136 fail('You have uncommitted changes in git')137138 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)143144145if __name__ == '__main__':146 main()
deleted:scripts/test_import_migration.py-77 removed
1# Tester for the flaskext_migrate.py module located in flask/scripts/2#3# Author: Keyan Pishdadian4import pytest5from redbaron import RedBaron6import flaskext_migrate as migrate789def test_simple_from_import():10 red = RedBaron("from flask.ext import foo")11 output = migrate.fix_tester(red)12 assert output == "import flask_foo as foo"131415def test_from_to_from_import():16 red = RedBaron("from flask.ext.foo import bar")17 output = migrate.fix_tester(red)18 assert output == "from flask_foo import bar as bar"192021def test_multiple_import():22 red = RedBaron("from flask.ext.foo import bar, foobar, something")23 output = migrate.fix_tester(red)24 assert output == "from flask_foo import bar, foobar, something"252627def test_multiline_import():28 red = RedBaron("from flask.ext.foo import \29 bar,\30 foobar,\31 something")32 output = migrate.fix_tester(red)33 assert output == "from flask_foo import bar, foobar, something"343536def test_module_import():37 red = RedBaron("import flask.ext.foo")38 output = migrate.fix_tester(red)39 assert output == "import flask_foo"404142def test_named_module_import():43 red = RedBaron("import flask.ext.foo as foobar")44 output = migrate.fix_tester(red)45 assert output == "import flask_foo as foobar"464748def test_named_from_import():49 red = RedBaron("from flask.ext.foo import bar as baz")50 output = migrate.fix_tester(red)51 assert output == "from flask_foo import bar as baz"525354def test_parens_import():55 red = RedBaron("from flask.ext.foo import (bar, foo, foobar)")56 output = migrate.fix_tester(red)57 assert output == "from flask_foo import (bar, foo, foobar)"585960def test_function_call_migration():61 red = RedBaron("flask.ext.foo(var)")62 output = migrate.fix_tester(red)63 assert output == "flask_foo(var)"646566def test_nested_function_call_migration():67 red = RedBaron("import flask.ext.foo\n\n"68 "flask.ext.foo.bar(var)")69 output = migrate.fix_tester(red)70 assert output == ("import flask_foo\n\n"71 "flask_foo.bar(var)")727374def test_no_change_to_import():75 red = RedBaron("from flask import Flask")76 output = migrate.fix_tester(red)77 assert output == "from flask import Flask"
added:tests/templates/non_escaping_template.txt+8 added
1{{ text }}2{{ html }}3{% autoescape false %}{{ text }}4{{ html }}{% endautoescape %}5{% autoescape true %}{{ text }}6{{ html }}{% endautoescape %}7{{ text }}8{{ html }}
added:tests/test_apps/cliapp/__init__.py
added:tests/test_apps/cliapp/app.py+5 added
1from __future__ import absolute_import, print_function23from flask import Flask45testapp = Flask('testapp')
added:tests/test_apps/cliapp/importerrorapp.py+7 added
1from __future__ import absolute_import, print_function23from flask import Flask45raise ImportError()67testapp = Flask('testapp')
added:tests/test_apps/cliapp/multiapp.py+6 added
1from __future__ import absolute_import, print_function23from flask import Flask45app1 = Flask('app1')6app2 = Flask('app2')
modified:tests/conftest.py+60 added-20 removed
5 unmodified lines
6 :copyright: (c) 2015 by the Flask Team, see AUTHORS for more details.7 :license: BSD, see LICENSE for more details.8"""9import flask10import gc11import os12import sys13import pkgutil14import pytest15import textwrap16from flask import Flask as _Flask171819class Flask(_Flask):20 testing = True21 secret_key = __name__2223 def make_response(self, rv):24 if rv is None:25 rv = ''26 return super(Flask, self).make_response(rv)272829@pytest.fixture30def app():31 app = Flask(__name__)32 return app333435@pytest.fixture36def app_ctx(app):37 with app.app_context() as ctx:38 yield ctx394041@pytest.fixture42def req_ctx(app):43 with app.test_request_context() as ctx:44 yield ctx454647@pytest.fixture48def client(app):49 return app.test_client()505152@pytest.fixture53def test_apps(monkeypatch):54 monkeypatch.syspath_prepend(55 os.path.abspath(os.path.join(56 os.path.dirname(__file__), 'test_apps'))57 )585960@pytest.fixture(autouse=True)25def leak_detector(request):26 def ensure_clean_request_context():27 # make sure we're not leaking a request context since we are28 # testing flask internally in debug mode in a few cases29 leaks = []30 while flask._request_ctx_stack.top is not None:31 leaks.append(flask._request_ctx_stack.pop())32 assert leaks == []33 request.addfinalizer(ensure_clean_request_context)61def leak_detector():62 yield6364 # make sure we're not leaking a request context since we are65 # testing flask internally in debug mode in a few cases66 leaks = []67 while flask._request_ctx_stack.top is not None:68 leaks.append(flask._request_ctx_stack.pop())69 assert leaks == []707172@pytest.fixture(params=(True, False))73def limit_loader(request, monkeypatch):74 """Patch pkgutil.get_loader to give loader without get_filename or archive.75
20 unmodified lines
96 old_get_loader = pkgutil.get_loader9798 def get_loader(*args, **kwargs):99 return LimitedLoader(old_get_loader(*args, **kwargs))100101 monkeypatch.setattr(pkgutil, 'get_loader', get_loader)102103104@pytest.fixture105def modules_tmpdir(tmpdir, monkeypatch):69 '''A tmpdir added to sys.path'''106 """A tmpdir added to sys.path."""107 rv = tmpdir.mkdir('modules_tmpdir')108 monkeypatch.syspath_prepend(str(rv))109 return rv110
5 unmodified lines
116117118@pytest.fixture119def site_packages(modules_tmpdir, monkeypatch):83 '''Create a fake site-packages'''120 """Create a fake site-packages."""121 rv = modules_tmpdir \85 .mkdir('lib')\86 .mkdir('python{x[0]}.{x[1]}'.format(x=sys.version_info))\122 .mkdir('lib') \123 .mkdir('python{x[0]}.{x[1]}'.format(x=sys.version_info)) \124 .mkdir('site-packages')125 monkeypatch.syspath_prepend(str(rv))126 return rv127128129@pytest.fixture130def install_egg(modules_tmpdir, monkeypatch):94 '''Generate egg from package name inside base and put the egg into95 sys.path'''131 """Generate egg from package name inside base and put the egg into132 sys.path."""133134 def inner(name, base=modules_tmpdir):135 if not isinstance(name, str):136 raise ValueError(name)137 base.join(name).ensure_dir()
15 unmodified lines
153 )154 egg_path, = modules_tmpdir.join('dist/').listdir()155 monkeypatch.syspath_prepend(str(egg_path))156 return egg_path157158 return inner159160161@pytest.fixture162def purge_module(request):163 def inner(name):164 request.addfinalizer(lambda: sys.modules.pop(name, None))165166 return inner167168129@pytest.fixture130def catch_deprecation_warnings():131 import warnings132 warnings.simplefilter('default', category=DeprecationWarning)133 return lambda: warnings.catch_warnings(record=True)169@pytest.yield_fixture(autouse=True)170def catch_deprecation_warnings(recwarn):171 yield172 gc.collect()173 assert not recwarn.list, '\n'.join(str(w.message) for w in recwarn.list)
modified:tests/test_appctx.py+70 added-20 removed
12 unmodified lines
1314import flask151617def test_basic_url_generation():18 app = flask.Flask(__name__)17def test_basic_url_generation(app):18 app.config['SERVER_NAME'] = 'localhost'19 app.config['PREFERRED_URL_SCHEME'] = 'https'2021 @app.route('/')
3 unmodified lines
25 with app.app_context():26 rv = flask.url_for('index')27 assert rv == 'https://localhost/'2830def test_url_generation_requires_server_name():31 app = flask.Flask(__name__)2930def test_url_generation_requires_server_name(app):31 with app.app_context():32 with pytest.raises(RuntimeError):33 flask.url_for('index')343536def test_url_generation_without_context_fails():37 with pytest.raises(RuntimeError):38 flask.url_for('index')3940def test_request_context_means_app_context():41 app = flask.Flask(__name__)4041def test_request_context_means_app_context(app):42 with app.test_request_context():43 assert flask.current_app._get_current_object() == app44 assert flask._app_ctx_stack.top is None4546def test_app_context_provides_current_app():47 app = flask.Flask(__name__)4647def test_app_context_provides_current_app(app):48 with app.app_context():49 assert flask.current_app._get_current_object() == app50 assert flask._app_ctx_stack.top is None515252def test_app_tearing_down():53def test_app_tearing_down(app):54 cleanup_stuff = []54 app = flask.Flask(__name__)5556 @app.teardown_appcontext57 def cleanup(exception):58 cleanup_stuff.append(exception)59
1 unmodified line
61 pass6263 assert cleanup_stuff == [None]646564def test_app_tearing_down_with_previous_exception():66def test_app_tearing_down_with_previous_exception(app):67 cleanup_stuff = []66 app = flask.Flask(__name__)6869 @app.teardown_appcontext70 def cleanup(exception):71 cleanup_stuff.append(exception)72
6 unmodified lines
79 pass8081 assert cleanup_stuff == [None]828381def test_app_tearing_down_with_handled_exception():84def test_app_tearing_down_with_handled_exception(app):85 cleanup_stuff = []83 app = flask.Flask(__name__)8687 @app.teardown_appcontext88 def cleanup(exception):89 cleanup_stuff.append(exception)90
4 unmodified lines
95 pass9697 assert cleanup_stuff == [None]9899100def test_app_ctx_globals_methods(app, app_ctx):101 # get102 assert flask.g.get('foo') is None103 assert flask.g.get('foo', 'bar') == 'bar'104 # __contains__105 assert 'foo' not in flask.g106 flask.g.foo = 'bar'107 assert 'foo' in flask.g108 # setdefault109 flask.g.setdefault('bar', 'the cake is a lie')110 flask.g.setdefault('bar', 'hello world')111 assert flask.g.bar == 'the cake is a lie'112 # pop113 assert flask.g.pop('bar') == 'the cake is a lie'114 with pytest.raises(KeyError):115 flask.g.pop('bar')116 assert flask.g.pop('bar', 'more cake') == 'more cake'117 # __iter__118 assert list(flask.g) == ['foo']11912096def test_custom_app_ctx_globals_class():121def test_custom_app_ctx_globals_class(app):122 class CustomRequestGlobals(object):123 def __init__(self):124 self.spam = 'eggs'100 app = flask.Flask(__name__)125126 app.app_ctx_globals_class = CustomRequestGlobals127 with app.app_context():128 assert flask.render_template_string('{{ g.spam }}') == 'eggs'129130105def test_context_refcounts():131def test_context_refcounts(app, client):132 called = []107 app = flask.Flask(__name__)133134 @app.teardown_request135 def teardown_req(error=None):136 called.append('request')137138 @app.teardown_appcontext139 def teardown_app(error=None):140 called.append('app')141142 @app.route('/')143 def index():144 with flask._app_ctx_stack.top:145 with flask._request_ctx_stack.top:146 pass147 env = flask._request_ctx_stack.top.request.environ148 assert env['werkzeug.request'] is not None149 return u''122 c = app.test_client()123 res = c.get('/')150151 res = client.get('/')152 assert res.status_code == 200153 assert res.data == b''154 assert called == ['request', 'app']155156157def test_clean_pop(app):158 app.testing = False159 called = []160161 @app.teardown_request162 def teardown_req(error=None):163 1 / 0164165 @app.teardown_appcontext166 def teardown_app(error=None):167 called.append('TEARDOWN')168169 try:170 with app.test_request_context():171 called.append(flask.current_app.name)172 except ZeroDivisionError:173 pass174175 assert called == ['conftest', 'TEARDOWN']176 assert not flask.current_app
modified:tests/test_basic.py+659 added-449 removed
23 unmodified lines
24from werkzeug.routing import BuildError25import werkzeug.serving262728def test_options_work():29 app = flask.Flask(__name__)3028def test_options_work(app, client):29 @app.route('/', methods=['GET', 'POST'])30 def index():31 return 'Hello World'3234 rv = app.test_client().open('/', method='OPTIONS')33 rv = client.open('/', method='OPTIONS')34 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']35 assert rv.data == b''363739def test_options_on_multiple_rules():40 app = flask.Flask(__name__)4138def test_options_on_multiple_rules(app, client):39 @app.route('/', methods=['GET', 'POST'])40 def index():41 return 'Hello World'4243 @app.route('/', methods=['PUT'])44 def index_put():45 return 'Aha!'4649 rv = app.test_client().open('/', method='OPTIONS')47 rv = client.open('/', method='OPTIONS')48 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']495053def test_options_handling_disabled():51def test_provide_automatic_options_attr():52 app = flask.Flask(__name__)5354 def index():55 return 'Hello World!'5657 index.provide_automatic_options = False58 app.route('/')(index)59 rv = app.test_client().open('/', method='OPTIONS')60 assert rv.status_code == 405
1 unmodified line
62 app = flask.Flask(__name__)6364 def index2():65 return 'Hello World!'6667 index2.provide_automatic_options = True68 app.route('/', methods=['OPTIONS'])(index2)69 rv = app.test_client().open('/', method='OPTIONS')70 assert sorted(rv.allow) == ['OPTIONS']717273def test_request_dispatching():74 app = flask.Flask(__name__)73def test_provide_automatic_options_kwarg(app, client):74 def index():75 return flask.request.method7677 def more():78 return flask.request.method7980 app.add_url_rule('/', view_func=index, provide_automatic_options=False)81 app.add_url_rule(82 '/more', view_func=more, methods=['GET', 'POST'],83 provide_automatic_options=False84 )85 assert client.get('/').data == b'GET'8687 rv = client.post('/')88 assert rv.status_code == 40589 assert sorted(rv.allow) == ['GET', 'HEAD']9091 # Older versions of Werkzeug.test.Client don't have an options method92 if hasattr(client, 'options'):93 rv = client.options('/')94 else:95 rv = client.open('/', method='OPTIONS')9697 assert rv.status_code == 4059899 rv = client.head('/')100 assert rv.status_code == 200101 assert not rv.data # head truncates102 assert client.post('/more').data == b'POST'103 assert client.get('/more').data == b'GET'104105 rv = client.delete('/more')106 assert rv.status_code == 405107 assert sorted(rv.allow) == ['GET', 'HEAD', 'POST']108109 if hasattr(client, 'options'):110 rv = client.options('/more')111 else:112 rv = client.open('/more', method='OPTIONS')113114 assert rv.status_code == 405115116117def test_request_dispatching(app, client):118 @app.route('/')119 def index():120 return flask.request.method121122 @app.route('/more', methods=['GET', 'POST'])123 def more():124 return flask.request.method12584 c = app.test_client()85 assert c.get('/').data == b'GET'86 rv = c.post('/')126 assert client.get('/').data == b'GET'127 rv = client.post('/')128 assert rv.status_code == 405129 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']89 rv = c.head('/')130 rv = client.head('/')131 assert rv.status_code == 200132 assert not rv.data # head truncates92 assert c.post('/more').data == b'POST'93 assert c.get('/more').data == b'GET'94 rv = c.delete('/more')133 assert client.post('/more').data == b'POST'134 assert client.get('/more').data == b'GET'135 rv = client.delete('/more')136 assert rv.status_code == 405137 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']13813999def test_disallow_string_for_allowed_methods():100 app = flask.Flask(__name__)140def test_disallow_string_for_allowed_methods(app):141 with pytest.raises(TypeError):142 @app.route('/', methods='GET POST')143 def index():144 return "Hey"145146107def test_url_mapping():108 app = flask.Flask(__name__)109147def test_url_mapping(app, client):148 random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"149150 def index():151 return flask.request.method
3 unmodified lines
155156 def options():157 return random_uuid4158121159 app.add_url_rule('/', 'index', index)160 app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])161162 # Issue 1288: Test that automatic options are not added when non-uppercase 'options' in methods163 app.add_url_rule('/options', 'options', options, methods=['options'])164128 c = app.test_client()129 assert c.get('/').data == b'GET'130 rv = c.post('/')165 assert client.get('/').data == b'GET'166 rv = client.post('/')167 assert rv.status_code == 405168 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']133 rv = c.head('/')169 rv = client.head('/')170 assert rv.status_code == 200171 assert not rv.data # head truncates136 assert c.post('/more').data == b'POST'137 assert c.get('/more').data == b'GET'138 rv = c.delete('/more')172 assert client.post('/more').data == b'POST'173 assert client.get('/more').data == b'GET'174 rv = client.delete('/more')175 assert rv.status_code == 405176 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']141 rv = c.open('/options', method='OPTIONS')177 rv = client.open('/options', method='OPTIONS')178 assert rv.status_code == 200179 assert random_uuid4 in rv.data.decode("utf-8")180181146def test_werkzeug_routing():182def test_werkzeug_routing(app, client):183 from werkzeug.routing import Submount, Rule148 app = flask.Flask(__name__)184 app.url_map.add(Submount('/foo', [185 Rule('/bar', endpoint='bar'),186 Rule('/', endpoint='index')187 ]))
2 unmodified lines
190 return 'bar'191192 def index():193 return 'index'194195 app.view_functions['bar'] = bar196 app.view_functions['index'] = index197162 c = app.test_client()163 assert c.get('/foo/').data == b'index'164 assert c.get('/foo/bar').data == b'bar'198 assert client.get('/foo/').data == b'index'199 assert client.get('/foo/bar').data == b'bar'200201167def test_endpoint_decorator():202def test_endpoint_decorator(app, client):203 from werkzeug.routing import Submount, Rule169 app = flask.Flask(__name__)204 app.url_map.add(Submount('/foo', [205 Rule('/bar', endpoint='bar'),206 Rule('/', endpoint='index')207 ]))
5 unmodified lines
213 @app.endpoint('index')214 def index():215 return 'index'216183 c = app.test_client()184 assert c.get('/foo/').data == b'index'185 assert c.get('/foo/bar').data == b'bar'217 assert client.get('/foo/').data == b'index'218 assert client.get('/foo/bar').data == b'bar'219220188def test_session():189 app = flask.Flask(__name__)221def test_session(app, client):222 app.secret_key = 'testkey'223224 @app.route('/set', methods=['POST'])225 def set():
3 unmodified lines
229 @app.route('/get')230 def get():231 return flask.session['value']232201 c = app.test_client()202 assert c.post('/set', data={'value': '42'}).data == b'value set'203 assert c.get('/get').data == b'42'233 assert client.post('/set', data={'value': '42'}).data == b'value set'234 assert client.get('/get').data == b'42'235236206def test_session_using_server_name():207 app = flask.Flask(__name__)237def test_session_using_server_name(app, client):238 app.config.update(239 SECRET_KEY='foo',240 SERVER_NAME='example.com'241 )
1 unmodified line
243 @app.route('/')244 def index():245 flask.session['testing'] = 42246 return 'Hello World'247217 rv = app.test_client().get('/', 'http://example.com/')248 rv = client.get('/', 'http://example.com/')249 assert 'domain=.example.com' in rv.headers['set-cookie'].lower()250 assert 'httponly' in rv.headers['set-cookie'].lower()251252222def test_session_using_server_name_and_port():223 app = flask.Flask(__name__)253def test_session_using_server_name_and_port(app, client):254 app.config.update(255 SECRET_KEY='foo',256 SERVER_NAME='example.com:8080'257 )
1 unmodified line
259 @app.route('/')260 def index():261 flask.session['testing'] = 42262 return 'Hello World'263233 rv = app.test_client().get('/', 'http://example.com:8080/')264 rv = client.get('/', 'http://example.com:8080/')265 assert 'domain=.example.com' in rv.headers['set-cookie'].lower()266 assert 'httponly' in rv.headers['set-cookie'].lower()267268238def test_session_using_server_name_port_and_path():239 app = flask.Flask(__name__)269def test_session_using_server_name_port_and_path(app, client):270 app.config.update(271 SECRET_KEY='foo',272 SERVER_NAME='example.com:8080',273 APPLICATION_ROOT='/foo'
2 unmodified lines
276 @app.route('/')277 def index():278 flask.session['testing'] = 42279 return 'Hello World'280250 rv = app.test_client().get('/', 'http://example.com:8080/foo')281 rv = client.get('/', 'http://example.com:8080/foo')282 assert 'domain=example.com' in rv.headers['set-cookie'].lower()283 assert 'path=/foo' in rv.headers['set-cookie'].lower()284 assert 'httponly' in rv.headers['set-cookie'].lower()285286256def test_session_using_application_root():287def test_session_using_application_root(app, client):288 class PrefixPathMiddleware(object):258289 def __init__(self, app, prefix):290 self.app = app291 self.prefix = prefix292293 def __call__(self, environ, start_response):294 environ['SCRIPT_NAME'] = self.prefix295 return self.app(environ, start_response)296267 app = flask.Flask(__name__)297 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar')298 app.config.update(299 SECRET_KEY='foo',300 APPLICATION_ROOT='/bar'
2 unmodified lines
303 @app.route('/')304 def index():305 flask.session['testing'] = 42306 return 'Hello World'307278 rv = app.test_client().get('/', 'http://example.com:8080/')308 rv = client.get('/', 'http://example.com:8080/')309 assert 'path=/bar' in rv.headers['set-cookie'].lower()310311282def test_session_using_session_settings():283 app = flask.Flask(__name__)312def test_session_using_session_settings(app, client):313 app.config.update(314 SECRET_KEY='foo',315 SERVER_NAME='www.example.com:8080',316 APPLICATION_ROOT='/test',
6 unmodified lines
323 @app.route('/')324 def index():325 flask.session['testing'] = 42326 return 'Hello World'327298 rv = app.test_client().get('/', 'http://www.example.com:8080/test/')328 rv = client.get('/', 'http://www.example.com:8080/test/')329 cookie = rv.headers['set-cookie'].lower()330 assert 'domain=.example.com' in cookie331 assert 'path=/' in cookie332 assert 'secure' in cookie333 assert 'httponly' not in cookie334335336def test_session_localhost_warning(recwarn, app, client):337 app.config.update(338 SECRET_KEY='testing',339 SERVER_NAME='localhost:5000',340 )341342 @app.route('/')343 def index():344 flask.session['testing'] = 42345 return 'testing'346347 rv = client.get('/', 'http://localhost:5000/')348 assert 'domain' not in rv.headers['set-cookie'].lower()349 w = recwarn.pop(UserWarning)350 assert '"localhost" is not a valid cookie domain' in str(w.message)351352353def test_session_ip_warning(recwarn, app, client):354 app.config.update(355 SECRET_KEY='testing',356 SERVER_NAME='127.0.0.1:5000',357 )358359 @app.route('/')360 def index():361 flask.session['testing'] = 42362 return 'testing'363364 rv = client.get('/', 'http://127.0.0.1:5000/')365 assert 'domain=127.0.0.1' in rv.headers['set-cookie'].lower()366 w = recwarn.pop(UserWarning)367 assert 'cookie domain is an IP' in str(w.message)368369370def test_missing_session():371 app = flask.Flask(__name__)372373 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'374 e = pytest.raises(RuntimeError, f, *args, **kwargs)375 assert e.value.args and 'session is unavailable' in e.value.args[0]376377 with app.test_request_context():378 assert flask.session.get('missing_key') is None379 expect_exception(flask.session.__setitem__, 'foo', 42)380 expect_exception(flask.session.pop, 'foo')381382322def test_session_expiration():383def test_session_expiration(app, client):384 permanent = True324 app = flask.Flask(__name__)385 app.secret_key = 'testkey'386387 @app.route('/')388 def index():
4 unmodified lines
393 @app.route('/test')394 def test():395 return text_type(flask.session.permanent)396337 client = app.test_client()397 rv = client.get('/')398 assert 'set-cookie' in rv.headers340 match = re.search(r'\bexpires=([^;]+)(?i)', rv.headers['set-cookie'])399 match = re.search(r'(?i)\bexpires=([^;]+)', rv.headers['set-cookie'])400 expires = parse_date(match.group())401 expected = datetime.utcnow() + app.permanent_session_lifetime402 assert expires.year == expected.year403 assert expires.month == expected.month
2 unmodified lines
406 rv = client.get('/test')407 assert rv.data == b'True'408409 permanent = False351 rv = app.test_client().get('/')410 rv = client.get('/')411 assert 'set-cookie' in rv.headers412 match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])413 assert match is None414415357def test_session_stored_last():358 app = flask.Flask(__name__)416def test_session_stored_last(app, client):417 app.secret_key = 'development-key'360 app.testing = True418419 @app.after_request420 def modify_session(response):421 flask.session['foo'] = 42
2 unmodified lines
424 @app.route('/')425 def dump_session_contents():426 return repr(flask.session.get('foo'))427371 c = app.test_client()372 assert c.get('/').data == b'None'373 assert c.get('/').data == b'42'428 assert client.get('/').data == b'None'429 assert client.get('/').data == b'42'430431376def test_session_special_types():377 app = flask.Flask(__name__)432def test_session_special_types(app, client):433 app.secret_key = 'development-key'379 app.testing = True434 now = datetime.utcnow().replace(microsecond=0)435 the_uuid = uuid.uuid4()436437 @app.after_request
8 unmodified lines
446 @app.route('/')447 def dump_session_contents():448 return pickle.dumps(dict(flask.session))449396 c = app.test_client()397 c.get('/')398 rv = pickle.loads(c.get('/').data)450 client.get('/')451 rv = pickle.loads(client.get('/').data)452 assert rv['m'] == flask.Markup('Hello!')453 assert type(rv['m']) == flask.Markup454 assert rv['dt'] == now455 assert rv['u'] == the_uuid
1 unmodified line
457 assert type(rv['b']) == bytes458 assert rv['t'] == (1, 2, 3)459460408def test_session_cookie_setting():409 app = flask.Flask(__name__)410 app.testing = True461def test_session_cookie_setting(app):462 app.secret_key = 'dev key'463 is_permanent = True464465 @app.route('/bump')
33 unmodified lines
499 app.config['SESSION_REFRESH_EACH_REQUEST'] = False500 run_test(expect_header=False)501502452def test_flashes():453 app = flask.Flask(__name__)503def test_session_vary_cookie(app, client):504 app.secret_key = 'testkey'505456 with app.test_request_context():457 assert not flask.session.modified458 flask.flash('Zap')459 flask.session.modified = False460 flask.flash('Zip')461 assert flask.session.modified462 assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']506 @app.route('/set')507 def set_session():508 flask.session['test'] = 'test'509 return ''510511 @app.route('/get')512 def get():513 return flask.session.get('test')514515 @app.route('/getitem')516 def getitem():517 return flask.session['test']518519 @app.route('/setdefault')520 def setdefault():521 return flask.session.setdefault('test', 'default')522523 @app.route('/vary-cookie-header-set')524 def vary_cookie_header_set():525 response = flask.Response()526 response.headers['Vary'] = 'Cookie'527 flask.session['test'] = 'test'528 return response529530 @app.route('/vary-header-set')531 def vary_header_set():532 response = flask.Response()533 response.headers['Vary'] = 'Accept-Encoding, Accept-Language'534 flask.session['test'] = 'test'535 return response536537 @app.route('/no-vary-header')538 def no_vary_header():539 return ''540541 def expect(path, header_value='Cookie'):542 rv = client.get(path)543544 if header_value:545 # The 'Vary' key should exist in the headers only once.546 assert len(rv.headers.get_all('Vary')) == 1547 assert rv.headers['Vary'] == header_value548 else:549 assert 'Vary' not in rv.headers550551 expect('/set')552 expect('/get')553 expect('/getitem')554 expect('/setdefault')555 expect('/vary-cookie-header-set')556 expect('/vary-header-set', 'Accept-Encoding, Accept-Language, Cookie')557 expect('/no-vary-header', None)558559560def test_flashes(app, req_ctx):561 app.secret_key = 'testkey'562563 assert not flask.session.modified564 flask.flash('Zap')565 flask.session.modified = False566 flask.flash('Zip')567 assert flask.session.modified568 assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']569570465def test_extended_flashing():571def test_extended_flashing(app):572 # Be sure app.testing=True below, else tests can fail silently.573 #574 # Specifically, if app.testing is not set to True, the AssertionErrors575 # in the view functions will cause a 500 response to the test client576 # instead of propagating exceptions.577472 app = flask.Flask(__name__)578 app.secret_key = 'testkey'474 app.testing = True579580 @app.route('/')581 def index():582 flask.flash(u'Hello World')
49 unmodified lines
632 return ''633634 # Create new test client on each test to clean flashed messages.635532 c = app.test_client()533 c.get('/')534 c.get('/test/')636 client = app.test_client()637 client.get('/')638 client.get('/test_with_categories/')639536 c = app.test_client()537 c.get('/')538 c.get('/test_with_categories/')640 client = app.test_client()641 client.get('/')642 client.get('/test_filter/')643540 c = app.test_client()541 c.get('/')542 c.get('/test_filter/')644 client = app.test_client()645 client.get('/')646 client.get('/test_filters/')647544 c = app.test_client()545 c.get('/')546 c.get('/test_filters/')648 client = app.test_client()649 client.get('/')650 client.get('/test_filters_without_returning_categories/')651548 c = app.test_client()549 c.get('/')550 c.get('/test_filters_without_returning_categories/')652552553def test_request_processing():653def test_request_processing(app, client):554 app = flask.Flask(__name__)654 evts = []655656 @app.before_request657 def before_request():
9 unmodified lines
667 def index():668 assert 'before' in evts669 assert 'after' not in evts670 return 'request'671672 assert 'after' not in evts573 rv = app.test_client().get('/').data673 rv = client.get('/').data674 assert 'after' in evts675 assert rv == b'request|after'676677578def test_request_preprocessing_early_return():579 app = flask.Flask(__name__)678def test_request_preprocessing_early_return(app, client):679 evts = []680681 @app.before_request682 def before_request1():
13 unmodified lines
696 def index():697 evts.append('index')698 return "damnit"699601 rv = app.test_client().get('/').data.strip()700 rv = client.get('/').data.strip()701 assert rv == b'hello'702 assert evts == [1, 2]703704606def test_after_request_processing():607 app = flask.Flask(__name__)608 app.testing = True609705def test_after_request_processing(app, client):706 @app.route('/')707 def index():708 @flask.after_this_request709 def foo(response):710 response.headers['X-Foo'] = 'a header'711 return response712713 return 'Test'617 c = app.test_client()618 resp = c.get('/')714715 resp = client.get('/')716 assert resp.status_code == 200717 assert resp.headers['X-Foo'] == 'a header'718719623def test_teardown_request_handler():720def test_teardown_request_handler(app, client):721 called = []625 app = flask.Flask(__name__)722723 @app.teardown_request724 def teardown_request(exc):725 called.append(True)
1 unmodified line
727728 @app.route('/')729 def root():730 return "Response"635 rv = app.test_client().get('/')731732 rv = client.get('/')733 assert rv.status_code == 200734 assert b'Response' in rv.data735 assert len(called) == 1736737641def test_teardown_request_handler_debug_mode():738def test_teardown_request_handler_debug_mode(app, client):739 called = []643 app = flask.Flask(__name__)644 app.testing = True740741 @app.teardown_request742 def teardown_request(exc):743 called.append(True)
1 unmodified line
745746 @app.route('/')747 def root():748 return "Response"654 rv = app.test_client().get('/')749750 rv = client.get('/')751 assert rv.status_code == 200752 assert b'Response' in rv.data753 assert len(called) == 1754755660def test_teardown_request_handler_error():756def test_teardown_request_handler_error(app, client):757 called = []662 app = flask.Flask(__name__)758 app.config['LOGGER_HANDLER_POLICY'] = 'never'759 app.testing = False760761 @app.teardown_request762 def teardown_request1(exc):763 assert type(exc) == ZeroDivisionError
20 unmodified lines
784785 @app.route('/')786 def fails():787 1 // 0692 rv = app.test_client().get('/')788789 rv = client.get('/')790 assert rv.status_code == 500791 assert b'Internal Server Error' in rv.data792 assert len(called) == 2793794698def test_before_after_request_order():795def test_before_after_request_order(app, client):796 called = []700 app = flask.Flask(__name__)797798 @app.before_request799 def before1():800 called.append(1)
22 unmodified lines
823824 @app.route('/')825 def index():826 return '42'731 rv = app.test_client().get('/')827828 rv = client.get('/')829 assert rv.data == b'42'830 assert called == [1, 2, 3, 4, 5, 6]831832736def test_error_handling():737 app = flask.Flask(__name__)833def test_error_handling(app, client):834 app.config['LOGGER_HANDLER_POLICY'] = 'never'835 app.testing = False836837 @app.errorhandler(404)838 def not_found(e):839 return 'not found', 404
16 unmodified lines
856857 @app.route('/forbidden')858 def error2():859 flask.abort(403)763 c = app.test_client()764 rv = c.get('/')860861 rv = client.get('/')862 assert rv.status_code == 404863 assert rv.data == b'not found'767 rv = c.get('/error')864 rv = client.get('/error')865 assert rv.status_code == 500866 assert b'internal server error' == rv.data770 rv = c.get('/forbidden')867 rv = client.get('/forbidden')868 assert rv.status_code == 403869 assert b'forbidden' == rv.data870871775def test_before_request_and_routing_errors():776 app = flask.Flask(__name__)872def test_error_handling_processing(app, client):873 app.config['LOGGER_HANDLER_POLICY'] = 'never'874 app.testing = False875876 @app.errorhandler(500)877 def internal_server_error(e):878 return 'internal server error', 500879880 @app.route('/')881 def broken_func():882 1 // 0883884 @app.after_request885 def after_request(resp):886 resp.mimetype = 'text/x-special'887 return resp888889 resp = client.get('/')890 assert resp.mimetype == 'text/x-special'891 assert resp.data == b'internal server error'892893894def test_baseexception_error_handling(app, client):895 app.config['LOGGER_HANDLER_POLICY'] = 'never'896 app.testing = False897898 @app.route('/')899 def broken_func():900 raise KeyboardInterrupt()901902 with pytest.raises(KeyboardInterrupt):903 client.get('/')904905 ctx = flask._request_ctx_stack.top906 assert ctx.preserved907 assert type(ctx._preserved_exc) is KeyboardInterrupt908909910def test_before_request_and_routing_errors(app, client):911 @app.before_request912 def attach_something():913 flask.g.something = 'value'914915 @app.errorhandler(404)916 def return_something(error):917 return flask.g.something, 404785 rv = app.test_client().get('/')918919 rv = client.get('/')920 assert rv.status_code == 404921 assert rv.data == b'value'922923790def test_user_error_handling():924def test_user_error_handling(app, client):925 class MyException(Exception):926 pass927794 app = flask.Flask(__name__)795928 @app.errorhandler(MyException)929 def handle_my_exception(e):930 assert isinstance(e, MyException)931 return '42'
1 unmodified line
933 @app.route('/')934 def index():935 raise MyException()936805 c = app.test_client()806 assert c.get('/').data == b'42'937 assert client.get('/').data == b'42'938939809def test_http_error_subclass_handling():940def test_http_error_subclass_handling(app, client):941 class ForbiddenSubclass(Forbidden):942 pass943813 app = flask.Flask(__name__)814944 @app.errorhandler(ForbiddenSubclass)945 def handle_forbidden_subclass(e):946 assert isinstance(e, ForbiddenSubclass)947 return 'banana'
15 unmodified lines
963 @app.route('/3')964 def index3():965 raise Forbidden()966838 c = app.test_client()839 assert c.get('/1').data == b'banana'840 assert c.get('/2').data == b'apple'841 assert c.get('/3').data == b'apple'967 assert client.get('/1').data == b'banana'968 assert client.get('/2').data == b'apple'969 assert client.get('/3').data == b'apple'970971844def test_trapping_of_bad_request_key_errors():845 app = flask.Flask(__name__)846 app.testing = True847972def test_trapping_of_bad_request_key_errors(app, client):973 @app.route('/fail')974 def fail():975 flask.request.form['missing_key']851 c = app.test_client()852 assert c.get('/fail').status_code == 400976977 assert client.get('/fail').status_code == 400978979 app.config['TRAP_BAD_REQUEST_ERRORS'] = True855 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'980 with pytest.raises(KeyError) as e:981 client.get("/fail")982 assert e.errisinstance(BadRequest)983984864def test_trapping_of_all_http_exceptions():865 app = flask.Flask(__name__)866 app.testing = True985def test_trapping_of_all_http_exceptions(app, client):986 app.config['TRAP_HTTP_EXCEPTIONS'] = True987988 @app.route('/fail')989 def fail():990 flask.abort(404)991873 c = app.test_client()992 with pytest.raises(NotFound):875 c.get('/fail')993 client.get('/fail')994995878def test_enctype_debug_helper():996def test_enctype_debug_helper(app, client):997 from flask.debughelpers import DebugFilesKeyError880 app = flask.Flask(__name__)998 app.debug = True9991000 @app.route('/fail', methods=['POST'])1001 def index():
1 unmodified line
10031004 # with statement is important because we leave an exception on the1005 # stack otherwise and we want to ensure that this is not the case1006 # to not negatively affect other tests.890 with app.test_client() as c:891 try:892 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)896 else:897 assert False, 'Expected exception'1007 with client:1008 with pytest.raises(DebugFilesKeyError) as e:1009 client.post('/fail', data={'foo': 'index.txt'})1010 assert 'no file contents were transmitted' in str(e.value)1011 assert 'This was submitted: "index.txt"' in str(e.value)10121013900def test_response_creation():901 app = flask.Flask(__name__)902903 @app.route('/unicode')904 def from_unicode():1014def test_response_types(app, client):1015 @app.route('/text')1016 def from_text():1017 return u'Hällo Wörld'1018907 @app.route('/string')908 def from_string():1019 @app.route('/bytes')1020 def from_bytes():1021 return u'Hällo Wörld'.encode('utf-8')1022911 @app.route('/args')912 def from_tuple():1023 @app.route('/full_tuple')1024 def from_full_tuple():1025 return 'Meh', 400, {1026 'X-Foo': 'Testing',1027 'Content-Type': 'text/plain; charset=utf-8'1028 }1029918 @app.route('/two_args')919 def from_two_args_tuple():1030 @app.route('/text_headers')1031 def from_text_headers():1032 return 'Hello', {1033 'X-Foo': 'Test',1034 'Content-Type': 'text/plain; charset=utf-8'1035 }1036925 @app.route('/args_status')926 def from_status_tuple():1037 @app.route('/text_status')1038 def from_text_status():1039 return 'Hi, status!', 4001040929 @app.route('/args_header')930 def from_response_instance_status_tuple():931 return flask.Response('Hello world', 404), {1041 @app.route('/response_headers')1042 def from_response_headers():1043 return flask.Response('Hello world', 404, {'X-Foo': 'Baz'}), {1044 "X-Foo": "Bar",1045 "X-Bar": "Foo"1046 }1047936 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')1048 @app.route('/response_status')1049 def from_response_status():1050 return app.response_class('Hello world', 400), 50010511052 @app.route('/wsgi')1053 def from_wsgi():1054 return NotFound()10551056 assert client.get('/text').data == u'Hällo Wörld'.encode('utf-8')1057 assert client.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')10581059 rv = client.get('/full_tuple')1060 assert rv.data == b'Meh'1061 assert rv.headers['X-Foo'] == 'Testing'1062 assert rv.status_code == 4001063 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 == 40410641065 rv = client.get('/text_headers')1066 assert rv.data == b'Hello'1067 assert rv.headers['X-Foo'] == 'Test'1068 assert rv.status_code == 2001069 assert rv.mimetype == 'text/plain'1070960def test_make_response():961 app = flask.Flask(__name__)962 with app.test_request_context():963 rv = flask.make_response()964 assert rv.status_code == 200965 assert rv.data == b''966 assert rv.mimetype == 'text/html'1071 rv = client.get('/text_status')1072 assert rv.data == b'Hi, status!'1073 assert rv.status_code == 4001074 assert rv.mimetype == 'text/html'1075968 rv = flask.make_response('Awesome')969 assert rv.status_code == 200970 assert rv.data == b'Awesome'971 assert rv.mimetype == 'text/html'1076 rv = client.get('/response_headers')1077 assert rv.data == b'Hello world'1078 assert rv.headers.getlist('X-Foo') == ['Baz', 'Bar']1079 assert rv.headers['X-Bar'] == 'Foo'1080 assert rv.status_code == 4041081973 rv = flask.make_response('W00t', 404)974 assert rv.status_code == 404975 assert rv.data == b'W00t'976 assert rv.mimetype == 'text/html'1082 rv = client.get('/response_status')1083 assert rv.data == b'Hello world'1084 assert rv.status_code == 50010851086 rv = client.get('/wsgi')1087 assert b'Not Found' in rv.data1088 assert rv.status_code == 4041089979def test_make_response_with_response_instance():10901091def test_response_type_errors():1092 app = flask.Flask(__name__)981 with app.test_request_context():982 rv = flask.make_response(983 flask.jsonify({'msg': 'W00t'}), 400)984 assert rv.status_code == 400985 assert rv.data == b'{\n "msg": "W00t"\n}\n'986 assert rv.mimetype == 'application/json'1093 app.testing = True1094988 rv = flask.make_response(989 flask.Response(''), 400)990 assert rv.status_code == 400991 assert rv.data == b''992 assert rv.mimetype == 'text/html'1095 @app.route('/none')1096 def from_none():1097 pass1098994 rv = flask.make_response(995 flask.Response('', headers={'Content-Type': 'text/html'}),996 400, [('X-Foo', 'bar')])997 assert rv.status_code == 400998 assert rv.headers['Content-Type'] == 'text/html'999 assert rv.headers['X-Foo'] == 'bar'1099 @app.route('/small_tuple')1100 def from_small_tuple():1101 return 'Hello',11021103 @app.route('/large_tuple')1104 def from_large_tuple():1105 return 'Hello', 234, {'X-Foo': 'Bar'}, '???'11061002def test_jsonify_no_prettyprint():1003 app = flask.Flask(__name__)1107 @app.route('/bad_type')1108 def from_bad_type():1109 return True11101111 @app.route('/bad_wsgi')1112 def from_bad_wsgi():1113 return lambda: None11141115 c = app.test_client()11161117 with pytest.raises(TypeError) as e:1118 c.get('/none')1119 assert 'returned None' in str(e)11201121 with pytest.raises(TypeError) as e:1122 c.get('/small_tuple')1123 assert 'tuple must have the form' in str(e)11241125 pytest.raises(TypeError, c.get, '/large_tuple')11261127 with pytest.raises(TypeError) as e:1128 c.get('/bad_type')1129 assert 'it was a bool' in str(e)11301131 pytest.raises(TypeError, c.get, '/bad_wsgi')113211331134def test_make_response(app, req_ctx):1135 rv = flask.make_response()1136 assert rv.status_code == 2001137 assert rv.data == b''1138 assert rv.mimetype == 'text/html'11391140 rv = flask.make_response('Awesome')1141 assert rv.status_code == 2001142 assert rv.data == b'Awesome'1143 assert rv.mimetype == 'text/html'11441145 rv = flask.make_response('W00t', 404)1146 assert rv.status_code == 4041147 assert rv.data == b'W00t'1148 assert rv.mimetype == 'text/html'114911501151def test_make_response_with_response_instance(app, req_ctx):1152 rv = flask.make_response(1153 flask.jsonify({'msg': 'W00t'}), 400)1154 assert rv.status_code == 4001155 assert rv.data == b'{"msg":"W00t"}\n'1156 assert rv.mimetype == 'application/json'11571158 rv = flask.make_response(1159 flask.Response(''), 400)1160 assert rv.status_code == 4001161 assert rv.data == b''1162 assert rv.mimetype == 'text/html'11631164 rv = flask.make_response(1165 flask.Response('', headers={'Content-Type': 'text/html'}),1166 400, [('X-Foo', 'bar')])1167 assert rv.status_code == 4001168 assert rv.headers['Content-Type'] == 'text/html'1169 assert rv.headers['X-Foo'] == 'bar'117011711172def test_jsonify_no_prettyprint(app, req_ctx):1173 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1005 with app.test_request_context():1006 compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1007 uncompressed_msg = {1008 "msg": {1009 "submsg": "W00t"1010 },1011 "msg2": "foobar"1012 }1174 compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1175 uncompressed_msg = {1176 "msg": {1177 "submsg": "W00t"1178 },1179 "msg2": "foobar"1180 }11811014 rv = flask.make_response(1015 flask.jsonify(uncompressed_msg), 200)1016 assert rv.data == compressed_msg1182 rv = flask.make_response(1183 flask.jsonify(uncompressed_msg), 200)1184 assert rv.data == compressed_msg118511861019def test_jsonify_prettyprint():1020 app = flask.Flask(__name__)1187def test_jsonify_prettyprint(app, req_ctx):1188 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1022 with app.test_request_context():1023 compressed_msg = {"msg":{"submsg":"W00t"},"msg2":"foobar"}1024 pretty_response =\1025 b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'1189 compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1190 pretty_response = \1191 b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'11921027 rv = flask.make_response(1028 flask.jsonify(compressed_msg), 200)1029 assert rv.data == pretty_response1193 rv = flask.make_response(1194 flask.jsonify(compressed_msg), 200)1195 assert rv.data == pretty_response119611971032def test_url_generation():1033 app = flask.Flask(__name__)1198def test_jsonify_mimetype(app, req_ctx):1199 app.config.update({"JSONIFY_MIMETYPE": 'application/vnd.api+json'})1200 msg = {1201 "msg": {"submsg": "W00t"},1202 }1203 rv = flask.make_response(1204 flask.jsonify(msg), 200)1205 assert rv.mimetype == 'application/vnd.api+json'120612071208def test_jsonify_args_and_kwargs_check(app, req_ctx):1209 with pytest.raises(TypeError) as e:1210 flask.jsonify('fake args', kwargs='fake')1211 assert 'behavior undefined' in str(e.value)121212131214def test_url_generation(app, req_ctx):1215 @app.route('/hello/<name>', methods=['POST'])1216 def hello():1217 pass1038 with app.test_request_context():1039 assert flask.url_for('hello', name='test x') == '/hello/test%20x'1040 assert flask.url_for('hello', name='test x', _external=True) == \1041 'http://localhost/hello/test%20x'12181219 assert flask.url_for('hello', name='test x') == '/hello/test%20x'1220 assert flask.url_for('hello', name='test x', _external=True) == \1221 'http://localhost/hello/test%20x'12221044def test_build_error_handler():1045 app = flask.Flask(__name__)12231224def test_build_error_handler(app):1225 # Test base case, a URL which results in a BuildError.1226 with app.test_request_context():1227 pytest.raises(BuildError, flask.url_for, 'spam')1228
12 unmodified lines
1241 # Test a custom handler.1242 def handler(error, endpoint, values):1243 # Just a test.1244 return '/test_handler/'12451246 app.url_build_error_handlers.append(handler)1247 with app.test_request_context():1248 assert flask.url_for('spam') == '/test_handler/'124912501072def test_custom_converters():1251def test_build_error_handler_reraise(app):1252 # Test a custom handler which reraises the BuildError1253 def handler_raises_build_error(error, endpoint, values):1254 raise error12551256 app.url_build_error_handlers.append(handler_raises_build_error)12571258 with app.test_request_context():1259 pytest.raises(BuildError, flask.url_for, 'not.existing')126012611262def test_url_for_passes_special_values_to_build_error_handler(app):1263 @app.url_build_error_handlers.append1264 def handler(error, endpoint, values):1265 assert values == {1266 '_external': False,1267 '_anchor': None,1268 '_method': None,1269 '_scheme': None,1270 }1271 return 'handled'12721273 with app.test_request_context():1274 flask.url_for('/')127512761277def test_custom_converters(app, client):1278 from werkzeug.routing import BaseConverter12791280 class ListConverter(BaseConverter):10761281 def to_python(self, value):1282 return value.split(',')12831284 def to_url(self, value):1285 base_to_url = super(ListConverter, self).to_url1286 return ','.join(base_to_url(x) for x in value)1083 app = flask.Flask(__name__)12871288 app.url_map.converters['list'] = ListConverter12891290 @app.route('/<list:args>')1291 def index(args):1292 return '|'.join(args)1089 c = app.test_client()1090 assert c.get('/1,2,3').data == b'1|2|3'12931294 assert client.get('/1,2,3').data == b'1|2|3'12951093def test_static_files():1094 app = flask.Flask(__name__)1095 app.testing = True1096 rv = app.test_client().get('/static/index.html')12961297def test_static_files(app, client):1298 rv = client.get('/static/index.html')1299 assert rv.status_code == 2001300 assert rv.data.strip() == b'<h1>Hello World!</h1>'1301 with app.test_request_context():1302 assert flask.url_for('static', filename='index.html') == \1101 '/static/index.html'1303 '/static/index.html'1304 rv.close()130513061105def test_none_response():1106 app = flask.Flask(__name__)1307def test_static_path_deprecated(recwarn):1308 app = flask.Flask(__name__, static_path='/foo')1309 recwarn.pop(DeprecationWarning)13101311 app.testing = True1312 rv = app.test_client().get('/foo/index.html')1313 assert rv.status_code == 2001314 rv.close()13151109 @app.route('/')1110 def test():1111 return None1112 try:1113 app.test_client().get('/')1114 except ValueError as e:1115 assert str(e) == 'View function did not return a response'1116 pass1117 else:1118 assert "Expected ValueError"1316 with app.test_request_context():1317 assert flask.url_for('static', filename='index.html') == '/foo/index.html'131813191320def test_static_url_path():1321 app = flask.Flask(__name__, static_url_path='/foo')1322 app.testing = True1323 rv = app.test_client().get('/foo/index.html')1324 assert rv.status_code == 2001325 rv.close()13261327 with app.test_request_context():1328 assert flask.url_for('static', filename='index.html') == '/foo/index.html'132913301331def test_static_route_with_host_matching():1332 app = flask.Flask(__name__, host_matching=True, static_host='example.com')1333 c = app.test_client()1334 rv = c.get('http://example.com/static/index.html')1335 assert rv.status_code == 2001336 rv.close()1337 with app.test_request_context():1338 rv = flask.url_for('static', filename='index.html', _external=True)1339 assert rv == 'http://example.com/static/index.html'1340 # Providing static_host without host_matching=True should error.1341 with pytest.raises(Exception):1342 flask.Flask(__name__, static_host='example.com')1343 # Providing host_matching=True with static_folder but without static_host should error.1344 with pytest.raises(Exception):1345 flask.Flask(__name__, host_matching=True)1346 # Providing host_matching=True without static_host but with static_folder=None should not error.1347 flask.Flask(__name__, host_matching=True, static_folder=None)134813491350def test_request_locals():1351 assert repr(flask.g) == '<LocalProxy unbound>'1352 assert not flask.g135313541126def test_test_app_proper_environ():1127 app = flask.Flask(__name__)1355def test_test_app_proper_environ(app, client):1356 app.config.update(1357 SERVER_NAME='localhost.localdomain:5000'1358 )1359
4 unmodified lines
1364 @app.route('/', subdomain='foo')1365 def subdomain():1366 return 'Foo SubDomain'13671140 rv = app.test_client().get('/')1368 rv = client.get('/')1369 assert rv.data == b'Foo'13701143 rv = app.test_client().get('/', 'http://localhost.localdomain:5000')1371 rv = client.get('/', 'http://localhost.localdomain:5000')1372 assert rv.data == b'Foo'13731146 rv = app.test_client().get('/', 'https://localhost.localdomain:5000')1374 rv = client.get('/', 'https://localhost.localdomain:5000')1375 assert rv.data == b'Foo'13761377 app.config.update(SERVER_NAME='localhost.localdomain')1150 rv = app.test_client().get('/', 'https://localhost.localdomain')1378 rv = client.get('/', 'https://localhost.localdomain')1379 assert rv.data == b'Foo'13801381 try:1382 app.config.update(SERVER_NAME='localhost.localdomain:443')1155 rv = app.test_client().get('/', 'https://localhost.localdomain')1383 rv = client.get('/', 'https://localhost.localdomain')1384 # Werkzeug 0.81385 assert rv.status_code == 4041386 except ValueError as e:1387 # Werkzeug 0.7
4 unmodified lines
1392 )13931394 try:1395 app.config.update(SERVER_NAME='localhost.localdomain')1168 rv = app.test_client().get('/', 'http://foo.localhost')1396 rv = client.get('/', 'http://foo.localhost')1397 # Werkzeug 0.81398 assert rv.status_code == 4041399 except ValueError as e:1400 # Werkzeug 0.7
2 unmodified lines
1403 "('localhost.localdomain') does not match the "1404 "server name from the WSGI environment ('foo.localhost')"1405 )14061179 rv = app.test_client().get('/', 'http://foo.localhost.localdomain')1407 rv = client.get('/', 'http://foo.localhost.localdomain')1408 assert rv.data == b'Foo SubDomain'140914101183def test_exception_propagation():1411def test_exception_propagation(app, client):1412 def apprunner(config_key):1185 app = flask.Flask(__name__)1413 app.config['LOGGER_HANDLER_POLICY'] = 'never'14141415 @app.route('/')1416 def index():1417 1 // 01191 c = app.test_client()14181419 if config_key is not None:1420 app.config[config_key] = True1194 try:1195 c.get('/')1196 except Exception:1197 pass1198 else:1199 assert False, 'expected exception'1421 with pytest.raises(Exception):1422 client.get('/')1423 else:1201 assert c.get('/').status_code == 5001424 assert client.get('/').status_code == 50014251426 # we have to run this test in an isolated thread because if the1427 # debug flag is set to true and an exception happens the context is1428 # not torn down. This causes other tests that run after this fail
3 unmodified lines
1432 t.start()1433 t.join()143414351213def test_max_content_length():1214 app = flask.Flask(__name__)1436@pytest.mark.parametrize('debug', [True, False])1437@pytest.mark.parametrize('use_debugger', [True, False])1438@pytest.mark.parametrize('use_reloader', [True, False])1439@pytest.mark.parametrize('propagate_exceptions', [None, True, False])1440def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1441 use_reloader, propagate_exceptions, app):1442 rv = {}14431444 # Mocks werkzeug.serving.run_simple method1445 def run_simple_mock(*args, **kwargs):1446 rv['passthrough_errors'] = kwargs.get('passthrough_errors')14471448 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1449 app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1450 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)145114521453def test_max_content_length(app, client):1454 app.config['MAX_CONTENT_LENGTH'] = 6414551456 @app.before_request1457 def always_first():
8 unmodified lines
1466 @app.errorhandler(413)1467 def catcher(error):1468 return '42'14691231 c = app.test_client()1232 rv = c.post('/accept', data={'myfile': 'foo' * 100})1470 rv = client.post('/accept', data={'myfile': 'foo' * 100})1471 assert rv.data == b'42'147214731236def test_url_processors():1237 app = flask.Flask(__name__)1474def test_url_processors(app, client):14751476 @app.url_defaults1477 def add_language_code(endpoint, values):1478 if flask.g.lang_code is not None and \1242 app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1479 app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1480 values.setdefault('lang_code', flask.g.lang_code)14811482 @app.url_value_preprocessor1483 def pull_lang_code(endpoint, values):
10 unmodified lines
1494 @app.route('/foo')1495 def something_else():1496 return flask.url_for('about', lang_code='en')14971261 c = app.test_client()1498 assert client.get('/de/').data == b'/de/about'1499 assert client.get('/de/about').data == b'/foo'1500 assert client.get('/foo').data == b'/en/about'15011263 assert c.get('/de/').data == b'/de/about'1264 assert c.get('/de/about').data == b'/foo'1265 assert c.get('/foo').data == b'/en/about'150212671268def test_inject_blueprint_url_defaults():1503def test_inject_blueprint_url_defaults(app):1269 app = flask.Flask(__name__)1504 bp = flask.Blueprint('foo.bar.baz', __name__,1505 template_folder='template')15061507 @bp.url_defaults
16 unmodified lines
1524 expected = '/login'1525 assert url == expected152615271294def test_nonascii_pathinfo():1295 app = flask.Flask(__name__)1296 app.testing = True12971528def test_nonascii_pathinfo(app, client):1529 @app.route(u'/киртест')1530 def index():1531 return 'Hello World!'15321302 c = app.test_client()1303 rv = c.get(u'/киртест')1533 rv = client.get(u'/киртест')1534 assert rv.data == b'Hello World!'153515361307def test_debug_mode_complains_after_first_request():1308 app = flask.Flask(__name__)1537def test_debug_mode_complains_after_first_request(app, client):1538 app.debug = True15391540 @app.route('/')1541 def index():1542 return 'Awesome'15431544 assert not app.got_first_request1315 assert app.test_client().get('/').data == b'Awesome'1316 try:1545 assert client.get('/').data == b'Awesome'1546 with pytest.raises(AssertionError) as e:1547 @app.route('/foo')1548 def broken():1549 return 'Meh'1320 except AssertionError as e:1321 assert 'A setup function was called' in str(e)1550 assert 'A setup function was called' in str(e)1322 else:1323 assert False, 'Expected exception'15511552 app.debug = False15531554 @app.route('/foo')1555 def working():1556 return 'Meh'15571330 assert app.test_client().get('/foo').data == b'Meh'1558 assert client.get('/foo').data == b'Meh'1559 assert app.got_first_request156015611334def test_before_first_request_functions():1562def test_before_first_request_functions(app, client):1563 got = []1336 app = flask.Flask(__name__)15641565 @app.before_first_request1566 def foo():1567 got.append(42)1341 c = app.test_client()1342 c.get('/')15681569 client.get('/')1570 assert got == [42]1344 c.get('/')1571 client.get('/')1572 assert got == [42]1573 assert app.got_first_request157415751349def test_before_first_request_functions_concurrent():1576def test_before_first_request_functions_concurrent(app, client):1577 got = []1351 app = flask.Flask(__name__)15781579 @app.before_first_request1580 def foo():1581 time.sleep(0.2)1582 got.append(42)15831358 c = app.test_client()13591584 def get_and_assert():1361 c.get("/")1585 client.get("/")1586 assert got == [42]15871588 t = Thread(target=get_and_assert)1589 t.start()
1 unmodified line
1591 t.join()1592 assert app.got_first_request159315941371def test_routing_redirect_debugging():1372 app = flask.Flask(__name__)1595def test_routing_redirect_debugging(app, client):1596 app.debug = True15971598 @app.route('/foo/', methods=['GET', 'POST'])1599 def foo():1600 return 'success'1378 with app.test_client() as c:1379 try:1380 c.post('/foo', data={})1381 except AssertionError as e:1382 assert 'http://localhost/foo/' in str(e)1383 assert ('Make sure to directly send '1384 'your POST-request to this URL') in str(e)1385 else:1386 assert False, 'Expected exception'16011602 with client:1603 with pytest.raises(AssertionError) as e:1604 client.post('/foo', data={})1605 assert 'http://localhost/foo/' in str(e)1606 assert ('Make sure to directly send '1607 'your POST-request to this URL') in str(e)16081388 rv = c.get('/foo', data={}, follow_redirects=True)1609 rv = client.get('/foo', data={}, follow_redirects=True)1610 assert rv.data == b'success'16111612 app.debug = False1392 with app.test_client() as c:1393 rv = c.post('/foo', data={}, follow_redirects=True)1613 with client:1614 rv = client.post('/foo', data={}, follow_redirects=True)1615 assert rv.data == b'success'161616171397def test_route_decorator_custom_endpoint():1398 app = flask.Flask(__name__)1618def test_route_decorator_custom_endpoint(app, client):1619 app.debug = True16201621 @app.route('/foo/')1622 def foo():
11 unmodified lines
1634 assert flask.url_for('foo') == '/foo/'1635 assert flask.url_for('bar') == '/bar/'1636 assert flask.url_for('123') == '/bar/123'16371418 c = app.test_client()1419 assert c.get('/foo/').data == b'foo'1420 assert c.get('/bar/').data == b'bar'1421 assert c.get('/bar/123').data == b'123'1638 assert client.get('/foo/').data == b'foo'1639 assert client.get('/bar/').data == b'bar'1640 assert client.get('/bar/123').data == b'123'164116421424def test_preserve_only_once():1425 app = flask.Flask(__name__)1643def test_preserve_only_once(app, client):1644 app.debug = True16451646 @app.route('/fail')1647 def fail_func():1648 1 // 016491432 c = app.test_client()1650 for x in range(3):1651 with pytest.raises(ZeroDivisionError):1435 c.get('/fail')1652 client.get('/fail')16531654 assert flask._request_ctx_stack.top is not None1655 assert flask._app_ctx_stack.top is not None1656 # implicit appctx disappears too
1 unmodified line
1658 assert flask._request_ctx_stack.top is None1659 assert flask._app_ctx_stack.top is None166016611445def test_preserve_remembers_exception():1446 app = flask.Flask(__name__)1662def test_preserve_remembers_exception(app, client):1663 app.debug = True1664 errors = []16651666 @app.route('/fail')
7 unmodified lines
1674 @app.teardown_request1675 def teardown_handler(exc):1676 errors.append(exc)16771462 c = app.test_client()14631678 # After this failure we did not yet call the teardown handler1679 with pytest.raises(ZeroDivisionError):1466 c.get('/fail')1680 client.get('/fail')1681 assert errors == []16821683 # But this request triggers it, and it's an error1470 c.get('/success')1684 client.get('/success')1685 assert len(errors) == 21686 assert isinstance(errors[0], ZeroDivisionError)16871688 # At this point another request does nothing.1475 c.get('/success')1689 client.get('/success')1690 assert len(errors) == 31691 assert errors[1] is None169216931480def test_get_method_on_g():1481 app = flask.Flask(__name__)1482 app.testing = True1694def test_get_method_on_g(app_ctx):1695 assert flask.g.get('x') is None1696 assert flask.g.get('x', 11) == 111697 flask.g.x = 421698 assert flask.g.get('x') == 421699 assert flask.g.x == 4217001484 with app.app_context():1485 assert flask.g.get('x') is None1486 assert flask.g.get('x', 11) == 111487 flask.g.x = 421488 assert flask.g.get('x') == 421489 assert flask.g.x == 4217011702def test_g_iteration_protocol(app_ctx):1703 flask.g.foo = 231704 flask.g.bar = 421705 assert 'foo' in flask.g1706 assert 'foos' not in flask.g1707 assert sorted(flask.g) == ['bar', 'foo']17081492def test_g_iteration_protocol():1493 app = flask.Flask(__name__)1494 app.testing = True17091496 with app.app_context():1497 flask.g.foo = 231498 flask.g.bar = 421499 assert 'foo' in flask.g1500 assert 'foos' not in flask.g1501 assert sorted(flask.g) == ['bar', 'foo']1710def test_subdomain_basic_support(app, client):1711 app.config['SERVER_NAME'] = 'localhost.localdomain'171215031504def test_subdomain_basic_support():1505 app = flask.Flask(__name__)1506 app.config['SERVER_NAME'] = 'localhost'15071713 @app.route('/')1714 def normal_index():1715 return 'normal index'17161717 @app.route('/', subdomain='test')1718 def test_index():1719 return 'test index'17201516 c = app.test_client()1517 rv = c.get('/', 'http://localhost/')1721 rv = client.get('/', 'http://localhost.localdomain/')1722 assert rv.data == b'normal index'17231520 rv = c.get('/', 'http://test.localhost/')1724 rv = client.get('/', 'http://test.localhost.localdomain/')1725 assert rv.data == b'test index'172617271524def test_subdomain_matching():1525 app = flask.Flask(__name__)1526 app.config['SERVER_NAME'] = 'localhost'1728def test_subdomain_matching(app, client):1729 app.config['SERVER_NAME'] = 'localhost.localdomain'17301731 @app.route('/', subdomain='<user>')1732 def index(user):1733 return 'index for %s' % user17341532 c = app.test_client()1533 rv = c.get('/', 'http://mitsuhiko.localhost/')1735 rv = client.get('/', 'http://mitsuhiko.localhost.localdomain/')1736 assert rv.data == b'index for mitsuhiko'173717381537def test_subdomain_matching_with_ports():1538 app = flask.Flask(__name__)1539 app.config['SERVER_NAME'] = 'localhost:3000'1739def test_subdomain_matching_with_ports(app, client):1740 app.config['SERVER_NAME'] = 'localhost.localdomain:3000'17411742 @app.route('/', subdomain='<user>')1743 def index(user):1744 return 'index for %s' % user17451545 c = app.test_client()1546 rv = c.get('/', 'http://mitsuhiko.localhost:3000/')1746 rv = client.get('/', 'http://mitsuhiko.localhost.localdomain:3000/')1747 assert rv.data == b'index for mitsuhiko'174817491550def test_multi_route_rules():1551 app = flask.Flask(__name__)15521750def test_multi_route_rules(app, client):1751 @app.route('/')1752 @app.route('/<test>/')1753 def index(test='a'):1754 return test17551558 rv = app.test_client().open('/')1756 rv = client.open('/')1757 assert rv.data == b'a'1560 rv = app.test_client().open('/b/')1758 rv = client.open('/b/')1759 assert rv.data == b'b'176017611564def test_multi_route_class_views():1762def test_multi_route_class_views(app, client):1763 class View(object):15661764 def __init__(self, app):1765 app.add_url_rule('/', 'index', self.index)1766 app.add_url_rule('/<test>/', 'index', self.index)17671768 def index(self, test='a'):1769 return test17701574 app = flask.Flask(__name__)1771 _ = View(app)1576 rv = app.test_client().open('/')1772 rv = client.open('/')1773 assert rv.data == b'a'1578 rv = app.test_client().open('/b/')1774 rv = client.open('/b/')1775 assert rv.data == b'b'177617771582def test_run_defaults(monkeypatch):1778def test_run_defaults(monkeypatch, app):1779 rv = {}17801781 # Mocks werkzeug.serving.run_simple method1782 def run_simple_mock(*args, **kwargs):1783 rv['result'] = 'running...'17841589 app = flask.Flask(__name__)1785 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1786 app.run()1787 assert rv['result'] == 'running...'178817891595def test_run_server_port(monkeypatch):1790def test_run_server_port(monkeypatch, app):1791 rv = {}17921793 # Mocks werkzeug.serving.run_simple method1794 def run_simple_mock(hostname, port, application, *args, **kwargs):1795 rv['result'] = 'running on %s:%s ...' % (hostname, port)17961602 app = flask.Flask(__name__)1797 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1798 hostname, port = 'localhost', 80001799 app.run(hostname, port, debug=True)1800 assert rv['result'] == 'running on %s:%s ...' % (hostname, port)180118021803@pytest.mark.parametrize('host,port,expect_host,expect_port', (1804 (None, None, 'pocoo.org', 8080),1805 ('localhost', None, 'localhost', 8080),1806 (None, 80, 'pocoo.org', 80),1807 ('localhost', 80, 'localhost', 80),1808))1809def test_run_from_config(monkeypatch, host, port, expect_host, expect_port, app):1810 def run_simple_mock(hostname, port, *args, **kwargs):1811 assert hostname == expect_host1812 assert port == expect_port18131814 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1815 app.config['SERVER_NAME'] = 'pocoo.org:8080'1816 app.run(host, port)
modified:tests/test_blueprints.py+357 added-114 removed
16 unmodified lines
17from werkzeug.http import parse_cache_control_header18from jinja2 import TemplateNotFound192021def test_blueprint_specific_error_handling():21def test_blueprint_specific_error_handling(app, client):22 frontend = flask.Blueprint('frontend', __name__)23 backend = flask.Blueprint('backend', __name__)24 sideend = flask.Blueprint('sideend', __name__)25
16 unmodified lines
42 @sideend.route('/what-is-a-sideend')43 def sideend_no():44 flask.abort(403)4546 app = flask.Flask(__name__)46 app.register_blueprint(frontend)47 app.register_blueprint(backend)48 app.register_blueprint(sideend)4950 @app.errorhandler(403)51 def app_forbidden(e):52 return 'application itself says no', 4035355 c = app.test_client()54 assert client.get('/frontend-no').data == b'frontend says no'55 assert client.get('/backend-no').data == b'backend says no'56 assert client.get('/what-is-a-sideend').data == b'application itself says no'5757 assert c.get('/frontend-no').data == b'frontend says no'58 assert c.get('/backend-no').data == b'backend says no'59 assert c.get('/what-is-a-sideend').data == b'application itself says no'5861def test_blueprint_specific_user_error_handling():59def test_blueprint_specific_user_error_handling(app, client):60 class MyDecoratorException(Exception):61 pass6263 class MyFunctionException(Exception):64 pass6566 blue = flask.Blueprint('blue', __name__)
5 unmodified lines
7273 def my_function_exception_handler(e):74 assert isinstance(e, MyFunctionException)75 return 'bam'7677 blue.register_error_handler(MyFunctionException, my_function_exception_handler)7879 @blue.route('/decorator')80 def blue_deco_test():81 raise MyDecoratorException()8283 @blue.route('/function')84 def blue_func_test():85 raise MyFunctionException()8686 app = flask.Flask(__name__)87 app.register_blueprint(blue)8889 c = app.test_client()89 assert client.get('/decorator').data == b'boom'90 assert client.get('/function').data == b'bam'9191 assert c.get('/decorator').data == b'boom'92 assert c.get('/function').data == b'bam'9294def test_blueprint_url_definitions():93def test_blueprint_app_error_handling(app, client):94 errors = flask.Blueprint('errors', __name__)9596 @errors.app_errorhandler(403)97 def forbidden_handler(e):98 return 'you shall not pass', 40399100 @app.route('/forbidden')101 def app_forbidden():102 flask.abort(403)103104 forbidden_bp = flask.Blueprint('forbidden_bp', __name__)105106 @forbidden_bp.route('/nope')107 def bp_forbidden():108 flask.abort(403)109110 app.register_blueprint(errors)111 app.register_blueprint(forbidden_bp)112113 assert client.get('/forbidden').data == b'you shall not pass'114 assert client.get('/nope').data == b'you shall not pass'115116117def test_blueprint_url_definitions(app, client):118 bp = flask.Blueprint('test', __name__)119120 @bp.route('/foo', defaults={'baz': 42})121 def foo(bar, baz):
2 unmodified lines
124 @bp.route('/bar')125 def bar(bar):126 return text_type(bar)127105 app = flask.Flask(__name__)128 app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23})129 app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19})130109 c = app.test_client()110 assert c.get('/1/foo').data == b'23/42'111 assert c.get('/2/foo').data == b'19/42'112 assert c.get('/1/bar').data == b'23'113 assert c.get('/2/bar').data == b'19'131 assert client.get('/1/foo').data == b'23/42'132 assert client.get('/2/foo').data == b'19/42'133 assert client.get('/1/bar').data == b'23'134 assert client.get('/2/bar').data == b'19'135136115def test_blueprint_url_processors():137def test_blueprint_url_processors(app, client):138 bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')139140 @bp.url_defaults141 def add_language_code(endpoint, values):
10 unmodified lines
152 @bp.route('/about')153 def about():154 return flask.url_for('.index')155134 app = flask.Flask(__name__)156 app.register_blueprint(bp)157137 c = app.test_client()158 assert client.get('/de/').data == b'/de/about'159 assert client.get('/de/about').data == b'/de/'160139 assert c.get('/de/').data == b'/de/about'140 assert c.get('/de/about').data == b'/de/'161162def test_templates_and_static(test_apps):163 from blueprintapp import app144 c = app.test_client()164 client = app.test_client()165146 rv = c.get('/')166 rv = client.get('/')167 assert rv.data == b'Hello from the Frontend'148 rv = c.get('/admin/')168 rv = client.get('/admin/')169 assert rv.data == b'Hello from the Admin'150 rv = c.get('/admin/index2')170 rv = client.get('/admin/index2')171 assert rv.data == b'Hello from the Admin'152 rv = c.get('/admin/static/test.txt')172 rv = client.get('/admin/static/test.txt')173 assert rv.data.strip() == b'Admin File'174 rv.close()155 rv = c.get('/admin/static/css/test.css')175 rv = client.get('/admin/static/css/test.css')176 assert rv.data.strip() == b'/* nested file */'177 rv.close()178179 # try/finally, in case other tests use this app for Blueprint tests.
2 unmodified lines
182 expected_max_age = 3600183 if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == expected_max_age:184 expected_max_age = 7200185 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age166 rv = c.get('/admin/static/css/test.css')186 rv = client.get('/admin/static/css/test.css')187 cc = parse_cache_control_header(rv.headers['Cache-Control'])188 assert cc.max_age == expected_max_age189 rv.close()190 finally:
2 unmodified lines
193 with app.test_request_context():194 assert flask.url_for('admin.static', filename='test.txt') == '/admin/static/test.txt'195196 with app.test_request_context():177 try:197 with pytest.raises(TemplateNotFound) as e:198 flask.render_template('missing.html')179 except TemplateNotFound as e:180 assert e.name == 'missing.html'199 assert e.value.name == 'missing.html'181 else:182 assert 0, 'expected exception'200201 with flask.Flask(__name__).test_request_context():202 assert flask.render_template('nested/nested.txt') == 'I\'m nested'203187def test_default_static_cache_timeout():188 app = flask.Flask(__name__)204205def test_default_static_cache_timeout(app):206 class MyBlueprint(flask.Blueprint):207 def get_send_file_max_age(self, filename):208 return 100209
14 unmodified lines
224 rv.close()225 finally:226 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default227228229def test_templates_list(test_apps):230 from blueprintapp import app231 templates = sorted(app.jinja_env.list_templates())232 assert templates == ['admin/index.html', 'frontend/index.html']233234216def test_dotted_names():235def test_dotted_names(app, client):236 frontend = flask.Blueprint('myapp.frontend', __name__)237 backend = flask.Blueprint('myapp.backend', __name__)238239 @frontend.route('/fe')
7 unmodified lines
247 @backend.route('/be')248 def backend_index():249 return flask.url_for('myapp.frontend.frontend_index')250232 app = flask.Flask(__name__)251 app.register_blueprint(frontend)252 app.register_blueprint(backend)253236 c = app.test_client()237 assert c.get('/fe').data.strip() == b'/be'238 assert c.get('/fe2').data.strip() == b'/fe'239 assert c.get('/be').data.strip() == b'/fe'254 assert client.get('/fe').data.strip() == b'/be'255 assert client.get('/fe2').data.strip() == b'/fe'256 assert client.get('/be').data.strip() == b'/fe'257241def test_dotted_names_from_app():242 app = flask.Flask(__name__)243 app.testing = True258259def test_dotted_names_from_app(app, client):260 test = flask.Blueprint('test', __name__)261262 @app.route('/')263 def app_index():
4 unmodified lines
268 return flask.url_for('app_index')269270 app.register_blueprint(test)271256 with app.test_client() as c:257 rv = c.get('/')258 assert rv.data == b'/test/'272 rv = client.get('/')273 assert rv.data == b'/test/'274275260def test_empty_url_defaults():276def test_empty_url_defaults(app, client):277 bp = flask.Blueprint('bp', __name__)278279 @bp.route('/', defaults={'page': 1})280 @bp.route('/page/<int:page>')281 def something(page):282 return str(page)283268 app = flask.Flask(__name__)284 app.register_blueprint(bp)285271 c = app.test_client()272 assert c.get('/').data == b'1'273 assert c.get('/page/2').data == b'2'286 assert client.get('/').data == b'1'287 assert client.get('/page/2').data == b'2'288275def test_route_decorator_custom_endpoint():289290def test_route_decorator_custom_endpoint(app, client):291 bp = flask.Blueprint('bp', __name__)292293 @bp.route('/foo')294 def foo():
10 unmodified lines
305 @bp.route('/bar/foo')306 def bar_foo():307 return flask.request.endpoint308295 app = flask.Flask(__name__)309 app.register_blueprint(bp, url_prefix='/py')310311 @app.route('/')312 def index():313 return flask.request.endpoint314302 c = app.test_client()303 assert c.get('/').data == b'index'304 assert c.get('/py/foo').data == b'bp.foo'305 assert c.get('/py/bar').data == b'bp.bar'306 assert c.get('/py/bar/123').data == b'bp.123'307 assert c.get('/py/bar/foo').data == b'bp.bar_foo'315 assert client.get('/').data == b'index'316 assert client.get('/py/foo').data == b'bp.foo'317 assert client.get('/py/bar').data == b'bp.bar'318 assert client.get('/py/bar/123').data == b'bp.123'319 assert client.get('/py/bar/foo').data == b'bp.bar_foo'320321309def test_route_decorator_custom_endpoint_with_dots():322def test_route_decorator_custom_endpoint_with_dots(app, client):323 bp = flask.Blueprint('bp', __name__)324325 @bp.route('/foo')326 def foo():
32 unmodified lines
359 bp.route('/bar/123', endpoint='bar.123'),360 lambda: None361 )362350 app = flask.Flask(__name__)363 app.register_blueprint(bp, url_prefix='/py')364353 c = app.test_client()354 assert c.get('/py/foo').data == b'bp.foo'365 assert client.get('/py/foo').data == b'bp.foo'366 # The rule's didn't actually made it through356 rv = c.get('/py/bar')367 rv = client.get('/py/bar')368 assert rv.status_code == 404358 rv = c.get('/py/bar/123')369 rv = client.get('/py/bar/123')370 assert rv.status_code == 404371361def test_template_filter():372373def test_endpoint_decorator(app, client):374 from werkzeug.routing import Rule375 app.url_map.add(Rule('/foo', endpoint='bar'))376377 bp = flask.Blueprint('bp', __name__)378379 @bp.endpoint('bar')380 def foobar():381 return flask.request.endpoint382383 app.register_blueprint(bp, url_prefix='/bp_prefix')384385 assert client.get('/foo').data == b'bar'386 assert client.get('/bp_prefix/bar').status_code == 404387388389def test_template_filter(app):390 bp = flask.Blueprint('bp', __name__)391392 @bp.app_template_filter()393 def my_reverse(s):394 return s[::-1]366 app = flask.Flask(__name__)395396 app.register_blueprint(bp, url_prefix='/py')397 assert 'my_reverse' in app.jinja_env.filters.keys()398 assert app.jinja_env.filters['my_reverse'] == my_reverse399 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'400401372def test_add_template_filter():402def test_add_template_filter(app):403 bp = flask.Blueprint('bp', __name__)404405 def my_reverse(s):406 return s[::-1]407408 bp.add_app_template_filter(my_reverse)377 app = flask.Flask(__name__)409 app.register_blueprint(bp, url_prefix='/py')410 assert 'my_reverse' in app.jinja_env.filters.keys()411 assert app.jinja_env.filters['my_reverse'] == my_reverse412 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'413414383def test_template_filter_with_name():415def test_template_filter_with_name(app):416 bp = flask.Blueprint('bp', __name__)417418 @bp.app_template_filter('strrev')419 def my_reverse(s):420 return s[::-1]388 app = flask.Flask(__name__)421422 app.register_blueprint(bp, url_prefix='/py')423 assert 'strrev' in app.jinja_env.filters.keys()424 assert app.jinja_env.filters['strrev'] == my_reverse425 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'426427394def test_add_template_filter_with_name():428def test_add_template_filter_with_name(app):429 bp = flask.Blueprint('bp', __name__)430431 def my_reverse(s):432 return s[::-1]433434 bp.add_app_template_filter(my_reverse, 'strrev')399 app = flask.Flask(__name__)435 app.register_blueprint(bp, url_prefix='/py')436 assert 'strrev' in app.jinja_env.filters.keys()437 assert app.jinja_env.filters['strrev'] == my_reverse438 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'439440405def test_template_filter_with_template():441def test_template_filter_with_template(app, client):442 bp = flask.Blueprint('bp', __name__)443444 @bp.app_template_filter()445 def super_reverse(s):446 return s[::-1]410 app = flask.Flask(__name__)447448 app.register_blueprint(bp, url_prefix='/py')449450 @app.route('/')451 def index():452 return flask.render_template('template_filter.html', value='abcd')415 rv = app.test_client().get('/')453454 rv = client.get('/')455 assert rv.data == b'dcba'456418def test_template_filter_after_route_with_template():419 app = flask.Flask(__name__)457458def test_template_filter_after_route_with_template(app, client):459 @app.route('/')460 def index():461 return flask.render_template('template_filter.html', value='abcd')462463 bp = flask.Blueprint('bp', __name__)464465 @bp.app_template_filter()466 def super_reverse(s):467 return s[::-1]468469 app.register_blueprint(bp, url_prefix='/py')428 rv = app.test_client().get('/')470 rv = client.get('/')471 assert rv.data == b'dcba'472473431def test_add_template_filter_with_template():474def test_add_template_filter_with_template(app, client):475 bp = flask.Blueprint('bp', __name__)476477 def super_reverse(s):478 return s[::-1]479480 bp.add_app_template_filter(super_reverse)436 app = flask.Flask(__name__)481 app.register_blueprint(bp, url_prefix='/py')482483 @app.route('/')484 def index():485 return flask.render_template('template_filter.html', value='abcd')441 rv = app.test_client().get('/')486487 rv = client.get('/')488 assert rv.data == b'dcba'489490444def test_template_filter_with_name_and_template():491def test_template_filter_with_name_and_template(app, client):492 bp = flask.Blueprint('bp', __name__)493494 @bp.app_template_filter('super_reverse')495 def my_reverse(s):496 return s[::-1]449 app = flask.Flask(__name__)497498 app.register_blueprint(bp, url_prefix='/py')499500 @app.route('/')501 def index():502 return flask.render_template('template_filter.html', value='abcd')454 rv = app.test_client().get('/')503504 rv = client.get('/')505 assert rv.data == b'dcba'506507457def test_add_template_filter_with_name_and_template():508def test_add_template_filter_with_name_and_template(app, client):509 bp = flask.Blueprint('bp', __name__)510511 def my_reverse(s):512 return s[::-1]513514 bp.add_app_template_filter(my_reverse, 'super_reverse')462 app = flask.Flask(__name__)515 app.register_blueprint(bp, url_prefix='/py')516517 @app.route('/')518 def index():519 return flask.render_template('template_filter.html', value='abcd')467 rv = app.test_client().get('/')520521 rv = client.get('/')522 assert rv.data == b'dcba'523524470def test_template_test():525def test_template_test(app):526 bp = flask.Blueprint('bp', __name__)527528 @bp.app_template_test()529 def is_boolean(value):530 return isinstance(value, bool)475 app = flask.Flask(__name__)531532 app.register_blueprint(bp, url_prefix='/py')533 assert 'is_boolean' in app.jinja_env.tests.keys()534 assert app.jinja_env.tests['is_boolean'] == is_boolean535 assert app.jinja_env.tests['is_boolean'](False)536537481def test_add_template_test():538def test_add_template_test(app):539 bp = flask.Blueprint('bp', __name__)540541 def is_boolean(value):542 return isinstance(value, bool)543544 bp.add_app_template_test(is_boolean)486 app = flask.Flask(__name__)545 app.register_blueprint(bp, url_prefix='/py')546 assert 'is_boolean' in app.jinja_env.tests.keys()547 assert app.jinja_env.tests['is_boolean'] == is_boolean548 assert app.jinja_env.tests['is_boolean'](False)549550492def test_template_test_with_name():551def test_template_test_with_name(app):552 bp = flask.Blueprint('bp', __name__)553554 @bp.app_template_test('boolean')555 def is_boolean(value):556 return isinstance(value, bool)497 app = flask.Flask(__name__)557558 app.register_blueprint(bp, url_prefix='/py')559 assert 'boolean' in app.jinja_env.tests.keys()560 assert app.jinja_env.tests['boolean'] == is_boolean561 assert app.jinja_env.tests['boolean'](False)562563503def test_add_template_test_with_name():564def test_add_template_test_with_name(app):565 bp = flask.Blueprint('bp', __name__)566567 def is_boolean(value):568 return isinstance(value, bool)569570 bp.add_app_template_test(is_boolean, 'boolean')508 app = flask.Flask(__name__)571 app.register_blueprint(bp, url_prefix='/py')572 assert 'boolean' in app.jinja_env.tests.keys()573 assert app.jinja_env.tests['boolean'] == is_boolean574 assert app.jinja_env.tests['boolean'](False)575576514def test_template_test_with_template():577def test_template_test_with_template(app, client):578 bp = flask.Blueprint('bp', __name__)579580 @bp.app_template_test()581 def boolean(value):582 return isinstance(value, bool)519 app = flask.Flask(__name__)583584 app.register_blueprint(bp, url_prefix='/py')585586 @app.route('/')587 def index():588 return flask.render_template('template_test.html', value=False)524 rv = app.test_client().get('/')589590 rv = client.get('/')591 assert b'Success!' in rv.data592527def test_template_test_after_route_with_template():528 app = flask.Flask(__name__)593594def test_template_test_after_route_with_template(app, client):595 @app.route('/')596 def index():597 return flask.render_template('template_test.html', value=False)598599 bp = flask.Blueprint('bp', __name__)600601 @bp.app_template_test()602 def boolean(value):603 return isinstance(value, bool)604605 app.register_blueprint(bp, url_prefix='/py')537 rv = app.test_client().get('/')606 rv = client.get('/')607 assert b'Success!' in rv.data608609540def test_add_template_test_with_template():610def test_add_template_test_with_template(app, client):611 bp = flask.Blueprint('bp', __name__)612613 def boolean(value):614 return isinstance(value, bool)615616 bp.add_app_template_test(boolean)545 app = flask.Flask(__name__)617 app.register_blueprint(bp, url_prefix='/py')618619 @app.route('/')620 def index():621 return flask.render_template('template_test.html', value=False)550 rv = app.test_client().get('/')622623 rv = client.get('/')624 assert b'Success!' in rv.data625626553def test_template_test_with_name_and_template():627def test_template_test_with_name_and_template(app, client):628 bp = flask.Blueprint('bp', __name__)629630 @bp.app_template_test('boolean')631 def is_boolean(value):632 return isinstance(value, bool)558 app = flask.Flask(__name__)633634 app.register_blueprint(bp, url_prefix='/py')635636 @app.route('/')637 def index():638 return flask.render_template('template_test.html', value=False)563 rv = app.test_client().get('/')639640 rv = client.get('/')641 assert b'Success!' in rv.data642643566def test_add_template_test_with_name_and_template():644def test_add_template_test_with_name_and_template(app, client):645 bp = flask.Blueprint('bp', __name__)646647 def is_boolean(value):648 return isinstance(value, bool)649650 bp.add_app_template_test(is_boolean, 'boolean')571 app = flask.Flask(__name__)651 app.register_blueprint(bp, url_prefix='/py')652653 @app.route('/')654 def index():655 return flask.render_template('template_test.html', value=False)576 rv = app.test_client().get('/')656657 rv = client.get('/')658 assert b'Success!' in rv.data659660661def test_context_processing(app, client):662 answer_bp = flask.Blueprint('answer_bp', __name__)663664 template_string = lambda: flask.render_template_string(665 '{% if notanswer %}{{ notanswer }} is not the answer. {% endif %}'666 '{% if answer %}{{ answer }} is the answer.{% endif %}'667 )668669 # App global context processor670 @answer_bp.app_context_processor671 def not_answer_context_processor():672 return {'notanswer': 43}673674 # Blueprint local context processor675 @answer_bp.context_processor676 def answer_context_processor():677 return {'answer': 42}678679 # Setup endpoints for testing680 @answer_bp.route('/bp')681 def bp_page():682 return template_string()683684 @app.route('/')685 def app_page():686 return template_string()687688 # Register the blueprint689 app.register_blueprint(answer_bp)690691 app_page_bytes = client.get('/').data692 answer_page_bytes = client.get('/bp').data693694 assert b'43' in app_page_bytes695 assert b'42' not in app_page_bytes696697 assert b'42' in answer_page_bytes698 assert b'43' in answer_page_bytes699700701def test_template_global(app):702 bp = flask.Blueprint('bp', __name__)703704 @bp.app_template_global()705 def get_answer():706 return 42707708 # Make sure the function is not in the jinja_env already709 assert 'get_answer' not in app.jinja_env.globals.keys()710 app.register_blueprint(bp)711712 # Tests713 assert 'get_answer' in app.jinja_env.globals.keys()714 assert app.jinja_env.globals['get_answer'] is get_answer715 assert app.jinja_env.globals['get_answer']() == 42716717 with app.app_context():718 rv = flask.render_template_string('{{ get_answer() }}')719 assert rv == '42'720721722def test_request_processing(app, client):723 bp = flask.Blueprint('bp', __name__)724 evts = []725726 @bp.before_request727 def before_bp():728 evts.append('before')729730 @bp.after_request731 def after_bp(response):732 response.data += b'|after'733 evts.append('after')734 return response735736 @bp.teardown_request737 def teardown_bp(exc):738 evts.append('teardown')739740 # Setup routes for testing741 @bp.route('/bp')742 def bp_endpoint():743 return 'request'744745 app.register_blueprint(bp)746747 assert evts == []748 rv = client.get('/bp')749 assert rv.data == b'request|after'750 assert evts == ['before', 'after', 'teardown']751752753def test_app_request_processing(app, client):754 bp = flask.Blueprint('bp', __name__)755 evts = []756757 @bp.before_app_first_request758 def before_first_request():759 evts.append('first')760761 @bp.before_app_request762 def before_app():763 evts.append('before')764765 @bp.after_app_request766 def after_app(response):767 response.data += b'|after'768 evts.append('after')769 return response770771 @bp.teardown_app_request772 def teardown_app(exc):773 evts.append('teardown')774775 app.register_blueprint(bp)776777 # Setup routes for testing778 @app.route('/')779 def bp_endpoint():780 return 'request'781782 # before first request783 assert evts == []784785 # first request786 resp = client.get('/').data787 assert resp == b'request|after'788 assert evts == ['first', 'before', 'after', 'teardown']789790 # second request791 resp = client.get('/').data792 assert resp == b'request|after'793 assert evts == ['first'] + ['before', 'after', 'teardown'] * 2794795796def test_app_url_processors(app, client):797 bp = flask.Blueprint('bp', __name__)798799 # Register app-wide url defaults and preprocessor on blueprint800 @bp.app_url_defaults801 def add_language_code(endpoint, values):802 values.setdefault('lang_code', flask.g.lang_code)803804 @bp.app_url_value_preprocessor805 def pull_lang_code(endpoint, values):806 flask.g.lang_code = values.pop('lang_code')807808 # Register route rules at the app level809 @app.route('/<lang_code>/')810 def index():811 return flask.url_for('about')812813 @app.route('/<lang_code>/about')814 def about():815 return flask.url_for('index')816817 app.register_blueprint(bp)818819 assert client.get('/de/').data == b'/de/about'820 assert client.get('/de/about').data == b'/de/'
added:tests/test_cli.py+346 added
1# -*- coding: utf-8 -*-2"""3 tests.test_cli4 ~~~~~~~~~~~~~~56 :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#14from __future__ import absolute_import, print_function15import os16import sys17from functools import partial1819import click20import pytest21from click.testing import CliRunner22from flask import Flask, current_app2324from flask.cli import cli, AppGroup, FlaskGroup, NoAppException, ScriptInfo, \25 find_best_app, locate_app, with_appcontext, prepare_exec_for_file, \26 find_default_import_path, get_version272829@pytest.fixture30def runner():31 return CliRunner()323334def test_cli_name(test_apps):35 """Make sure the CLI object's name is the app's name and not the app itself"""36 from cliapp.app import testapp37 assert testapp.cli.name == testapp.name383940def test_find_best_app(test_apps):41 """Test if `find_best_app` behaves as expected with different combinations of input."""42 script_info = ScriptInfo()4344 class Module:45 app = Flask('appname')4647 assert find_best_app(script_info, Module) == Module.app4849 class Module:50 application = Flask('appname')5152 assert find_best_app(script_info, Module) == Module.application5354 class Module:55 myapp = Flask('appname')5657 assert find_best_app(script_info, Module) == Module.myapp5859 class Module:60 @staticmethod61 def create_app():62 return Flask('appname')6364 assert isinstance(find_best_app(script_info, Module), Flask)65 assert find_best_app(script_info, Module).name == 'appname'6667 class Module:68 @staticmethod69 def create_app(foo):70 return Flask('appname')7172 assert isinstance(find_best_app(script_info, Module), Flask)73 assert find_best_app(script_info, Module).name == 'appname'7475 class Module:76 @staticmethod77 def create_app(foo=None, script_info=None):78 return Flask('appname')7980 assert isinstance(find_best_app(script_info, Module), Flask)81 assert find_best_app(script_info, Module).name == 'appname'8283 class Module:84 @staticmethod85 def make_app():86 return Flask('appname')8788 assert isinstance(find_best_app(script_info, Module), Flask)89 assert find_best_app(script_info, Module).name == 'appname'9091 class Module:92 myapp = Flask('appname1')9394 @staticmethod95 def create_app():96 return Flask('appname2')9798 assert find_best_app(script_info, Module) == Module.myapp99100 class Module:101 myapp = Flask('appname1')102103 @staticmethod104 def create_app():105 return Flask('appname2')106107 assert find_best_app(script_info, Module) == Module.myapp108109 class Module:110 pass111112 pytest.raises(NoAppException, find_best_app, script_info, Module)113114 class Module:115 myapp1 = Flask('appname1')116 myapp2 = Flask('appname2')117118 pytest.raises(NoAppException, find_best_app, script_info, Module)119120 class Module:121 @staticmethod122 def create_app(foo, bar):123 return Flask('appname2')124125 pytest.raises(NoAppException, find_best_app, script_info, Module)126127128def test_prepare_exec_for_file(test_apps):129 """Expect the correct path to be set and the correct module name to be returned.130131 :func:`prepare_exec_for_file` has a side effect, where132 the parent directory of given file is added to `sys.path`.133 """134 realpath = os.path.realpath('/tmp/share/test.py')135 dirname = os.path.dirname(realpath)136 assert prepare_exec_for_file('/tmp/share/test.py') == 'test'137 assert dirname in sys.path138139 realpath = os.path.realpath('/tmp/share/__init__.py')140 dirname = os.path.dirname(os.path.dirname(realpath))141 assert prepare_exec_for_file('/tmp/share/__init__.py') == 'share'142 assert dirname in sys.path143144 with pytest.raises(NoAppException):145 prepare_exec_for_file('/tmp/share/test.txt')146147148def test_locate_app(test_apps):149 """Test of locate_app."""150 script_info = ScriptInfo()151 assert locate_app(script_info, "cliapp.app").name == "testapp"152 assert locate_app(script_info, "cliapp.app:testapp").name == "testapp"153 assert locate_app(script_info, "cliapp.multiapp:app1").name == "app1"154 pytest.raises(NoAppException, locate_app,155 script_info, "notanpp.py")156 pytest.raises(NoAppException, locate_app,157 script_info, "cliapp/app")158 pytest.raises(RuntimeError, locate_app,159 script_info, "cliapp.app:notanapp")160 pytest.raises(NoAppException, locate_app,161 script_info, "cliapp.importerrorapp")162163164def test_find_default_import_path(test_apps, monkeypatch, tmpdir):165 """Test of find_default_import_path."""166 monkeypatch.delitem(os.environ, 'FLASK_APP', raising=False)167 assert find_default_import_path() == None168 monkeypatch.setitem(os.environ, 'FLASK_APP', 'notanapp')169 assert find_default_import_path() == 'notanapp'170 tmpfile = tmpdir.join('testapp.py')171 tmpfile.write('')172 monkeypatch.setitem(os.environ, 'FLASK_APP', str(tmpfile))173 expect_rv = prepare_exec_for_file(str(tmpfile))174 assert find_default_import_path() == expect_rv175176177def test_get_version(test_apps, capsys):178 """Test of get_version."""179 from flask import __version__ as flask_ver180 from sys import version as py_ver181182 class MockCtx(object):183 resilient_parsing = False184 color = None185186 def exit(self): return187188 ctx = MockCtx()189 get_version(ctx, None, "test")190 out, err = capsys.readouterr()191 assert flask_ver in out192 assert py_ver in out193194195def test_scriptinfo(test_apps):196 """Test of ScriptInfo."""197 obj = ScriptInfo(app_import_path="cliapp.app:testapp")198 assert obj.load_app().name == "testapp"199 assert obj.load_app().name == "testapp"200201 def create_app(info):202 return Flask("createapp")203204 obj = ScriptInfo(create_app=create_app)205 app = obj.load_app()206 assert app.name == "createapp"207 assert obj.load_app() == app208209210def test_with_appcontext(runner):211 """Test of with_appcontext."""212213 @click.command()214 @with_appcontext215 def testcmd():216 click.echo(current_app.name)217218 obj = ScriptInfo(create_app=lambda info: Flask("testapp"))219220 result = runner.invoke(testcmd, obj=obj)221 assert result.exit_code == 0222 assert result.output == 'testapp\n'223224225def test_appgroup(runner):226 """Test of with_appcontext."""227228 @click.group(cls=AppGroup)229 def cli():230 pass231232 @cli.command(with_appcontext=True)233 def test():234 click.echo(current_app.name)235236 @cli.group()237 def subgroup():238 pass239240 @subgroup.command(with_appcontext=True)241 def test2():242 click.echo(current_app.name)243244 obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))245246 result = runner.invoke(cli, ['test'], obj=obj)247 assert result.exit_code == 0248 assert result.output == 'testappgroup\n'249250 result = runner.invoke(cli, ['subgroup', 'test2'], obj=obj)251 assert result.exit_code == 0252 assert result.output == 'testappgroup\n'253254255def test_flaskgroup(runner):256 """Test FlaskGroup."""257258 def create_app(info):259 return Flask("flaskgroup")260261 @click.group(cls=FlaskGroup, create_app=create_app)262 def cli(**params):263 pass264265 @cli.command()266 def test():267 click.echo(current_app.name)268269 result = runner.invoke(cli, ['test'])270 assert result.exit_code == 0271 assert result.output == 'flaskgroup\n'272273274def test_print_exceptions(runner):275 """Print the stacktrace if the CLI."""276277 def create_app(info):278 raise Exception("oh no")279 return Flask("flaskgroup")280281 @click.group(cls=FlaskGroup, create_app=create_app)282 def cli(**params):283 pass284285 result = runner.invoke(cli, ['--help'])286 assert result.exit_code == 0287 assert 'Exception: oh no' in result.output288 assert 'Traceback' in result.output289290291class TestRoutes:292 @pytest.fixture293 def invoke(self, runner):294 def create_app(info):295 app = Flask(__name__)296 app.testing = True297298 @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])299 def yyy_get_post(x, y):300 pass301302 @app.route('/zzz_post', methods=['POST'])303 def aaa_post():304 pass305306 return app307308 cli = FlaskGroup(create_app=create_app)309 return partial(runner.invoke, cli)310311 def expect_order(self, order, output):312 # skip the header and match the start of each row313 for expect, line in zip(order, output.splitlines()[2:]):314 # do this instead of startswith for nicer pytest output315 assert line[:len(expect)] == expect316317 def test_simple(self, invoke):318 result = invoke(['routes'])319 assert result.exit_code == 0320 self.expect_order(321 ['aaa_post', 'static', 'yyy_get_post'],322 result.output323 )324325 def test_sort(self, invoke):326 default_output = invoke(['routes']).output327 endpoint_output = invoke(['routes', '-s', 'endpoint']).output328 assert default_output == endpoint_output329 self.expect_order(330 ['static', 'yyy_get_post', 'aaa_post'],331 invoke(['routes', '-s', 'methods']).output332 )333 self.expect_order(334 ['yyy_get_post', 'static', 'aaa_post'],335 invoke(['routes', '-s', 'rule']).output336 )337 self.expect_order(338 ['aaa_post', 'yyy_get_post', 'static'],339 invoke(['routes', '-s', 'match']).output340 )341342 def test_all_methods(self, invoke):343 output = invoke(['routes']).output344 assert 'GET, HEAD, OPTIONS, POST' not in output345 output = invoke(['routes', '--all-methods']).output346 assert 'GET, HEAD, OPTIONS, POST' in output
modified:tests/test_config.py+45 added-30 removed
5 unmodified lines
6 :copyright: (c) 2015 by the Flask Team, see AUTHORS for more details.7 :license: BSD, see LICENSE for more details.8"""910import pytest1011from datetime import timedelta12import os13import textwrap1415import flask16from flask._compat import PY217import pytest181920# config keys used for the TestConfig21TEST_KEY = 'foo'
69 unmodified lines
91 env = os.environ92 try:93 os.environ = {}94 app = flask.Flask(__name__)91 try:95 with pytest.raises(RuntimeError) as e:96 app.config.from_envvar('FOO_SETTINGS')93 except RuntimeError as e:94 assert "'FOO_SETTINGS' is not set" in str(e)97 assert "'FOO_SETTINGS' is not set" in str(e.value)95 else:96 assert 0, 'expected exception'98 assert not app.config.from_envvar('FOO_SETTINGS', silent=True)99100 os.environ = {'FOO_SETTINGS': __file__.rsplit('.', 1)[0] + '.py'}101 assert app.config.from_envvar('FOO_SETTINGS')
5 unmodified lines
107def test_config_from_envvar_missing():108 env = os.environ109 try:110 os.environ = {'FOO_SETTINGS': 'missing.cfg'}110 try:111 with pytest.raises(IOError) as e:112 app = flask.Flask(__name__)113 app.config.from_envvar('FOO_SETTINGS')113 except IOError as e:114 msg = str(e)115 assert msg.startswith('[Errno 2] Unable to load configuration '116 'file (No such file or directory):')117 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'")118 else:119 assert False, 'expected IOError'118 assert not app.config.from_envvar('FOO_SETTINGS', silent=True)119 finally:120 os.environ = env121122123def test_config_missing():124 app = flask.Flask(__name__)127 try:125 with pytest.raises(IOError) as e:126 app.config.from_pyfile('missing.cfg')129 except IOError as e:130 msg = str(e)131 assert msg.startswith('[Errno 2] Unable to load configuration '132 'file (No such file or directory):')133 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'")134 else:135 assert 0, 'expected config'131 assert not app.config.from_pyfile('missing.cfg', silent=True)132133134def test_config_missing_json():135 app = flask.Flask(__name__)141 try:136 with pytest.raises(IOError) as e:137 app.config.from_json('missing.json')143 except IOError as e:144 msg = str(e)145 assert msg.startswith('[Errno 2] Unable to load configuration '146 'file (No such file or directory):')147 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'")148 else:149 assert 0, 'expected config'142 assert not app.config.from_json('missing.json', silent=True)143144145def test_custom_config_class():
13 unmodified lines
159 app.config['PERMANENT_SESSION_LIFETIME'] = 42160 assert app.permanent_session_lifetime.seconds == 42161162163def test_send_file_max_age():164 app = flask.Flask(__name__)165 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600166 assert app.send_file_max_age_default.seconds == 3600167 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(hours=2)168 assert app.send_file_max_age_default.seconds == 7200169170171def test_get_namespace():172 app = flask.Flask(__name__)173 app.config['FOO_OPTION_1'] = 'foo option 1'174 app.config['FOO_OPTION_2'] = 'foo option 2'
14 unmodified lines
189 bar_options = app.config.get_namespace('BAR_', lowercase=False, trim_namespace=False)190 assert 2 == len(bar_options)191 assert 'bar stuff 1' == bar_options['BAR_STUFF_1']192 assert 'bar stuff 2' == bar_options['BAR_STUFF_2']193194195@pytest.mark.parametrize('encoding', ['utf-8', 'iso-8859-15', 'latin-1'])196def test_from_pyfile_weird_encoding(tmpdir, encoding):197 f = tmpdir.join('my_config.py')198 f.write_binary(textwrap.dedent(u'''199 # -*- coding: {0} -*-200 TEST_VALUE = "föö"201 '''.format(encoding)).encode(encoding))202 app = flask.Flask(__name__)203 app.config.from_pyfile(str(f))204 value = app.config['TEST_VALUE']205 if PY2:206 value = value.decode(encoding)207 assert value == u'föö'
modified:tests/test_deprecations.py+6 added-17 removed
13 unmodified lines
14import flask151617class TestRequestDeprecation(object):1819 def test_request_json(self, catch_deprecation_warnings):18 def test_request_json(self, recwarn, app, client):19 """Request.json is deprecated"""21 app = flask.Flask(__name__)22 app.testing = True2021 @app.route('/', methods=['POST'])22 def index():23 assert flask.request.json == {'spam': 42}24 print(flask.request.json)25 return 'OK'2630 with catch_deprecation_warnings() as captured:31 c = app.test_client()32 c.post('/', data='{"spam": 42}', content_type='application/json')27 client.post('/', data='{"spam": 42}', content_type='application/json')28 recwarn.pop(DeprecationWarning)2934 assert len(captured) == 13536 def test_request_module(self, catch_deprecation_warnings):30 def test_request_module(self, recwarn, app, client):31 """Request.module is deprecated"""38 app = flask.Flask(__name__)39 app.testing = True3233 @app.route('/')34 def index():35 assert flask.request.module is None36 return 'OK'3746 with catch_deprecation_warnings() as captured:47 c = app.test_client()48 c.get('/')4950 assert len(captured) == 138 client.get('/')39 recwarn.pop(DeprecationWarning)
modified:tests/test_ext.py+18 added-8 removed
19 unmodified lines
20from flask._compat import PY2212223@pytest.fixture(autouse=True)24def disable_extwarnings(recwarn):25 from flask.exthook import ExtDeprecationWarning2627 yield2829 assert set(w.category for w in recwarn.list) \30 <= set([ExtDeprecationWarning])31 recwarn.clear()323334@pytest.fixture(autouse=True)24def importhook_setup(monkeypatch, request):35def importhook_setup(monkeypatch):36 # we clear this out for various reasons. The most important one is37 # that a real flaskext could be in there which would disable our38 # fake package. Secondly we want to make sure that the flaskext39 # import hook does not break on reloading.
16 unmodified lines
56 cls.__name__ == 'ExtensionImporter':57 import_hooks += 158 assert import_hooks == 15949 def teardown():50 from flask import ext51 for key in ext.__dict__:52 assert '.' not in key60 yield6154 request.addfinalizer(teardown)62 from flask import ext63 for key in ext.__dict__:64 assert '.' not in key656667@pytest.fixture68def newext_simple(modules_tmpdir):
107 unmodified lines
176177def test_no_error_swallowing(flaskext_broken):178 with pytest.raises(ImportError) as excinfo:179 import flask.ext.broken170171 assert excinfo.type is ImportError180 # python3.6 raises a subclass of ImportError: 'ModuleNotFoundError'181 assert issubclass(excinfo.type, ImportError)182 if PY2:183 message = 'No module named missing_module'184 else:185 message = 'No module named \'missing_module\''
12 unmodified lines
modified:tests/test_helpers.py+535 added-285 removed
10 unmodified lines
1112import pytest1314import os15import uuid16import datetime1718import flask19from logging import StreamHandler20from werkzeug.datastructures import Range21from werkzeug.exceptions import BadRequest, NotFound22from werkzeug.http import parse_cache_control_header, parse_options_header23from werkzeug.http import http_date24from flask._compat import StringIO, text_type25from flask.helpers import get_debug_flag, make_response262728def has_encoding(name):29 try:
4 unmodified lines
34 return False353637class TestJSON(object):38 def test_ignore_cached_json(self, app):39 with app.test_request_context('/', method='POST', data='malformed',40 content_type='application/json'):41 assert flask.request.get_json(silent=True, cache=True) is None42 with pytest.raises(BadRequest):43 flask.request.get_json(silent=False, cache=False)4434 def test_jsonify_date_types(self):35 """Test jsonify with datetime.date and datetime.datetime types."""3637 test_dates = (38 datetime.datetime(1973, 3, 11, 6, 30, 45),39 datetime.date(1975, 1, 5)40 )4142 app = flask.Flask(__name__)43 c = app.test_client()4445 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())5152 def test_post_empty_json_adds_exception_to_response_content_in_debug(self):45 def test_post_empty_json_adds_exception_to_response_content_in_debug(self, app, client):53 app = flask.Flask(__name__)46 app.config['DEBUG'] = True4748 @app.route('/json', methods=['POST'])49 def post_json():50 flask.request.get_json()51 return None59 c = app.test_client()60 rv = c.post('/json', data=None, content_type='application/json')5253 rv = client.post('/json', data=None, content_type='application/json')54 assert rv.status_code == 40055 assert b'Failed to decode JSON object' in rv.data5664 def test_post_empty_json_wont_add_exception_to_response_if_no_debug(self):65 app = flask.Flask(__name__)57 def test_post_empty_json_wont_add_exception_to_response_if_no_debug(self, app, client):58 app.config['DEBUG'] = False5960 @app.route('/json', methods=['POST'])61 def post_json():62 flask.request.get_json()63 return None71 c = app.test_client()72 rv = c.post('/json', data=None, content_type='application/json')6465 rv = client.post('/json', data=None, content_type='application/json')66 assert rv.status_code == 40067 assert b'Failed to decode JSON object' not in rv.data6876 def test_json_bad_requests(self):77 app = flask.Flask(__name__)69 def test_json_bad_requests(self, app, client):7071 @app.route('/json', methods=['POST'])72 def return_json():73 return flask.jsonify(foo=text_type(flask.request.get_json()))81 c = app.test_client()82 rv = c.post('/json', data='malformed', content_type='application/json')7475 rv = client.post('/json', data='malformed', content_type='application/json')76 assert rv.status_code == 4007785 def test_json_custom_mimetypes(self):86 app = flask.Flask(__name__)78 def test_json_custom_mimetypes(self, app, client):7980 @app.route('/json', methods=['POST'])81 def return_json():82 return flask.request.get_json()90 c = app.test_client()91 rv = c.post('/json', data='"foo"', content_type='application/x+json')8384 rv = client.post('/json', data='"foo"', content_type='application/x+json')85 assert rv.data == b'foo'8694 def test_json_body_encoding(self):95 app = flask.Flask(__name__)96 app.testing = True87 def test_json_body_encoding(self, app, client):8889 @app.route('/')90 def index():91 return flask.request.get_json()92101 c = app.test_client()102 resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),103 content_type='application/json; charset=iso-8859-15')93 resp = client.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),94 content_type='application/json; charset=iso-8859-15')95 assert resp.data == u'Hällo Wörld'.encode('utf-8')96106 def test_jsonify(self):107 d = dict(a=23, b=42, c=[1, 2, 3])108 app = flask.Flask(__name__)97 @pytest.mark.parametrize('test_value,expected', [(True, '"\\u2603"'), (False, u'"\u2603"')])98 def test_json_as_unicode(self, test_value, expected, app, app_ctx):99100 app.config['JSON_AS_ASCII'] = test_value101 rv = flask.json.dumps(u'\N{SNOWMAN}')102 assert rv == expected103104 def test_json_dump_to_file(self, app, app_ctx):105 test_data = {'name': 'Flask'}106 out = StringIO()107108 flask.json.dump(test_data, out)109 out.seek(0)110 rv = flask.json.load(out)111 assert rv == test_data112113 @pytest.mark.parametrize('test_value', [0, -1, 1, 23, 3.14, 's', "longer string", True, False, None])114 def test_jsonify_basic_types(self, test_value, app, client):115 """Test jsonify with basic types."""116117 url = '/jsonify_basic_types'118 app.add_url_rule(url, url, lambda x=test_value: flask.jsonify(x))119 rv = client.get(url)120 assert rv.mimetype == 'application/json'121 assert flask.json.loads(rv.data) == test_value122123 def test_jsonify_dicts(self, app, client):124 """Test jsonify with dicts and kwargs unpacking."""125 d = {'a': 0, 'b': 23, 'c': 3.14, 'd': 't',126 'e': 'Hi', 'f': True, 'g': False,127 'h': ['test list', 10, False],128 'i': {'test': 'dict'}}129130 @app.route('/kw')131 def return_kwargs():132 return flask.jsonify(**d)133134 @app.route('/dict')135 def return_dict():136 return flask.jsonify(d)115 c = app.test_client()137138 for url in '/kw', '/dict':117 rv = c.get(url)139 rv = client.get(url)140 assert rv.mimetype == 'application/json'141 assert flask.json.loads(rv.data) == d142121 def test_json_as_unicode(self):122 app = flask.Flask(__name__)143 def test_jsonify_arrays(self, app, client):144 """Test jsonify of lists and args unpacking."""145 l = [146 0, 42, 3.14, 't', 'hello', True, False,147 ['test list', 2, False],148 {'test': 'dict'}149 ]150124 app.config['JSON_AS_ASCII'] = True125 with app.app_context():126 rv = flask.json.dumps(u'\N{SNOWMAN}')127 assert rv == '"\\u2603"'151 @app.route('/args_unpack')152 def return_args_unpack():153 return flask.jsonify(*l)154129 app.config['JSON_AS_ASCII'] = False130 with app.app_context():131 rv = flask.json.dumps(u'\N{SNOWMAN}')132 assert rv == u'"\u2603"'155 @app.route('/array')156 def return_array():157 return flask.jsonify(l)158134 def test_json_attr(self):135 app = flask.Flask(__name__)159 for url in '/args_unpack', '/array':160 rv = client.get(url)161 assert rv.mimetype == 'application/json'162 assert flask.json.loads(rv.data) == l163164 def test_jsonify_date_types(self, app, client):165 """Test jsonify with datetime.date and datetime.datetime types."""166 test_dates = (167 datetime.datetime(1973, 3, 11, 6, 30, 45),168 datetime.date(1975, 1, 5)169 )170171 for i, d in enumerate(test_dates):172 url = '/datetest{0}'.format(i)173 app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val))174 rv = client.get(url)175 assert rv.mimetype == 'application/json'176 assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple())177178 def test_jsonify_uuid_types(self, app, client):179 """Test jsonify with uuid.UUID types"""180181 test_uuid = uuid.UUID(bytes=b'\xDE\xAD\xBE\xEF' * 4)182 url = '/uuid_test'183 app.add_url_rule(url, url, lambda: flask.jsonify(x=test_uuid))184185 rv = client.get(url)186187 rv_x = flask.json.loads(rv.data)['x']188 assert rv_x == str(test_uuid)189 rv_uuid = uuid.UUID(rv_x)190 assert rv_uuid == test_uuid191192 def test_json_attr(self, app, client):193194 @app.route('/add', methods=['POST'])195 def add():196 json = flask.request.get_json()197 return text_type(json['a'] + json['b'])140 c = app.test_client()141 rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),142 content_type='application/json')198199 rv = client.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),200 content_type='application/json')201 assert rv.data == b'3'202145 def test_template_escaping(self):146 app = flask.Flask(__name__)203 def test_template_escaping(self, app, req_ctx):204 render = flask.render_template_string148 with app.test_request_context():149 rv = flask.json.htmlsafe_dumps('</script>')150 assert rv == u'"\\u003c/script\\u003e"'151 assert type(rv) == text_type152 rv = render('{{ "</script>"|tojson }}')153 assert rv == '"\\u003c/script\\u003e"'154 rv = render('{{ "<\0/script>"|tojson }}')155 assert rv == '"\\u003c\\u0000/script\\u003e"'156 rv = render('{{ "<!--<script>"|tojson }}')157 assert rv == '"\\u003c!--\\u003cscript\\u003e"'158 rv = render('{{ "&"|tojson }}')159 assert rv == '"\\u0026"'160 rv = render('{{ "\'"|tojson }}')161 assert rv == '"\\u0027"'162 rv = render("<a ng-data='{{ data|tojson }}'></a>",163 data={'x': ["foo", "bar", "baz'"]})164 assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'205 rv = flask.json.htmlsafe_dumps('</script>')206 assert rv == u'"\\u003c/script\\u003e"'207 assert type(rv) == text_type208 rv = render('{{ "</script>"|tojson }}')209 assert rv == '"\\u003c/script\\u003e"'210 rv = render('{{ "<\0/script>"|tojson }}')211 assert rv == '"\\u003c\\u0000/script\\u003e"'212 rv = render('{{ "<!--<script>"|tojson }}')213 assert rv == '"\\u003c!--\\u003cscript\\u003e"'214 rv = render('{{ "&"|tojson }}')215 assert rv == '"\\u0026"'216 rv = render('{{ "\'"|tojson }}')217 assert rv == '"\\u0027"'218 rv = render("<a ng-data='{{ data|tojson }}'></a>",219 data={'x': ["foo", "bar", "baz'"]})220 assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'221166 def test_json_customization(self):222 def test_json_customization(self, app, client):223 class X(object):224 def __init__(self, val):225 self.val = val226227 class MyEncoder(flask.json.JSONEncoder):228 def default(self, o):229 if isinstance(o, X):230 return '<%d>' % o.val231 return flask.json.JSONEncoder.default(self, o)232233 class MyDecoder(flask.json.JSONDecoder):234 def __init__(self, *args, **kwargs):235 kwargs.setdefault('object_hook', self.object_hook)236 flask.json.JSONDecoder.__init__(self, *args, **kwargs)237238 def object_hook(self, obj):239 if len(obj) == 1 and '_foo' in obj:240 return X(obj['_foo'])241 return obj183 app = flask.Flask(__name__)184 app.testing = True242243 app.json_encoder = MyEncoder244 app.json_decoder = MyDecoder245246 @app.route('/', methods=['POST'])247 def index():248 return flask.json.dumps(flask.request.get_json()['x'])190 c = app.test_client()191 rv = c.post('/', data=flask.json.dumps({249250 rv = client.post('/', data=flask.json.dumps({251 'x': {'_foo': 42}252 }), content_type='application/json')253 assert rv.data == b'"<42>"'254255 def test_blueprint_json_customization(self, app, client):256 class X(object):257 def __init__(self, val):258 self.val = val259260 class MyEncoder(flask.json.JSONEncoder):261 def default(self, o):262 if isinstance(o, X):263 return '<%d>' % o.val264265 return flask.json.JSONEncoder.default(self, o)266267 class MyDecoder(flask.json.JSONDecoder):268 def __init__(self, *args, **kwargs):269 kwargs.setdefault('object_hook', self.object_hook)270 flask.json.JSONDecoder.__init__(self, *args, **kwargs)271272 def object_hook(self, obj):273 if len(obj) == 1 and '_foo' in obj:274 return X(obj['_foo'])275276 return obj277278 bp = flask.Blueprint('bp', __name__)279 bp.json_encoder = MyEncoder280 bp.json_decoder = MyDecoder281282 @bp.route('/bp', methods=['POST'])283 def index():284 return flask.json.dumps(flask.request.get_json()['x'])285286 app.register_blueprint(bp)287288 rv = client.post('/bp', data=flask.json.dumps({289 'x': {'_foo': 42}290 }), content_type='application/json')291 assert rv.data == b'"<42>"'292196 def test_modified_url_encoding(self):293 def test_modified_url_encoding(self, app, client):294 class ModifiedRequest(flask.Request):295 url_charset = 'euc-kr'199 app = flask.Flask(__name__)200 app.testing = True296297 app.request_class = ModifiedRequest298 app.url_map.charset = 'euc-kr'299300 @app.route('/')301 def index():302 return flask.request.args['foo']303208 rv = app.test_client().get(u'/?foo=정상처리'.encode('euc-kr'))304 rv = client.get(u'/?foo=정상처리'.encode('euc-kr'))305 assert rv.status_code == 200306 assert rv.data == u'정상처리'.encode('utf-8')307308 if not has_encoding('euc-kr'):309 test_modified_url_encoding = None310215 def test_json_key_sorting(self):216 app = flask.Flask(__name__)217 app.testing = True311 def test_json_key_sorting(self, app, client):312 app.debug = True313314 assert app.config['JSON_SORT_KEYS'] == True315 d = dict.fromkeys(range(20), 'foo')316317 @app.route('/')318 def index():319 return flask.jsonify(values=d)320225 c = app.test_client()226 rv = c.get('/')321 rv = client.get('/')322 lines = [x.strip() for x in rv.data.strip().decode('utf-8').splitlines()]323 sorted_by_str = [324 '{',325 '"values": {',
51 unmodified lines
377 assert lines == sorted_by_int378 except AssertionError:379 assert lines == sorted_by_str380381382class TestSendfile(object):383 def test_send_file_regular(self, app, req_ctx):384 rv = flask.send_file('static/index.html')385 assert rv.direct_passthrough386 assert rv.mimetype == 'text/html'387 with app.open_resource('static/index.html') as f:388 rv.direct_passthrough = False389 assert rv.data == f.read()390 rv.close()391288 def test_send_file_regular(self):289 app = flask.Flask(__name__)290 with app.test_request_context():291 rv = flask.send_file('static/index.html')292 assert rv.direct_passthrough293 assert rv.mimetype == 'text/html'392 def test_send_file_xsendfile(self, app, req_ctx, catch_deprecation_warnings):393 app.use_x_sendfile = True394 rv = flask.send_file('static/index.html')395 assert rv.direct_passthrough396 assert 'x-sendfile' in rv.headers397 assert rv.headers['x-sendfile'] == \398 os.path.join(app.root_path, 'static/index.html')399 assert rv.mimetype == 'text/html'400 rv.close()401402 def test_send_file_last_modified(self, app, client):403 last_modified = datetime.datetime(1999, 1, 1)404405 @app.route('/')406 def index():407 return flask.send_file(StringIO("party like it's"),408 last_modified=last_modified,409 mimetype='text/plain')410411 rv = client.get('/')412 assert rv.last_modified == last_modified413414 def test_send_file_object_without_mimetype(self, app, req_ctx):415 with pytest.raises(ValueError) as excinfo:416 flask.send_file(StringIO("LOL"))417 assert 'Unable to infer MIME-type' in str(excinfo)418 assert 'no filename is available' in str(excinfo)419420 flask.send_file(StringIO("LOL"), attachment_filename='filename')421422 def test_send_file_object(self, app, req_ctx):423 with open(os.path.join(app.root_path, 'static/index.html'), mode='rb') as f:424 rv = flask.send_file(f, mimetype='text/html')425 rv.direct_passthrough = False426 with app.open_resource('static/index.html') as f:295 rv.direct_passthrough = False427 assert rv.data == f.read()428 assert rv.mimetype == 'text/html'429 rv.close()430299 def test_send_file_xsendfile(self):300 app = flask.Flask(__name__)431 app.use_x_sendfile = True302 with app.test_request_context():303 rv = flask.send_file('static/index.html')304 assert rv.direct_passthrough305 assert 'x-sendfile' in rv.headers306 assert rv.headers['x-sendfile'] == \307 os.path.join(app.root_path, 'static/index.html')432433 with open(os.path.join(app.root_path, 'static/index.html')) as f:434 rv = flask.send_file(f, mimetype='text/html')435 assert rv.mimetype == 'text/html'436 assert 'x-sendfile' not in rv.headers437 rv.close()438311 def test_send_file_object(self, catch_deprecation_warnings):312 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)317 rv.direct_passthrough = False318 with app.open_resource('static/index.html') as f:319 assert rv.data == f.read()320 assert rv.mimetype == 'text/html'321 rv.close()322 # mimetypes + etag323 assert len(captured) == 2439 app.use_x_sendfile = False440 f = StringIO('Test')441 rv = flask.send_file(f, mimetype='application/octet-stream')442 rv.direct_passthrough = False443 assert rv.data == b'Test'444 assert rv.mimetype == 'application/octet-stream'445 rv.close()446325 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)330 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')334 rv.close()335 # mimetypes + etag336 assert len(captured) == 2447 class PyStringIO(object):448 def __init__(self, *args, **kwargs):449 self._io = StringIO(*args, **kwargs)450338 app.use_x_sendfile = False339 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()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)451 def __getattr__(self, name):452 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) == 1453454 f = PyStringIO('Test')455 f.name = 'test.txt'456 rv = flask.send_file(f, attachment_filename=f.name)457 rv.direct_passthrough = False458 assert rv.data == b'Test'459 assert rv.mimetype == 'text/plain'460 rv.close()461462 f = StringIO('Test')463 rv = flask.send_file(f, mimetype='text/plain')464 rv.direct_passthrough = False465 assert rv.data == b'Test'466 assert rv.mimetype == 'text/plain'467 rv.close()468469 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) == 1470384 def test_attachment(self, catch_deprecation_warnings):385 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'])391 assert value == 'attachment'392 rv.close()393 # mimetypes + etag394 assert len(captured) == 2471 f = StringIO('Test')472 rv = flask.send_file(f, mimetype='text/html')473 assert 'x-sendfile' not in rv.headers474 rv.close()475396 with app.test_request_context():397 assert options['filename'] == 'index.html'398 rv = flask.send_file('static/index.html', as_attachment=True)399 value, options = parse_options_header(rv.headers['Content-Disposition'])476 @pytest.mark.skipif(477 not callable(getattr(Range, 'to_content_range_header', None)),478 reason="not implement within werkzeug"479 )480 def test_send_file_range_request(self, app, client):481 @app.route('/')482 def index():483 return flask.send_file('static/index.html', conditional=True)484485 rv = client.get('/', headers={'Range': 'bytes=4-15'})486 assert rv.status_code == 206487 with app.open_resource('static/index.html') as f:488 assert rv.data == f.read()[4:16]489 rv.close()490491 rv = client.get('/', headers={'Range': 'bytes=4-'})492 assert rv.status_code == 206493 with app.open_resource('static/index.html') as f:494 assert rv.data == f.read()[4:]495 rv.close()496497 rv = client.get('/', headers={'Range': 'bytes=4-1000'})498 assert rv.status_code == 206499 with app.open_resource('static/index.html') as f:500 assert rv.data == f.read()[4:]501 rv.close()502503 rv = client.get('/', headers={'Range': 'bytes=-10'})504 assert rv.status_code == 206505 with app.open_resource('static/index.html') as f:506 assert rv.data == f.read()[-10:]507 rv.close()508509 rv = client.get('/', headers={'Range': 'bytes=1000-'})510 assert rv.status_code == 416511 rv.close()512513 rv = client.get('/', headers={'Range': 'bytes=-'})514 assert rv.status_code == 416515 rv.close()516517 rv = client.get('/', headers={'Range': 'somethingsomething'})518 assert rv.status_code == 416519 rv.close()520521 last_modified = datetime.datetime.utcfromtimestamp(os.path.getmtime(522 os.path.join(app.root_path, 'static/index.html'))).replace(523 microsecond=0)524525 rv = client.get('/', headers={'Range': 'bytes=4-15',526 'If-Range': http_date(last_modified)})527 assert rv.status_code == 206528 rv.close()529530 rv = client.get('/', headers={'Range': 'bytes=4-15', 'If-Range': http_date(531 datetime.datetime(1999, 1, 1))})532 assert rv.status_code == 200533 rv.close()534535 def test_attachment(self, app, req_ctx):536537 with open(os.path.join(app.root_path, 'static/index.html')) as f:538 rv = flask.send_file(f, as_attachment=True,539 attachment_filename='index.html')540 value, options = \541 parse_options_header(rv.headers['Content-Disposition'])542 assert value == 'attachment'543 assert options['filename'] == 'index.html'544 assert 'filename*' not in rv.headers['Content-Disposition']545 rv.close()546404 with app.test_request_context():405 rv = flask.send_file(StringIO('Test'), as_attachment=True,406 attachment_filename='index.txt',407 add_etags=False)408 assert rv.mimetype == 'text/plain'409 value, options = parse_options_header(rv.headers['Content-Disposition'])410 assert value == 'attachment'411 assert options['filename'] == 'index.txt'412 rv.close()547 rv = flask.send_file('static/index.html', as_attachment=True)548 value, options = parse_options_header(rv.headers['Content-Disposition'])549 assert value == 'attachment'550 assert options['filename'] == 'index.html'551 rv.close()552414 def test_static_file(self):415 app = flask.Flask(__name__)553 rv = flask.send_file(StringIO('Test'), as_attachment=True,554 attachment_filename='index.txt',555 add_etags=False)556 assert rv.mimetype == 'text/plain'557 value, options = parse_options_header(rv.headers['Content-Disposition'])558 assert value == 'attachment'559 assert options['filename'] == 'index.txt'560 rv.close()561562 def test_attachment_with_utf8_filename(self, app, req_ctx):563 rv = flask.send_file('static/index.html', as_attachment=True, attachment_filename=u'Ñandú/pingüino.txt')564 content_disposition = set(rv.headers['Content-Disposition'].split('; '))565 assert content_disposition == set((566 'attachment',567 'filename="Nandu/pinguino.txt"',568 "filename*=UTF-8''%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt"569 ))570 rv.close()571572 def test_static_file(self, app, req_ctx):573 # default cache timeout is 12 hours417 with app.test_request_context():418 # Test with static file handler.419 rv = app.send_static_file('index.html')420 cc = parse_cache_control_header(rv.headers['Cache-Control'])421 assert cc.max_age == 12 * 60 * 60422 rv.close()423 # Test again with direct use of send_file utility.424 rv = flask.send_file('static/index.html')425 cc = parse_cache_control_header(rv.headers['Cache-Control'])426 assert cc.max_age == 12 * 60 * 60427 rv.close()574575 # Test with static file handler.576 rv = app.send_static_file('index.html')577 cc = parse_cache_control_header(rv.headers['Cache-Control'])578 assert cc.max_age == 12 * 60 * 60579 rv.close()580 # Test again with direct use of send_file utility.581 rv = flask.send_file('static/index.html')582 cc = parse_cache_control_header(rv.headers['Cache-Control'])583 assert cc.max_age == 12 * 60 * 60584 rv.close()585 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600429 with app.test_request_context():430 # Test with static file handler.431 rv = app.send_static_file('index.html')432 cc = parse_cache_control_header(rv.headers['Cache-Control'])433 assert cc.max_age == 3600434 rv.close()435 # Test again with direct use of send_file utility.436 rv = flask.send_file('static/index.html')437 cc = parse_cache_control_header(rv.headers['Cache-Control'])438 assert cc.max_age == 3600439 rv.close()586587 # Test with static file handler.588 rv = app.send_static_file('index.html')589 cc = parse_cache_control_header(rv.headers['Cache-Control'])590 assert cc.max_age == 3600591 rv.close()592 # Test again with direct use of send_file utility.593 rv = flask.send_file('static/index.html')594 cc = parse_cache_control_header(rv.headers['Cache-Control'])595 assert cc.max_age == 3600596 rv.close()597598 class StaticFileApp(flask.Flask):599 def get_send_file_max_age(self, filename):600 return 10601602 app = StaticFileApp(__name__)603 with app.test_request_context():604 # Test with static file handler.605 rv = app.send_static_file('index.html')
5 unmodified lines
611 cc = parse_cache_control_header(rv.headers['Cache-Control'])612 assert cc.max_age == 10613 rv.close()614456 def test_send_from_directory(self):457 app = flask.Flask(__name__)458 app.testing = True615 def test_send_from_directory(self, app, req_ctx):616 app.root_path = os.path.join(os.path.dirname(__file__),617 'test_apps', 'subdomaintestmodule')461 with app.test_request_context():462 rv = flask.send_from_directory('static', 'hello.txt')463 rv.direct_passthrough = False464 assert rv.data.strip() == b'Hello Subdomain'465 rv.close()618 rv = flask.send_from_directory('static', 'hello.txt')619 rv.direct_passthrough = False620 assert rv.data.strip() == b'Hello Subdomain'621 rv.close()622623 def test_send_from_directory_bad_request(self, app, req_ctx):624 app.root_path = os.path.join(os.path.dirname(__file__),625 'test_apps', 'subdomaintestmodule')626468class TestLogging(object):627 with pytest.raises(BadRequest):628 flask.send_from_directory('static', 'bad\x00')629630631class TestLogging(object):632 def test_logger_cache(self):633 app = flask.Flask(__name__)634 logger1 = app.logger635 assert app.logger is logger1636 assert logger1.name == __name__637 app.logger_name = __name__ + '/test_logger_cache'638 assert app.logger is not logger1639478 def test_debug_log(self, capsys):479 app = flask.Flask(__name__)640 def test_debug_log(self, capsys, app, client):641 app.debug = True642643 @app.route('/')644 def index():
4 unmodified lines
649 @app.route('/exc')650 def exc():651 1 // 0652492 with app.test_client() as c:493 c.get('/')653 with client:654 client.get('/')655 out, err = capsys.readouterr()656 assert 'WARNING in test_helpers [' in err657 assert os.path.basename(__file__.rsplit('.', 1)[0] + '.py') in err658 assert 'the standard library is dead' in err659 assert 'this is a debug statement' in err660661 with pytest.raises(ZeroDivisionError):501 c.get('/exc')662 client.get('/exc')663503 def test_debug_log_override(self):504 app = flask.Flask(__name__)664 def test_debug_log_override(self, app):665 app.debug = True666 app.logger_name = 'flask_tests/test_debug_log_override'667 app.logger.level = 10668 assert app.logger.level == 10669510 def test_exception_logging(self):670 def test_exception_logging(self, app, client):671 out = StringIO()512 app = flask.Flask(__name__)672 app.config['LOGGER_HANDLER_POLICY'] = 'never'673 app.logger_name = 'flask_tests/test_exception_logging'674 app.logger.addHandler(StreamHandler(out))675 app.testing = False676677 @app.route('/')678 def index():679 1 // 0680521 rv = app.test_client().get('/')681 rv = client.get('/')682 assert rv.status_code == 500683 assert b'Internal Server Error' in rv.data684685 err = out.getvalue()
1 unmodified line
687 assert 'Traceback (most recent call last):' in err688 assert '1 // 0' in err689 assert 'ZeroDivisionError:' in err690531 def test_processor_exceptions(self):532 app = flask.Flask(__name__)691 def test_processor_exceptions(self, app, client):692 app.config['LOGGER_HANDLER_POLICY'] = 'never'693 app.testing = False694695 @app.before_request696 def before_request():697 if trigger == 'before':698 1 // 0699700 @app.after_request701 def after_request(response):702 if trigger == 'after':703 1 // 0704 return response705706 @app.route('/')707 def index():708 return 'Foo'709710 @app.errorhandler(500)711 def internal_server_error(e):712 return 'Hello Server Error', 500713714 for trigger in 'before', 'after':550 rv = app.test_client().get('/')715 rv = client.get('/')716 assert rv.status_code == 500717 assert rv.data == b'Hello Server Error'718554 def test_url_for_with_anchor(self):555 app = flask.Flask(__name__)719 def test_url_for_with_anchor(self, app, req_ctx):720721 @app.route('/')722 def index():723 return '42'559 with app.test_request_context():560 assert flask.url_for('index', _anchor='x y') == '/#x%20y'724562 def test_url_for_with_scheme(self):563 app = flask.Flask(__name__)725 assert flask.url_for('index', _anchor='x y') == '/#x%20y'726727 def test_url_for_with_scheme(self, app, req_ctx):728729 @app.route('/')730 def index():731 return '42'567 with app.test_request_context():568 assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'732570 def test_url_for_with_scheme_not_external(self):571 app = flask.Flask(__name__)733 assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'734735 def test_url_for_with_scheme_not_external(self, app, req_ctx):736737 @app.route('/')738 def index():739 return '42'575 with app.test_request_context():576 pytest.raises(ValueError,577 flask.url_for,578 'index',579 _scheme='https')740741 pytest.raises(ValueError,742 flask.url_for,743 'index',744 _scheme='https')745746 def test_url_for_with_alternating_schemes(self, app, req_ctx):747748 @app.route('/')749 def index():750 return '42'751752 assert flask.url_for('index', _external=True) == 'http://localhost/'753 assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'754 assert flask.url_for('index', _external=True) == 'http://localhost/'755581 def test_url_with_method(self):756 def test_url_with_method(self, app, req_ctx):757 from flask.views import MethodView583 app = flask.Flask(__name__)758759 class MyView(MethodView):760 def get(self, id=None):761 if id is None:762 return 'List'763 return 'Get %d' % id764765 def post(self):766 return 'Create'767768 myview = MyView.as_view('myview')769 app.add_url_rule('/myview/', methods=['GET'],770 view_func=myview)771 app.add_url_rule('/myview/<int:id>', methods=['GET'],772 view_func=myview)773 app.add_url_rule('/myview/create', methods=['POST'],774 view_func=myview)775599 with app.test_request_context():600 assert flask.url_for('myview', _method='GET') == '/myview/'601 assert flask.url_for('myview', id=42, _method='GET') == '/myview/42'602 assert flask.url_for('myview', _method='POST') == '/myview/create'776 assert flask.url_for('myview', _method='GET') == '/myview/'777 assert flask.url_for('myview', id=42, _method='GET') == '/myview/42'778 assert flask.url_for('myview', _method='POST') == '/myview/create'779780781class TestNoImports(object):782 """Test Flasks are created without import.
14 unmodified lines
797 assert False, 'Flask(import_name) is importing import_name.'798799800class TestStreaming(object):801 def test_streaming_with_context(self, app, client):802626 def test_streaming_with_context(self):627 app = flask.Flask(__name__)628 app.testing = True803 @app.route('/')804 def index():805 def generate():806 yield 'Hello '807 yield flask.request.args['name']808 yield '!'809810 return flask.Response(flask.stream_with_context(generate()))636 c = app.test_client()637 rv = c.get('/?name=World')811812 rv = client.get('/?name=World')813 assert rv.data == b'Hello World!'814640 def test_streaming_with_context_as_decorator(self):641 app = flask.Flask(__name__)642 app.testing = True815 def test_streaming_with_context_as_decorator(self, app, client):816817 @app.route('/')818 def index():819 @flask.stream_with_context646 def generate():647 yield 'Hello '820 def generate(hello):821 yield hello822 yield flask.request.args['name']823 yield '!'824650 return flask.Response(generate())651 c = app.test_client()652 rv = c.get('/?name=World')825 return flask.Response(generate('Hello '))826827 rv = client.get('/?name=World')828 assert rv.data == b'Hello World!'829655 def test_streaming_with_context_and_custom_close(self):656 app = flask.Flask(__name__)657 app.testing = True830 def test_streaming_with_context_and_custom_close(self, app, client):831 called = []832833 class Wrapper(object):834 def __init__(self, gen):835 self._gen = gen836837 def __iter__(self):838 return self839840 def close(self):841 called.append(42)842843 def __next__(self):844 return next(self._gen)845846 next = __next__847848 @app.route('/')849 def index():850 def generate():851 yield 'Hello '852 yield flask.request.args['name']853 yield '!'854855 return flask.Response(flask.stream_with_context(856 Wrapper(generate())))677 c = app.test_client()678 rv = c.get('/?name=World')857858 rv = client.get('/?name=World')859 assert rv.data == b'Hello World!'860 assert called == [42]861862863class TestSafeJoin(object):864 def test_safe_join(self):865 # Valid combinations of *args and expected joined paths.866 passing = (867 (('a/b/c',), 'a/b/c'),868 (('/', 'a/', 'b/', 'c/'), '/a/b/c'),869 (('a', 'b', 'c'), 'a/b/c'),870 (('/a', 'b/c'), '/a/b/c'),871 (('a/b', 'X/../c'), 'a/b/c'),872 (('/a/b', 'c/X/..'), '/a/b/c'),873 # If last path is '' add a slash874 (('/a/b/c', ''), '/a/b/c/'),875 # Preserve dot slash876 (('/a/b/c', './'), '/a/b/c/.'),877 (('a/b/c', 'X/..'), 'a/b/c/.'),878 # Base directory is always considered safe879 (('../', 'a/b/c'), '../a/b/c'),880 (('/..',), '/..'),881 )882883 for args, expected in passing:884 assert flask.safe_join(*args) == expected885886 def test_safe_join_exceptions(self):887 # Should raise werkzeug.exceptions.NotFound on unsafe joins.888 failing = (889 # path.isabs and ``..'' checks890 ('/a', 'b', '/c'),891 ('/a', '../b/c'),892 ('/a', '..', 'b/c'),893 # Boundaries violations after path normalization894 ('/a', 'b/../b/../../c'),895 ('/a', 'b', 'c/../..'),896 ('/a', 'b/../../c'),897 )898899 for args in failing:900 with pytest.raises(NotFound):901 print(flask.safe_join(*args))902903class TestHelpers(object):904905 @pytest.mark.parametrize('debug, expected_flag, expected_default_flag', [906 ('', None, True),907 ('0', False, False),908 ('False', False, False),909 ('No', False, False),910 ('True', True, True)911 ])912 def test_get_debug_flag(self, monkeypatch, debug, expected_flag, expected_default_flag):913 monkeypatch.setenv('FLASK_DEBUG', debug)914 if expected_flag is None:915 assert get_debug_flag() is None916 else:917 assert get_debug_flag() == expected_flag918 assert get_debug_flag(default=True) == expected_default_flag919920 def test_make_response(self):921 app = flask.Flask(__name__)922 with app.test_request_context():923 rv = flask.helpers.make_response()924 assert rv.status_code == 200925 assert rv.mimetype == 'text/html'926927 rv = flask.helpers.make_response('Hello')928 assert rv.status_code == 200929 assert rv.data == b'Hello'930 assert rv.mimetype == 'text/html'
modified:tests/test_regression.py+5 added-9 removed
7 unmodified lines
8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1314import os12import gc13import sys17import flask14import threading1516import pytest17from werkzeug.exceptions import NotFound1819import flask2021_gc_lock = threading.Lock()2223
13 unmodified lines
37 gc.collect()38 self.old_objects = len(gc.get_objects())3940 def __exit__(self, exc_type, exc_value, tb):42 if not hasattr(sys, 'getrefcount'):43 gc.collect()41 gc.collect()42 new_objects = len(gc.get_objects())43 if new_objects > self.old_objects:44 pytest.fail('Example code leaked')45 _gc_lock.release()
29 unmodified lines
75 with pytest.raises(NotFound):76 safe_join('/foo', '..')777881def test_aborting():79def test_aborting(app):80 class Foo(Exception):81 whatever = 4284 app = flask.Flask(__name__)85 app.testing = True8283 @app.errorhandler(Foo)84 def handle_foo(e):85 return str(e.whatever)
14 unmodified lines
modified:tests/test_reqctx.py+86 added-58 removed
10 unmodified lines
1112import pytest1314import flask15from flask.sessions import SessionInterface1617try:18 from greenlet import greenlet19except ImportError:20 greenlet = None212222def test_teardown_on_pop():23def test_teardown_on_pop(app):24 buffer = []24 app = flask.Flask(__name__)2526 @app.teardown_request27 def end_of_request(exception):28 buffer.append(exception)29
2 unmodified lines
32 assert buffer == []33 ctx.pop()34 assert buffer == [None]353635def test_teardown_with_previous_exception():37def test_teardown_with_previous_exception(app):38 buffer = []37 app = flask.Flask(__name__)3940 @app.teardown_request41 def end_of_request(exception):42 buffer.append(exception)43
5 unmodified lines
49 with app.test_request_context():50 assert buffer == []51 assert buffer == [None]525351def test_teardown_with_handled_exception():54def test_teardown_with_handled_exception(app):55 buffer = []53 app = flask.Flask(__name__)5657 @app.teardown_request58 def end_of_request(exception):59 buffer.append(exception)60
4 unmodified lines
65 except Exception:66 pass67 assert buffer == [None]6866def test_proper_test_request_context():67 app = flask.Flask(__name__)6970def test_proper_test_request_context(app):71 app.config.update(72 SERVER_NAME='localhost.localdomain:5000'73 )74
6 unmodified lines
81 return None8283 with app.test_request_context('/'):84 assert flask.url_for('index', _external=True) == \82 'http://localhost.localdomain:5000/'85 'http://localhost.localdomain:5000/'8687 with app.test_request_context('/'):88 assert flask.url_for('sub', _external=True) == \86 'http://foo.localhost.localdomain:5000/'89 'http://foo.localhost.localdomain:5000/'9091 try:92 with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}):93 pass
11 unmodified lines
105 app.config.update(SERVER_NAME='localhost:80')106 with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}):107 pass108106def test_context_binding():107 app = flask.Flask(__name__)109110def test_context_binding(app):111 @app.route('/')112 def index():113 return 'Hello %s!' % flask.request.args['name']114115 @app.route('/meh')116 def meh():117 return flask.request.url118
2 unmodified lines
121 with app.test_request_context('/meh'):122 assert meh() == 'http://localhost/meh'123 assert flask._request_ctx_stack.top is None124121def test_context_test():122 app = flask.Flask(__name__)125126def test_context_test(app):127 assert not flask.request128 assert not flask.has_request_context()129 ctx = app.test_request_context()130 ctx.push()
2 unmodified lines
133 assert flask.has_request_context()134 finally:135 ctx.pop()136133def test_manual_context_binding():134 app = flask.Flask(__name__)137138def test_manual_context_binding(app):139 @app.route('/')140 def index():141 return 'Hello %s!' % flask.request.args['name']142143 ctx = app.test_request_context('/?name=World')144 ctx.push()145 assert index() == 'Hello World!'146 ctx.pop()143 try:147 with pytest.raises(RuntimeError):148 index()145 except RuntimeError:146 pass147 else:148 assert 0, 'expected runtime error'149150151@pytest.mark.skipif(greenlet is None, reason='greenlet not installed')151def test_greenlet_context_copying():152 app = flask.Flask(__name__)153 greenlets = []152class TestGreenletContextCopying(object):153154 def test_greenlet_context_copying(self, app, client):155 greenlets = []156157 @app.route('/')155 @app.route('/')156 def index():157 reqctx = flask._request_ctx_stack.top.copy()158 def g():159 assert not flask.request160 assert not flask.current_app161 with reqctx:158 def index():159 reqctx = flask._request_ctx_stack.top.copy()160161 def g():162 assert not flask.request163 assert not flask.current_app164 with reqctx:165 assert flask.request166 assert flask.current_app == app167 assert flask.request.path == '/'168 assert flask.request.args['foo'] == 'bar'169 assert not flask.request170 return 42171172 greenlets.append(greenlet(g))173 return 'Hello World!'174175 rv = client.get('/?foo=bar')176 assert rv.data == b'Hello World!'177178 result = greenlets[0].run()179 assert result == 42180181 def test_greenlet_context_copying_api(self, app, client):182 greenlets = []183184 @app.route('/')185 def index():186 reqctx = flask._request_ctx_stack.top.copy()187188 @flask.copy_current_request_context189 def g():190 assert flask.request191 assert flask.current_app == app192 assert flask.request.path == '/'193 assert flask.request.args['foo'] == 'bar'166 assert not flask.request167 return 42194 return 42168 greenlets.append(greenlet(g))169 return 'Hello World!'195171 rv = app.test_client().get('/?foo=bar')172 assert rv.data == b'Hello World!'196 greenlets.append(greenlet(g))197 return 'Hello World!'198174 result = greenlets[0].run()175 assert result == 42199 rv = client.get('/?foo=bar')200 assert rv.data == b'Hello World!'201177@pytest.mark.skipif(greenlet is None, reason='greenlet not installed')178def test_greenlet_context_copying_api():179 app = flask.Flask(__name__)180 greenlets = []202 result = greenlets[0].run()203 assert result == 42204205206def test_session_error_pops_context():207 class SessionError(Exception):208 pass209210 class FailingSessionInterface(SessionInterface):211 def open_session(self, app, request):212 raise SessionError()213214 class CustomFlask(flask.Flask):215 session_interface = FailingSessionInterface()216217 app = CustomFlask(__name__)218219 @app.route('/')220 def index():184 reqctx = flask._request_ctx_stack.top.copy()185 @flask.copy_current_request_context186 def g():187 assert flask.request188 assert flask.current_app == app189 assert flask.request.path == '/'190 assert flask.request.args['foo'] == 'bar'191 return 42192 greenlets.append(greenlet(g))193 return 'Hello World!'221 # shouldn't get here222 assert False223195 rv = app.test_client().get('/?foo=bar')196 assert rv.data == b'Hello World!'197198 result = greenlets[0].run()199 assert result == 42224 response = app.test_client().get('/')225 assert response.status_code == 500226 assert not flask.request227 assert not flask.current_app
modified:tests/test_signals.py+32 added-4 removed
16 unmodified lines
17 blinker = None1819import flask202121pytestmark = pytest.mark.skipif(22 blinker is None,23 reason='Signals require the blinker library.'24)2527def test_template_rendered():28 app = flask.Flask(__name__)2627def test_template_rendered(app, client):28 @app.route('/')29 def index():30 return flask.render_template('simple_template.html', whiskey=42)31
3 unmodified lines
35 recorded.append((template, context))3637 flask.template_rendered.connect(record, app)38 try:41 app.test_client().get('/')39 client.get('/')40 assert len(recorded) == 141 template, context = recorded[0]42 assert template.name == 'simple_template.html'43 assert context['whiskey'] == 4244 finally:45 flask.template_rendered.disconnect(record, app)464748def test_before_render_template():49 app = flask.Flask(__name__)5051 @app.route('/')52 def index():53 return flask.render_template('simple_template.html', whiskey=42)5455 recorded = []5657 def record(sender, template, context):58 context['whiskey'] = 4359 recorded.append((template, context))6061 flask.before_render_template.connect(record, app)62 try:63 rv = app.test_client().get('/')64 assert len(recorded) == 165 template, context = recorded[0]66 assert template.name == 'simple_template.html'67 assert context['whiskey'] == 4368 assert rv.data == b'<h1>43</h1>'69 finally:70 flask.before_render_template.disconnect(record, app)717273def test_request_signals():74 app = flask.Flask(__name__)75 calls = []76
31 unmodified lines
108 finally:109 flask.request_started.disconnect(before_request_signal, app)110 flask.request_finished.disconnect(after_request_signal, app)111112113def test_request_exception_signal():114 app = flask.Flask(__name__)115 recorded = []116
11 unmodified lines
128 assert isinstance(recorded[0], ZeroDivisionError)129 finally:130 flask.got_request_exception.disconnect(record, app)131132133def test_appcontext_signals():134 app = flask.Flask(__name__)135 recorded = []136
18 unmodified lines
155 finally:156 flask.appcontext_pushed.disconnect(record_push, app)157 flask.appcontext_popped.disconnect(record_pop, app)158159160def test_flash_signal():161 app = flask.Flask(__name__)162 app.config['SECRET_KEY'] = 'secret'163
18 unmodified lines
182 assert category == 'notice'183 finally:184 flask.message_flashed.disconnect(record, app)185186187def test_appcontext_tearing_down_signal():188 app = flask.Flask(__name__)189 recorded = []190
16 unmodified lines
modified:tests/test_templating.py+145 added-84 removed
14 unmodified lines
15import logging16from jinja2 import TemplateNotFound171819def test_context_processing():20 app = flask.Flask(__name__)19def test_context_processing(app, client):20 @app.context_processor21 def context_processor():22 return {'injected_value': 42}2324 @app.route('/')25 def index():26 return flask.render_template('context_template.html', value=23)27 rv = app.test_client().get('/')2728 rv = client.get('/')29 assert rv.data == b'<p>23|42'3030def test_original_win():31 app = flask.Flask(__name__)3132def test_original_win(app, client):33 @app.route('/')34 def index():35 return flask.render_template_string('{{ config }}', config=42)35 rv = app.test_client().get('/')3637 rv = client.get('/')38 assert rv.data == b'42'3938def test_request_less_rendering():39 app = flask.Flask(__name__)4041def test_request_less_rendering(app, app_ctx):42 app.config['WORLD_NAME'] = 'Special World'4344 @app.context_processor45 def context_processor():46 return dict(foo=42)4745 with app.app_context():46 rv = flask.render_template_string('Hello {{ config.WORLD_NAME }} '47 '{{ foo }}')48 assert rv == 'Hello Special World 42'48 rv = flask.render_template_string('Hello {{ config.WORLD_NAME }} '49 '{{ foo }}')50 assert rv == 'Hello Special World 42'5150def test_standard_context():51 app = flask.Flask(__name__)5253def test_standard_context(app, client):54 app.secret_key = 'development key'5556 @app.route('/')57 def index():58 flask.g.foo = 2359 flask.session['test'] = 'aha'
2 unmodified lines
62 {{ g.foo }}63 {{ config.DEBUG }}64 {{ session.test }}65 ''')6663 rv = app.test_client().get('/?foo=42')67 rv = client.get('/?foo=42')68 assert rv.data.split() == [b'42', b'23', b'False', b'aha']697066def test_escaping():71def test_escaping(app, client):72 text = '<p>Hello World!'68 app = flask.Flask(__name__)7374 @app.route('/')75 def index():76 return flask.render_template('escaping_template.html', text=text,77 html=flask.Markup(text))7873 lines = app.test_client().get('/').data.splitlines()79 lines = client.get('/').data.splitlines()80 assert lines == [81 b'&lt;p&gt;Hello World!',82 b'<p>Hello World!',83 b'<p>Hello World!',
1 unmodified line
85 b'&lt;p&gt;Hello World!',86 b'<p>Hello World!'87 ]8883def test_no_escaping():84 app = flask.Flask(__name__)85 with app.test_request_context():86 assert flask.render_template_string(87 '{{ foo }}', foo='<test>') == '<test>'88 assert flask.render_template('mail.txt', foo='<test>') == \89 '<test> Mail'8991def test_macros():92 app = flask.Flask(__name__)93 with app.test_request_context():94 macro = flask.get_template_attribute('_macro.html', 'hello')95 assert macro('World') == 'Hello World!'90def test_no_escaping(app, client):91 text = '<p>Hello World!'9297def test_template_filter():98 app = flask.Flask(__name__)93 @app.route('/')94 def index():95 return flask.render_template('non_escaping_template.txt', text=text,96 html=flask.Markup(text))9798 lines = client.get('/').data.splitlines()99 assert lines == [100 b'<p>Hello World!',101 b'<p>Hello World!',102 b'<p>Hello World!',103 b'<p>Hello World!',104 b'&lt;p&gt;Hello World!',105 b'<p>Hello World!',106 b'<p>Hello World!',107 b'<p>Hello World!'108 ]109110111def test_escaping_without_template_filename(app, client, req_ctx):112 assert flask.render_template_string(113 '{{ foo }}', foo='<test>') == '&lt;test&gt;'114 assert flask.render_template('mail.txt', foo='<test>') == '<test> Mail'115116117def test_macros(app, req_ctx):118 macro = flask.get_template_attribute('_macro.html', 'hello')119 assert macro('World') == 'Hello World!'120121122def test_template_filter(app):123 @app.template_filter()124 def my_reverse(s):125 return s[::-1]126127 assert 'my_reverse' in app.jinja_env.filters.keys()128 assert app.jinja_env.filters['my_reverse'] == my_reverse129 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'130106def test_add_template_filter():107 app = flask.Flask(__name__)131132def test_add_template_filter(app):133 def my_reverse(s):134 return s[::-1]135136 app.add_template_filter(my_reverse)137 assert 'my_reverse' in app.jinja_env.filters.keys()138 assert app.jinja_env.filters['my_reverse'] == my_reverse139 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'140115def test_template_filter_with_name():116 app = flask.Flask(__name__)141142def test_template_filter_with_name(app):143 @app.template_filter('strrev')144 def my_reverse(s):145 return s[::-1]146147 assert 'strrev' in app.jinja_env.filters.keys()148 assert app.jinja_env.filters['strrev'] == my_reverse149 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'150124def test_add_template_filter_with_name():125 app = flask.Flask(__name__)151152def test_add_template_filter_with_name(app):153 def my_reverse(s):154 return s[::-1]155156 app.add_template_filter(my_reverse, 'strrev')157 assert 'strrev' in app.jinja_env.filters.keys()158 assert app.jinja_env.filters['strrev'] == my_reverse159 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'160133def test_template_filter_with_template():134 app = flask.Flask(__name__)161162def test_template_filter_with_template(app, client):163 @app.template_filter()164 def super_reverse(s):165 return s[::-1]166167 @app.route('/')168 def index():169 return flask.render_template('template_filter.html', value='abcd')141 rv = app.test_client().get('/')170171 rv = client.get('/')172 assert rv.data == b'dcba'173144def test_add_template_filter_with_template():145 app = flask.Flask(__name__)174175def test_add_template_filter_with_template(app, client):176 def super_reverse(s):177 return s[::-1]178179 app.add_template_filter(super_reverse)180181 @app.route('/')182 def index():183 return flask.render_template('template_filter.html', value='abcd')152 rv = app.test_client().get('/')184185 rv = client.get('/')186 assert rv.data == b'dcba'187155def test_template_filter_with_name_and_template():156 app = flask.Flask(__name__)188189def test_template_filter_with_name_and_template(app, client):190 @app.template_filter('super_reverse')191 def my_reverse(s):192 return s[::-1]193194 @app.route('/')195 def index():196 return flask.render_template('template_filter.html', value='abcd')163 rv = app.test_client().get('/')197198 rv = client.get('/')199 assert rv.data == b'dcba'200166def test_add_template_filter_with_name_and_template():167 app = flask.Flask(__name__)201202def test_add_template_filter_with_name_and_template(app, client):203 def my_reverse(s):204 return s[::-1]205206 app.add_template_filter(my_reverse, 'super_reverse')207208 @app.route('/')209 def index():210 return flask.render_template('template_filter.html', value='abcd')174 rv = app.test_client().get('/')211212 rv = client.get('/')213 assert rv.data == b'dcba'214177def test_template_test():178 app = flask.Flask(__name__)215216def test_template_test(app):217 @app.template_test()218 def boolean(value):219 return isinstance(value, bool)220221 assert 'boolean' in app.jinja_env.tests.keys()222 assert app.jinja_env.tests['boolean'] == boolean223 assert app.jinja_env.tests['boolean'](False)224186def test_add_template_test():187 app = flask.Flask(__name__)225226def test_add_template_test(app):227 def boolean(value):228 return isinstance(value, bool)229230 app.add_template_test(boolean)231 assert 'boolean' in app.jinja_env.tests.keys()232 assert app.jinja_env.tests['boolean'] == boolean233 assert app.jinja_env.tests['boolean'](False)234195def test_template_test_with_name():196 app = flask.Flask(__name__)235236def test_template_test_with_name(app):237 @app.template_test('boolean')238 def is_boolean(value):239 return isinstance(value, bool)240241 assert 'boolean' in app.jinja_env.tests.keys()242 assert app.jinja_env.tests['boolean'] == is_boolean243 assert app.jinja_env.tests['boolean'](False)244204def test_add_template_test_with_name():205 app = flask.Flask(__name__)245246def test_add_template_test_with_name(app):247 def is_boolean(value):248 return isinstance(value, bool)249250 app.add_template_test(is_boolean, 'boolean')251 assert 'boolean' in app.jinja_env.tests.keys()252 assert app.jinja_env.tests['boolean'] == is_boolean253 assert app.jinja_env.tests['boolean'](False)254213def test_template_test_with_template():214 app = flask.Flask(__name__)255256def test_template_test_with_template(app, client):257 @app.template_test()258 def boolean(value):259 return isinstance(value, bool)260261 @app.route('/')262 def index():263 return flask.render_template('template_test.html', value=False)221 rv = app.test_client().get('/')264265 rv = client.get('/')266 assert b'Success!' in rv.data267224def test_add_template_test_with_template():225 app = flask.Flask(__name__)268269def test_add_template_test_with_template(app, client):270 def boolean(value):271 return isinstance(value, bool)272273 app.add_template_test(boolean)274275 @app.route('/')276 def index():277 return flask.render_template('template_test.html', value=False)232 rv = app.test_client().get('/')278279 rv = client.get('/')280 assert b'Success!' in rv.data281235def test_template_test_with_name_and_template():236 app = flask.Flask(__name__)282283def test_template_test_with_name_and_template(app, client):284 @app.template_test('boolean')285 def is_boolean(value):286 return isinstance(value, bool)287288 @app.route('/')289 def index():290 return flask.render_template('template_test.html', value=False)243 rv = app.test_client().get('/')291292 rv = client.get('/')293 assert b'Success!' in rv.data294246def test_add_template_test_with_name_and_template():247 app = flask.Flask(__name__)295296def test_add_template_test_with_name_and_template(app, client):297 def is_boolean(value):298 return isinstance(value, bool)299300 app.add_template_test(is_boolean, 'boolean')301302 @app.route('/')303 def index():304 return flask.render_template('template_test.html', value=False)254 rv = app.test_client().get('/')305306 rv = client.get('/')307 assert b'Success!' in rv.data308257def test_add_template_global():258 app = flask.Flask(__name__)309310def test_add_template_global(app, app_ctx):311 @app.template_global()312 def get_stuff():313 return 42314315 assert 'get_stuff' in app.jinja_env.globals.keys()316 assert app.jinja_env.globals['get_stuff'] == get_stuff317 assert app.jinja_env.globals['get_stuff'](), 42265 with app.app_context():266 rv = flask.render_template_string('{{ get_stuff() }}')267 assert rv == '42'318319 rv = flask.render_template_string('{{ get_stuff() }}')320 assert rv == '42'321322269def test_custom_template_loader():323def test_custom_template_loader(client):324 class MyFlask(flask.Flask):325 def create_global_jinja_loader(self):326 from jinja2 import DictLoader327 return DictLoader({'index.html': 'Hello Custom World!'})328329 app = MyFlask(__name__)330331 @app.route('/')332 def index():333 return flask.render_template('index.html')334335 c = app.test_client()336 rv = c.get('/')337 assert rv.data == b'Hello Custom World!'338282def test_iterable_loader():283 app = flask.Flask(__name__)339340def test_iterable_loader(app, client):341 @app.context_processor342 def context_processor():343 return {'whiskey': 'Jameson'}344345 @app.route('/')346 def index():347 return flask.render_template(348 ['no_template.xml', # should skip this one291 'simple_template.html', # should render this292 'context_template.html'],349 'simple_template.html', # should render this350 'context_template.html'],351 value=23)352295 rv = app.test_client().get('/')353 rv = client.get('/')354 assert rv.data == b'<h1>Jameson</h1>'355356298def test_templates_auto_reload():357def test_templates_auto_reload(app):358 # debug is False, config option is None300 app = flask.Flask(__name__)359 assert app.debug is False360 assert app.config['TEMPLATES_AUTO_RELOAD'] is None361 assert app.jinja_env.auto_reload is False362 # debug is False, config option is False
21 unmodified lines
384 app.config['DEBUG'] = True385 app.config['TEMPLATES_AUTO_RELOAD'] = True386 assert app.jinja_env.auto_reload is True387388389def test_template_loader_debugging(test_apps):390 from blueprintapp import app391392 called = []393394 class _TestHandler(logging.Handler):395 def handle(x, record):396 called.append(True)397 text = str(record.msg)
23 unmodified lines
421 app.config['EXPLAIN_TEMPLATE_LOADING'] = old_load_setting422423 assert len(called) == 1424425426def test_custom_jinja_env():427 class CustomEnvironment(flask.templating.Environment):428 pass429430 class CustomFlask(flask.Flask):370 jinja_env_class = CustomEnvironment431 jinja_environment = CustomEnvironment432433 app = CustomFlask(__name__)434 assert isinstance(app.jinja_env, CustomEnvironment)
modified:tests/test_testing.py+101 added-78 removed
9 unmodified lines
10"""11import pytest1213import flask14import werkzeug1516from flask._compat import text_type171818def test_environ_defaults_from_config():19 app = flask.Flask(__name__)20 app.testing = True19def test_environ_defaults_from_config(app, client):20 app.config['SERVER_NAME'] = 'example.com:1234'21 app.config['APPLICATION_ROOT'] = '/foo'2223 @app.route('/')24 def index():25 return flask.request.url2627 ctx = app.test_request_context()28 assert ctx.request.url == 'http://example.com:1234/foo/'29 with app.test_client() as c:30 rv = c.get('/')31 assert rv.data == b'http://example.com:1234/foo/'2933def test_environ_defaults():34 app = flask.Flask(__name__)35 app.testing = True30 rv = client.get('/')31 assert rv.data == b'http://example.com:1234/foo/'323334def test_environ_defaults(app, client, app_ctx, req_ctx):35 @app.route('/')36 def index():37 return flask.request.url3839 ctx = app.test_request_context()40 assert ctx.request.url == 'http://localhost/'42 with app.test_client() as c:43 rv = c.get('/')41 with client:42 rv = client.get('/')43 assert rv.data == b'http://localhost/'4446def test_redirect_keep_session():47 app = flask.Flask(__name__)4546def test_environ_base_default(app, client, app_ctx):47 @app.route('/')48 def index():49 flask.g.user_agent = flask.request.headers["User-Agent"]50 return flask.request.remote_addr5152 rv = client.get('/')53 assert rv.data == b'127.0.0.1'54 assert flask.g.user_agent == 'werkzeug/' + werkzeug.__version__555657def test_environ_base_modified(app, client, app_ctx):58 @app.route('/')59 def index():60 flask.g.user_agent = flask.request.headers["User-Agent"]61 return flask.request.remote_addr6263 client.environ_base['REMOTE_ADDR'] = '0.0.0.0'64 client.environ_base['HTTP_USER_AGENT'] = 'Foo'65 rv = client.get('/')66 assert rv.data == b'0.0.0.0'67 assert flask.g.user_agent == 'Foo'6869 client.environ_base['REMOTE_ADDR'] = '0.0.0.1'70 client.environ_base['HTTP_USER_AGENT'] = 'Bar'71 rv = client.get('/')72 assert rv.data == b'0.0.0.1'73 assert flask.g.user_agent == 'Bar'747576def test_redirect_keep_session(app, client, app_ctx):77 app.secret_key = 'testing'7879 @app.route('/', methods=['GET', 'POST'])80 def index():
5 unmodified lines
86 @app.route('/getsession')87 def get_session():88 return flask.session.get('data', '<missing>')8961 with app.test_client() as c:62 rv = c.get('/getsession')90 with client:91 rv = client.get('/getsession')92 assert rv.data == b'<missing>'9365 rv = c.get('/')94 rv = client.get('/')95 assert rv.data == b'index'96 assert flask.session.get('data') == 'foo'68 rv = c.post('/', data={}, follow_redirects=True)97 rv = client.post('/', data={}, follow_redirects=True)98 assert rv.data == b'foo'99100 # This support requires a new Werkzeug version72 if not hasattr(c, 'redirect_client'):101 if not hasattr(client, 'redirect_client'):102 assert flask.session.get('data') == 'foo'10375 rv = c.get('/getsession')104 rv = client.get('/getsession')105 assert rv.data == b'foo'10678def test_session_transactions():79 app = flask.Flask(__name__)80 app.testing = True107108def test_session_transactions(app, client):109 app.secret_key = 'testing'110111 @app.route('/')112 def index():113 return text_type(flask.session['foo'])11487 with app.test_client() as c:88 with c.session_transaction() as sess:115 with client:116 with client.session_transaction() as sess:117 assert len(sess) == 0118 sess['foo'] = [42]119 assert len(sess) == 192 rv = c.get('/')120 rv = client.get('/')121 assert rv.data == b'[42]'94 with c.session_transaction() as sess:122 with client.session_transaction() as sess:123 assert len(sess) == 1124 assert sess['foo'] == [42]125126127def test_session_transactions_no_null_sessions():128 app = flask.Flask(__name__)129 app.testing = True130131 with app.test_client() as c:103 try:132 with pytest.raises(RuntimeError) as e:133 with c.session_transaction() as sess:134 pass106 except RuntimeError as e:107 assert 'Session backend did not open a session' in str(e)135 assert 'Session backend did not open a session' in str(e.value)108 else:109 assert False, 'Expected runtime error'136111def test_session_transactions_keep_context():112 app = flask.Flask(__name__)113 app.testing = True137138def test_session_transactions_keep_context(app, client, req_ctx):139 app.secret_key = 'testing'140116 with app.test_client() as c:117 rv = c.get('/')118 req = flask.request._get_current_object()119 assert req is not None120 with c.session_transaction():121 assert req is flask.request._get_current_object()141 rv = client.get('/')142 req = flask.request._get_current_object()143 assert req is not None144 with client.session_transaction():145 assert req is flask.request._get_current_object()146123def test_session_transaction_needs_cookies():124 app = flask.Flask(__name__)125 app.testing = True147148def test_session_transaction_needs_cookies(app):149 c = app.test_client(use_cookies=False)127 try:150 with pytest.raises(RuntimeError) as e:151 with c.session_transaction() as s:152 pass130 except RuntimeError as e:131 assert 'cookies' in str(e)153 assert 'cookies' in str(e.value)132 else:133 assert False, 'Expected runtime error'154135def test_test_client_context_binding():136 app = flask.Flask(__name__)155156def test_test_client_context_binding(app, client):157 app.config['LOGGER_HANDLER_POLICY'] = 'never'158 app.testing = False159160 @app.route('/')161 def index():162 flask.g.value = 42163 return 'Hello World!'
1 unmodified line
165 @app.route('/other')166 def other():167 1 // 0168147 with app.test_client() as c:148 resp = c.get('/')169 with client:170 resp = client.get('/')171 assert flask.g.value == 42172 assert resp.data == b'Hello World!'173 assert resp.status_code == 200174153 resp = c.get('/other')175 resp = client.get('/other')176 assert not hasattr(flask.g, 'value')177 assert b'Internal Server Error' in resp.data178 assert resp.status_code == 500179 flask.g.value = 23
4 unmodified lines
184 pass185 else:186 raise AssertionError('some kind of exception expected')187166def test_reuse_client():167 app = flask.Flask(__name__)168 c = app.test_client()188189def test_reuse_client(client):190 c = client191192 with c:171 assert c.get('/').status_code == 404193 assert client.get('/').status_code == 404194195 with c:174 assert c.get('/').status_code == 404196 assert client.get('/').status_code == 404197176def test_test_client_calls_teardown_handlers():177 app = flask.Flask(__name__)198199def test_test_client_calls_teardown_handlers(app, client):200 called = []201202 @app.teardown_request203 def remember(error):204 called.append(error)205183 with app.test_client() as c:206 with client:207 assert called == []185 c.get('/')208 client.get('/')209 assert called == []210 assert called == [None]211212 del called[:]190 with app.test_client() as c:213 with client:214 assert called == []192 c.get('/')215 client.get('/')216 assert called == []194 c.get('/')217 client.get('/')218 assert called == [None]219 assert called == [None, None]220198def test_full_url_request():199 app = flask.Flask(__name__)200 app.testing = True221222def test_full_url_request(app, client):223 @app.route('/action', methods=['POST'])224 def action():225 return 'x'226206 with app.test_client() as c:207 rv = c.post('http://domain.com/action?vodka=42', data={'gin': 43})227 with client:228 rv = client.post('http://domain.com/action?vodka=42', data={'gin': 43})229 assert rv.status_code == 200230 assert 'gin' in flask.request.form231 assert 'vodka' in flask.request.args232212def test_subdomain():213 app = flask.Flask(__name__)233234def test_subdomain(app, client):235 app.config['SERVER_NAME'] = 'example.com'236237 @app.route('/', subdomain='<company_id>')238 def view(company_id):239 return company_id240241 with app.test_request_context():242 url = flask.url_for('view', company_id='xxx')243222 with app.test_client() as c:223 response = c.get(url)244 with client:245 response = client.get(url)246247 assert 200 == response.status_code248 assert b'xxx' == response.data249228def test_nosubdomain():229 app = flask.Flask(__name__)250251def test_nosubdomain(app, client):252 app.config['SERVER_NAME'] = 'example.com'253254 @app.route('/<company_id>')255 def view(company_id):256 return company_id257258 with app.test_request_context():259 url = flask.url_for('view', company_id='xxx')260238 with app.test_client() as c:239 response = c.get(url)261 with client:262 response = client.get(url)263264 assert 200 == response.status_code265 assert b'xxx' == response.data
modified:tests/test_user_error_handler.py+63 added-16 removed
1# -*- coding: utf-8 -*-2from werkzeug.exceptions import Forbidden, InternalServerError2from werkzeug.exceptions import (3 Forbidden,4 InternalServerError,5 HTTPException,6 NotFound7 )8import flask9106def test_error_handler_no_match():7 app = flask.Flask(__name__)11def test_error_handler_no_match(app, client):1213 class CustomException(Exception):14 pass15
13 unmodified lines
29 @app.route('/keyerror')30 def key_error():31 raise KeyError()3229 c = app.test_client()33 app.testing = False34 assert client.get('/custom').data == b'custom'35 assert client.get('/keyerror').data == b'KeyError'3631 assert c.get('/custom').data == b'custom'32 assert c.get('/keyerror').data == b'KeyError'373435def test_error_handler_subclass():38def test_error_handler_subclass(app):36 app = flask.Flask(__name__)3739 class ParentException(Exception):40 pass4142 class ChildExceptionUnregistered(ParentException):
30 unmodified lines
73 assert c.get('/child-unregistered').data == b'parent'74 assert c.get('/child-registered').data == b'child-registered'757676def test_error_handler_http_subclass():77 app = flask.Flask(__name__)7877def test_error_handler_http_subclass(app):78 class ForbiddenSubclassRegistered(Forbidden):79 pass8081 class ForbiddenSubclassUnregistered(Forbidden):
27 unmodified lines
109 assert c.get('/forbidden-unregistered').data == b'forbidden'110 assert c.get('/forbidden-registered').data == b'forbidden-registered'111112114def test_error_handler_blueprint():113def test_error_handler_blueprint(app):114 bp = flask.Blueprint('bp', __name__)115116 @bp.errorhandler(500)117 def bp_exception_handler(e):
2 unmodified lines
120 @bp.route('/error')121 def bp_test():122 raise InternalServerError()123125 app = flask.Flask(__name__)126124 @app.errorhandler(500)125 def app_exception_handler(e):126 return 'app-error'127
6 unmodified lines
134 c = app.test_client()135136 assert c.get('/error').data == b'app-error'137 assert c.get('/bp/error').data == b'bp-error'138139140def test_default_error_handler():141 bp = flask.Blueprint('bp', __name__)142143 @bp.errorhandler(HTTPException)144 def bp_exception_handler(e):145 assert isinstance(e, HTTPException)146 assert isinstance(e, NotFound)147 return 'bp-default'148149 @bp.errorhandler(Forbidden)150 def bp_exception_handler(e):151 assert isinstance(e, Forbidden)152 return 'bp-forbidden'153154 @bp.route('/undefined')155 def bp_registered_test():156 raise NotFound()157158 @bp.route('/forbidden')159 def bp_forbidden_test():160 raise Forbidden()161162 app = flask.Flask(__name__)163164 @app.errorhandler(HTTPException)165 def catchall_errorhandler(e):166 assert isinstance(e, HTTPException)167 assert isinstance(e, NotFound)168 return 'default'169170 @app.errorhandler(Forbidden)171 def catchall_errorhandler(e):172 assert isinstance(e, Forbidden)173 return 'forbidden'174175 @app.route('/forbidden')176 def forbidden():177 raise Forbidden()178179 app.register_blueprint(bp, url_prefix='/bp')180181 c = app.test_client()182 assert c.get('/bp/undefined').data == b'bp-default'183 assert c.get('/bp/forbidden').data == b'bp-forbidden'184 assert c.get('/undefined').data == b'default'185 assert c.get('/forbidden').data == b'forbidden'186187
modified:tests/test_views.py+102 added-25 removed
14 unmodified lines
15import flask.views1617from werkzeug.http import parse_set_header181920def common_test(app):21 c = app.test_client()2223 assert c.get('/').data == b'GET'
1 unmodified line
25 assert c.put('/').status_code == 40526 meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])27 assert sorted(meths) == ['GET', 'HEAD', 'OPTIONS', 'POST']2828def test_basic_view():29 app = flask.Flask(__name__)2930def test_basic_view(app):31 class Index(flask.views.View):32 methods = ['GET', 'POST']3334 def dispatch_request(self):35 return flask.request.method3637 app.add_url_rule('/', view_func=Index.as_view('index'))38 common_test(app)3939def test_method_based_view():40 app = flask.Flask(__name__)4041def test_method_based_view(app):42 class Index(flask.views.MethodView):43 def get(self):44 return 'GET'4546 def post(self):47 return 'POST'4849 app.add_url_rule('/', view_func=Index.as_view('index'))5051 common_test(app)5252def test_view_patching():53 app = flask.Flask(__name__)5354def test_view_patching(app):55 class Index(flask.views.MethodView):56 def get(self):57 1 // 05859 def post(self):60 1 // 06162 class Other(Index):63 def get(self):64 return 'GET'6566 def post(self):67 return 'POST'6869 view = Index.as_view('index')70 view.view_class = Other71 app.add_url_rule('/', view_func=view)72 common_test(app)7372def test_view_inheritance():73 app = flask.Flask(__name__)7475def test_view_inheritance(app, client):76 class Index(flask.views.MethodView):77 def get(self):78 return 'GET'7980 def post(self):81 return 'POST'8283 class BetterIndex(Index):84 def delete(self):85 return 'DELETE'8687 app.add_url_rule('/', view_func=BetterIndex.as_view('index'))86 c = app.test_client()8888 meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])89 meths = parse_set_header(client.open('/', method='OPTIONS').headers['Allow'])90 assert sorted(meths) == ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST']9191def test_view_decorators():92 app = flask.Flask(__name__)9293def test_view_decorators(app, client):94 def add_x_parachute(f):95 def new_function(*args, **kwargs):96 resp = flask.make_response(f(*args, **kwargs))97 resp.headers['X-Parachute'] = 'awesome'98 return resp99100 return new_function101102 class Index(flask.views.View):103 decorators = [add_x_parachute]104105 def dispatch_request(self):106 return 'Awesome'107108 app.add_url_rule('/', view_func=Index.as_view('index'))107 c = app.test_client()108 rv = c.get('/')109 rv = client.get('/')110 assert rv.headers['X-Parachute'] == 'awesome'111 assert rv.data == b'Awesome'112112def test_implicit_head():113114def test_view_provide_automatic_options_attr():115 app = flask.Flask(__name__)116117 class Index1(flask.views.View):118 provide_automatic_options = False119120 def dispatch_request(self):121 return 'Hello World!'122123 app.add_url_rule('/', view_func=Index1.as_view('index'))124 c = app.test_client()125 rv = c.open('/', method='OPTIONS')126 assert rv.status_code == 405127128 app = flask.Flask(__name__)129130 class Index2(flask.views.View):131 methods = ['OPTIONS']132 provide_automatic_options = True133134 def dispatch_request(self):135 return 'Hello World!'136137 app.add_url_rule('/', view_func=Index2.as_view('index'))138 c = app.test_client()139 rv = c.open('/', method='OPTIONS')140 assert sorted(rv.allow) == ['OPTIONS']141142 app = flask.Flask(__name__)143144 class Index3(flask.views.View):145 def dispatch_request(self):146 return 'Hello World!'147148 app.add_url_rule('/', view_func=Index3.as_view('index'))149 c = app.test_client()150 rv = c.open('/', method='OPTIONS')151 assert 'OPTIONS' in rv.allow152153154def test_implicit_head(app, client):155 class Index(flask.views.MethodView):156 def get(self):157 return flask.Response('Blub', headers={158 'X-Method': flask.request.method159 })160161 app.add_url_rule('/', view_func=Index.as_view('index'))122 c = app.test_client()123 rv = c.get('/')162 rv = client.get('/')163 assert rv.data == b'Blub'164 assert rv.headers['X-Method'] == 'GET'126 rv = c.head('/')165 rv = client.head('/')166 assert rv.data == b''167 assert rv.headers['X-Method'] == 'HEAD'168130def test_explicit_head():131 app = flask.Flask(__name__)169170def test_explicit_head(app, client):171 class Index(flask.views.MethodView):172 def get(self):173 return 'GET'174175 def head(self):176 return flask.Response('', headers={'X-Method': 'HEAD'})177178 app.add_url_rule('/', view_func=Index.as_view('index'))140 c = app.test_client()141 rv = c.get('/')179 rv = client.get('/')180 assert rv.data == b'GET'143 rv = c.head('/')181 rv = client.head('/')182 assert rv.data == b''183 assert rv.headers['X-Method'] == 'HEAD'184147def test_endpoint_override():148 app = flask.Flask(__name__)185186def test_endpoint_override(app):187 app.debug = True188189 class Index(flask.views.View):190 methods = ['GET', 'POST']191192 def dispatch_request(self):193 return flask.request.method194195 app.add_url_rule('/', view_func=Index.as_view('index'))
2 unmodified lines
198 app.add_url_rule('/', view_func=Index.as_view('index'))199200 # But these tests should still pass. We just log a warning.201 common_test(app)202203204def test_multiple_inheritance(app, client):205 class GetView(flask.views.MethodView):206 def get(self):207 return 'GET'208209 class DeleteView(flask.views.MethodView):210 def delete(self):211 return 'DELETE'212213 class GetDeleteView(GetView, DeleteView):214 pass215216 app.add_url_rule('/', view_func=GetDeleteView.as_view('index'))217218 assert client.get('/').data == b'GET'219 assert client.delete('/').data == b'DELETE'220 assert sorted(GetDeleteView.methods) == ['DELETE', 'GET']221222223def test_remove_method_from_parent(app, client):224 class GetView(flask.views.MethodView):225 def get(self):226 return 'GET'227228 class OtherView(flask.views.MethodView):229 def post(self):230 return 'POST'231232 class View(GetView, OtherView):233 methods = ['GET']234235 app.add_url_rule('/', view_func=View.as_view('index'))236237 assert client.get('/').data == b'GET'238 assert client.post('/').status_code == 405239 assert sorted(View.methods) == ['GET']
added:.coveragerc+11 added
1[run]2branch = True3source =4 flask5 tests67[paths]8source =9 flask10 .tox/*/lib/python*/site-packages/flask11 .tox/pypy/site-packages/flask
added:.gitattributes+1 added
1CHANGES merge=union
modified:.gitignore+9 added
2 unmodified lines
3*.pyo4env5env*6dist7build8*.egg9*.egg-info10_mailinglist11.tox12.cache/13.idea/1415# Coverage reports16htmlcov17.coverage18.coverage.*19*,cover
modified:.gitmodules+1 added-1 removed
1[submodule "docs/_themes"]2 path = docs/_themes3 url = git://github.com/mitsuhiko/flask-sphinx-themes.git3 url = https://github.com/mitsuhiko/flask-sphinx-themes.git
modified:.travis.yml+49 added-25 removed
1sudo: false2language: python34python:5 - "2.6"6 - "2.7"7 - "pypy"8 - "3.3"9 - "3.4"1011env:12 - REQUIREMENTS=lowest13 - REQUIREMENTS=release14 - REQUIREMENTS=devel154matrix:17 exclude:18 # Python 3 support currently does not work with lowest requirements19 - python: "3.3"20 env: REQUIREMENTS=lowest21 - python: "3.4"22 env: REQUIREMENTS=lowest5 include:6 - python: 3.67 env: TOXENV=py-release,codecov8 - python: 3.59 env: TOXENV=py-release,codecov10 - python: 3.411 env: TOXENV=py-release,codecov12 - python: 3.313 env: TOXENV=py-release,codecov14 - python: 2.715 env: TOXENV=py-release,codecov16 - python: 2.617 env: TOXENV=py-release,codecov18 - python: pypy19 env: TOXENV=py-release,codecov20 - python: nightly21 env: TOXENV=py-release22 - python: 3.623 env: TOXENV=docs-html24 - python: 3.625 env: TOXENV=py-release-simplejson,codecov26 - python: 2.727 env: TOXENV=py-release-simplejson,codecov28 - python: pypy29 env: TOXENV=py-release-simplejson,codecov30 - python: 3.631 env: TOXENV=py-devel,codecov32 - python: 3.333 env: TOXENV=py-devel,codecov34 - python: 2.735 env: TOXENV=py-devel,codecov36 - python: 2.637 env: TOXENV=py-devel,codecov38 - python: pypy39 env: TOXENV=py-devel,codecov40 - python: 3.641 env: TOXENV=py-lowest,codecov42 - python: 3.343 env: TOXENV=py-lowest,codecov44 - python: 2.745 env: TOXENV=py-lowest,codecov46 - python: 2.647 env: TOXENV=py-lowest,codecov48 - python: pypy49 env: TOXENV=py-lowest,codecov502451install:26 - pip install tox>=1.852 - pip install tox5354script:29 - tox -e \30 $(echo py$TRAVIS_PYTHON_VERSION | tr -d . | sed -e 's/pypypy/pypy/')-$REQUIREMENTS55 - tox5632branches:33 except:34 - website57cache:58 - pip5960notifications:61 email: false62 irc:
6 unmodified lines
modified:AUTHORS+4 added
13 unmodified lines
14- 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 Sigler
10 unmodified lines
modified:CHANGES+136 added-7 removed
1 unmodified line
2===============34Here you can see the full list of changes between each Flask release.56Version 1.07-----------6Version 0.137------------89(release date to be announced, codename to be selected)9Major release, unreleased1011- Make `app.run()` into a noop if a Flask application is run from the12 development server on the command line. This avoids some behavior that13 was confusing to debug for newcomers.14- Change default configuration `JSONIFY_PRETTYPRINT_REGULAR=False`. jsonify()15 method returns compressed response by default, and pretty response in16 debug mode.17- Change Flask.__init__ to accept two new keyword arguments, ``host_matching``18 and ``static_host``. This enables ``host_matching`` to be set properly by the19 time the constructor adds the static route, and enables the static route to20 be properly associated with the required host. (``#1559``)21- ``send_file`` supports Unicode in ``attachment_filename``. (`#2223`_)22- Pass ``_scheme`` argument from ``url_for`` to ``handle_build_error``.23 (`#2017`_)24- Add support for ``provide_automatic_options`` in ``add_url_rule`` to disable25 adding OPTIONS method when the ``view_func`` argument is not a class.26 (`#1489`_).27- ``MethodView`` can inherit method handlers from base classes. (`#1936`_)28- Errors caused while opening the session at the beginning of the request are29 handled by the app's error handlers. (`#2254`_)30- Blueprints gained ``json_encoder`` and ``json_decoder`` attributes to31 override the app's encoder and decoder. (`#1898`_)32- ``Flask.make_response`` raises ``TypeError`` instead of ``ValueError`` for33 bad response types. The error messages have been improved to describe why the34 type is invalid. (`#2256`_)35- Add ``routes`` CLI command to output routes registered on the application.36 (`#2259`_)37- Show warning when session cookie domain is a bare hostname or an IP38 address, as these may not behave properly in some browsers, such as Chrome.39 (`#2282`_)40- Allow IP address as exact session cookie domain. (`#2282`_)41- ``SESSION_COOKIE_DOMAIN`` is set if it is detected through ``SERVER_NAME``.42 (`#2282`_)43- Auto-detect zero-argument app factory called ``create_app`` or ``make_app``44 from ``FLASK_APP``. (`#2297`_)45- Factory functions are not required to take a ``script_info`` parameter to46 work with the ``flask`` command. If they take a single parameter or a47 parameter named ``script_info``, the ``ScriptInfo`` object will be passed.48 (`#2319`_)4950.. _#1489: https://github.com/pallets/flask/pull/148951.. _#1898: https://github.com/pallets/flask/pull/189852.. _#1936: https://github.com/pallets/flask/pull/193653.. _#2017: https://github.com/pallets/flask/pull/201754.. _#2223: https://github.com/pallets/flask/pull/222355.. _#2254: https://github.com/pallets/flask/pull/225456.. _#2256: https://github.com/pallets/flask/pull/225657.. _#2259: https://github.com/pallets/flask/pull/225958.. _#2282: https://github.com/pallets/flask/pull/228259.. _#2297: https://github.com/pallets/flask/pull/229760.. _#2319: https://github.com/pallets/flask/pull/23196162Version 0.12.263--------------6465Released on May 16 20176667- Fix a bug in `safe_join` on Windows.6869Version 0.12.170--------------7172Bugfix release, released on March 31st 20177374- Prevent `flask run` from showing a NoAppException when an ImportError occurs75 within the imported application module.76- Fix encoding behavior of ``app.config.from_pyfile`` for Python 3. Fix77 ``#2118``.78- Use the ``SERVER_NAME`` config if it is present as default values for79 ``app.run``. ``#2109``, ``#2152``80- Call `ctx.auto_pop` with the exception object instead of `None`, in the81 event that a `BaseException` such as `KeyboardInterrupt` is raised in a82 request handler.8384Version 0.1285------------8687Released on December 21st 2016, codename Punsch.8889- the cli command now responds to `--version`.90- Mimetype guessing and ETag generation for file-like objects in ``send_file``91 has been removed, as per issue ``#104``. See pull request ``#1849``.92- Mimetype guessing in ``send_file`` now fails loudly and doesn't fall back to93 ``application/octet-stream``. See pull request ``#1988``.94- Make ``flask.safe_join`` able to join multiple paths like ``os.path.join``95 (pull request ``#1730``).96- Revert a behavior change that made the dev server crash instead of returning97 a Internal Server Error (pull request ``#2006``).98- Correctly invoke response handlers for both regular request dispatching as99 well as error handlers.100- Disable logger propagation by default for the app logger.101- Add support for range requests in ``send_file``.102- ``app.test_client`` includes preset default environment, which can now be103 directly set, instead of per ``client.get``.104105Version 0.11.2106--------------107108Bugfix release, unreleased109110- Fix crash when running under PyPy3, see pull request ``#1814``.111112Version 0.11.1113--------------114115Bugfix release, released on June 7th 2016.116117- Fixed a bug that prevented ``FLASK_APP=foobar/__init__.py`` from working. See118 pull request ``#1872``.119120Version 0.11121------------122123Released on May 29th 2016, codename Absinthe.124125- Added support to serializing top-level arrays to :func:`flask.jsonify`. This126 introduces a security risk in ancient browsers. See127 :ref:`json-security` for details.128- Added before_render_template signal.129- Added `**kwargs` to :meth:`flask.Test.test_client` to support passing130 additional keyword arguments to the constructor of131 :attr:`flask.Flask.test_client_class`.132- Added ``SESSION_REFRESH_EACH_REQUEST`` config key that controls the
6 unmodified lines
139- Added support for returning tuples in the form ``(response, headers)``140 from a view function.141- Added :meth:`flask.Config.from_json`.142- Added :attr:`flask.Flask.config_class`.25- Added :meth:`flask.config.Config.get_namespace`.143- Added :meth:`flask.Config.get_namespace`.144- Templates are no longer automatically reloaded outside of debug mode. This145 can be configured with the new ``TEMPLATES_AUTO_RELOAD`` config key.146- Added a workaround for a limitation in Python 3.3's namespace loader.147- Added support for explicit root paths when using Python 3.3's namespace
25 unmodified lines
173 unnecessary white space included by default after separators.174- JSON responses are now terminated with a newline character, because it is a175 convention that UNIX text files end with a newline and some clients don't176 deal well when this newline is missing. See59 https://github.com/mitsuhiko/flask/pull/1262 -- this came up originally as a177 https://github.com/pallets/flask/pull/1262 -- this came up originally as a178 part of https://github.com/kennethreitz/httpbin/issues/168179- The automatically provided ``OPTIONS`` method is now correctly disabled if180 the user registered an overriding rule with the lowercase-version181 ``options`` (issue ``#1288``).
3 unmodified lines
185 handlers (pull request ``#1393``).186- Allow custom Jinja environment subclasses (pull request ``#1422``).187- Updated extension dev guidelines.188189- ``flask.g`` now has ``pop()`` and ``setdefault`` methods.190- Turn on autoescape for ``flask.templating.render_template_string`` by default191 (pull request ``#1515``).192- ``flask.ext`` is now deprecated (pull request ``#1484``).193- ``send_from_directory`` now raises BadRequest if the filename is invalid on194 the server OS (pull request ``#1763``).195- Added the ``JSONIFY_MIMETYPE`` configuration variable (pull request ``#1728``).196- Exceptions during teardown handling will no longer leave bad application197 contexts lingering around.198199Version 0.10.2200--------------201
13 unmodified lines
215 correctly.216- Changed logic of before first request handlers to flip the flag after217 invoking. This will allow some uses that are potentially dangerous but218 should probably be permitted.219- Fixed Python 3 bug when a handler from `app.url_build_error_handlers`220 reraises the `BuildError`.221222Version 0.10.1223--------------224
11 unmodified lines
236237Version 0.10238------------239111Released on June 13nd 2013, codename Limoncello.240Released on June 13th 2013, codename Limoncello.241242- Changed default cookie serialization format from pickle to JSON to243 limit the impact an attacker can do if the secret key leaks. See244 :ref:`upgrading-to-010` for more information.
171 unmodified lines
416 error if not handled. This is a backwards incompatible change.417- Applications now not only have a root path where the resources and modules418 are located but also an instance path which is the designated place to419 drop files that are modified at runtime (uploads etc.). Also this is291 conceptionally only instance depending and outside version control so it's420 conceptually only instance depending and outside version control so it's421 the perfect place to put configuration files etc. For more information422 see :ref:`instance-folders`.423- Added the ``APPLICATION_ROOT`` configuration variable.424- Implemented :meth:`~flask.testing.TestClient.session_transaction` to
257 unmodified lines
modified:CONTRIBUTING.rst+110 added-16 removed
1==========================2How to contribute to Flask3==========================45Thanks for considering contributing to Flask. 5Thanks for considering contributing to Flask.67Support questions8=================910Please, don't use the issue tracker for this. Check whether the ``#pocoo`` IRC11channel on Freenode can help with your issue. If your problem is not strictly12Werkzeug 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.1415Reporting issues16================17
9 unmodified lines
27- Include tests if your patch is supposed to solve a bug, and explain28 clearly under which circumstances the bug happens. Make sure the test fails29 without your patch.3031- Try to follow `PEP8 <http://legacy.python.org/dev/peps/pep-0008/>`_, but you31- Try to follow `PEP8 <https://www.python.org/dev/peps/pep-0008/>`_, but you32 may ignore the line-length-limit if following it would make the code uglier.3334First time setup35----------------3637- Download and install the `latest version of git`_.38- Configure git with your `username`_ and `email`_.39- Make sure you have a `GitHub account`_.40- Fork Flask to your GitHub account by clicking the `Fork`_ button.41- `Clone`_ your GitHub fork locally.42- Add the main repository as a remote to update later.43 ``git remote add pallets https://github.com/pallets/flask``4445.. _GitHub account: https://github.com/join46.. _latest version of git: https://git-scm.com/downloads47.. _username: https://help.github.com/articles/setting-your-username-in-git/48.. _email: https://help.github.com/articles/setting-your-email-in-git/49.. _Fork: https://github.com/pallets/flask/pull/2305#fork-destination-box50.. _Clone: https://help.github.com/articles/fork-a-repo/#step-2-create-a-local-clone-of-your-fork5152Start coding53------------5455- Create a branch to identify the issue you would like to work on (e.g.56 ``2287-dry-test-suite``)57- Using your favorite editor, make your changes, `committing as you go`_.58- Try to follow `PEP8`_, but you may ignore the line length limit if following59 it would make the code uglier.60- Include tests that cover any code changes you make. Make sure the test fails61 without your patch. `Run the tests. <contributing-testsuite_>`_.62- Push your commits to GitHub and `create a pull request`_.63- Celebrate 🎉6465.. _committing as you go: http://dont-be-afraid-to-commit.readthedocs.io/en/latest/git/commandlinegit.html#commit-your-changes66.. _PEP8: https://pep8.org/67.. _create a pull request: https://help.github.com/articles/creating-a-pull-request/6869.. _contributing-testsuite:7071Running the testsuite72---------------------7374You probably want to set up a `virtualenv39<http://virtualenv.readthedocs.org/en/latest/index.html>`_.75<https://virtualenv.readthedocs.io/en/latest/index.html>`_.7641The minimal requirement for running the testsuite is ``py.test``. You can77The minimal requirement for running the testsuite is ``pytest``. You can78install it with::7980 pip install pytest8182Clone this repository::8348 git clone https://github.com/mitsuhiko/flask.git84 git clone https://github.com/pallets/flask.git8586Install Flask as an editable package using the current source::8788 cd flask52 pip install --editable . 89 pip install --editable .9091Running the testsuite92---------------------9394The minimal requirement for running the testsuite is ``pytest``. You can95install it with::9697 pip install pytest9899Then you can run the testsuite with::10056 py.test101 pytest tests/10258With only py.test installed, a large part of the testsuite will get skipped59though. Whether this is relevant depends on which part of Werkzeug you're60working on. Travis is set up to run the full testsuite when you submit your61pull request anyways.103**Shortcut**: ``make test`` will ensure ``pytest`` is installed, and run it.104105With only pytest installed, a large part of the testsuite will get skipped106though. Whether this is relevant depends on which part of Flask you're working107on. Travis is set up to run the full testsuite when you submit your pull108request anyways.109110If you really want to test everything, you will have to install ``tox`` instead64of ``pytest``. Currently we're depending on a development version of Tox65because the released version is missing features we absolutely need. You can66install it with::111of ``pytest``. You can install it with::11268 pip install hg+https://bitbucket.org/hpk42/tox113 pip install tox114115The ``tox`` command will then run all tests against multiple combinations116Python versions and dependency versions.117118**Shortcut**: ``make tox-test`` will ensure ``tox`` is installed, and run it.119120Running test coverage121---------------------122Generating a report of lines that do not have unit test coverage can indicate where123to start contributing. ``pytest`` integrates with ``coverage.py``, using the ``pytest-cov``124plugin. This assumes you have already run the testsuite (see previous section)::125126 pip install pytest-cov127128After this has been installed, you can output a report to the command line using this command::129130 pytest --cov=flask tests/131132Generate a HTML report can be done using this command::133134 pytest --cov-report html --cov=flask tests/135136Full docs on ``coverage.py`` are here: https://coverage.readthedocs.io137138**Shortcut**: ``make cov`` will ensure ``pytest-cov`` is installed, run it, display the results, *and* save the HTML report.139140141Caution142=======143pushing144-------145This 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.146147148cloning149-------150The zero-padded file modes files above can cause issues while cloning, too. If you have151152::153154 [fetch]155 fsckobjects = true156157or158159::160161 [receive]162 fsckObjects = true163164165set 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+5 added-3 removed
1 unmodified line
23all: clean-pyc test45test:6 py.test tests examples6 pip install -r test-requirements.txt7 tox -e py-release88tox-test:9 tox9cov:10 pip install -r test-requirements.txt -q11 FLASK_DEBUG= py.test --cov-report term --cov-report html --cov=flask --cov=examples tests examples1213audit:14 python setup.py audit15
30 unmodified lines
modified:MANIFEST.in+8 added-10 removed
1include Makefile CHANGES LICENSE AUTHORS2recursive-include artwork *3recursive-include tests *4recursive-include examples *5recursive-include docs *6recursive-exclude docs *.pyc7recursive-exclude docs *.pyo8recursive-exclude tests *.pyc9recursive-exclude tests *.pyo10recursive-exclude examples *.pyc11recursive-exclude examples *.pyo23graft artwork4graft tests5graft examples6graft docs78global-exclude *.py[co]910prune docs/_build11prune docs/_themes
modified:README+4 added-2 removed
31 unmodified lines
32 ~ Where are the tests?3334 Good that you're asking. The tests are in the35 tests/ folder. To run the tests use the36 `py.test` testing tool:36 `pytest` testing tool:3738 $ py.test38 $ pytest3940 Details on contributing can be found in CONTRIBUTING.rst4142 ~ Where can I get help?4344 Either use the #pocoo IRC channel on irc.freenode.net or45 ask on the mailinglist: http://flask.pocoo.org/mailinglist/
4 unmodified lines
modified:setup.cfg+7 added-3 removed
1[aliases]2release = egg_info -RDb ''34[wheel]4[bdist_wheel]5universal = 167[pytest]8norecursedirs = .* *.egg *.egg-info env* artwork docs7[metadata]8license_file = LICENSE910[tool:pytest]11minversion = 3.012testpaths = tests
modified:setup.py+12 added-4 removed
31 unmodified lines
32 $ pip install Flask33 $ python hello.py34 * Running on http://localhost:5000/3536 Ready for production? `Read this first <http://flask.pocoo.org/docs/deploying/>`.3738Links39`````4041* `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>`_4546"""47import re48import ast
9 unmodified lines
5859setup(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 '
3 unmodified lines
70 include_package_data=True,71 zip_safe=False,72 platforms='any',73 install_requires=[72 'Werkzeug>=0.7',74 'Werkzeug>=0.9',75 'Jinja2>=2.4',76 'itsdangerous>=0.21',75 'click>=2.0',77 'click>=4.0',78 ],79 classifiers=[80 'Development Status :: 4 - Beta',81 'Environment :: Web Environment',82 'Intended Audience :: Developers',83 'License :: OSI Approved :: BSD License',84 'Operating System :: OS Independent',85 'Programming Language :: Python',86 'Programming Language :: Python :: 2',87 'Programming Language :: Python :: 2.6',88 'Programming Language :: Python :: 2.7',89 'Programming Language :: Python :: 3',90 'Programming Language :: Python :: 3.3',91 'Programming Language :: Python :: 3.4',92 'Programming Language :: Python :: 3.5',93 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',94 'Topic :: Software Development :: Libraries :: Python Modules'95 ],96 entry_points='''
4 unmodified lines
added:test-requirements.txt+3 added
1tox2pytest3pytest-cov
modified:tox.ini+54 added-17 removed
1[tox]2envlist = {py26,py27,pypy}-{lowest,release,devel}, {py33,py34}-{release,devel}2envlist =3 py{36,35,34,33,27,26,py}-release4 py{36,27,py}-release-simplejson5 py{36,33,27,26,py}-devel6 py{36,33,27,26,py}-lowest7 docs-html8 coverage-report910[testenv]5commands =6 py.test []78deps=9 pytest11passenv = LANG12usedevelop = true13deps =14 pytest>=315 coverage16 greenlet11 redbaron17 blinker1813 lowest: Werkzeug==0.719 lowest: Werkzeug==0.920 lowest: Jinja2==2.421 lowest: itsdangerous==0.2116 lowest: blinker==1.017 release: blinker18 devel: git+git://github.com/mitsuhiko/werkzeug.git19 devel: git+git://github.com/mitsuhiko/jinja2.git20 devel: git+git://github.com/mitsuhiko/itsdangerous.git21 devel: git+git://github.com/jek/blinker.git22 lowest: Click==4.02323# extra dependencies24git+git://github.com/jek/blinker.git#egg=blinker24 devel: https://github.com/pallets/werkzeug/archive/master.tar.gz25 devel: https://github.com/pallets/markupsafe/archive/master.tar.gz26 devel: https://github.com/pallets/jinja/archive/master.tar.gz27 devel: https://github.com/pallets/itsdangerous/archive/master.tar.gz28 devel: https://github.com/pallets/click/archive/master.tar.gz2930 simplejson: simplejson31commands =32 # the examples need to be installed to test successfully33 pip install -e examples/flaskr -q34 pip install -e examples/minitwit -q35 pip install -e examples/patterns/largerapp -q3637 # pytest-cov doesn't seem to play nice with -p38 coverage run -p -m pytest3926[testenv:docs]40[testenv:docs-html]41deps =42 sphinx43 flask-sphinx-themes44commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs docs/_build/html4546[testenv:docs-linkcheck]47deps = sphinx48commands = sphinx-build -W -b linkcheck -d {envtmpdir}/doctrees docs docs/_build/linkcheck4950[testenv:coverage-report]51deps = coverage52skip_install = true53commands =54 coverage combine55 coverage report56 coverage html5758[testenv:codecov]59passenv = CI TRAVIS TRAVIS_*60deps = codecov61skip_install = true62commands =63 coverage combine64 coverage report65 codecov