Skip to content
Myr

Merge branch 'master' into vary-cookies

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

authored by David Lord · committed by David Lord · parents 5935ee4, a558d47 · Browse files · 288 files+12758 added−9447 removed
This commit

State

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

Diff stats

288 files+12758 added−9447 removed

  • tests:+6518 added−0 removed
  • other:+6240 added−9447 removed

288 files+12758 added−9447 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>
modified:docs/_templates/sidebarintro.html+3 added-3 removed
modified:docs/deploying/cgi.rst+6 added-6 removed
22 unmodified lines
23Creating a `.cgi` file24----------------------2526First you need to create the CGI application file. Let's call it27`yourapplication.cgi`::27:file:`yourapplication.cgi`::2829 #!/usr/bin/python30 from wsgiref.handlers import CGIHandler31 from yourapplication import app
3 unmodified lines
35Server Setup36------------3738Usually there are two ways to configure the server. Either just copy the39`.cgi` into a `cgi-bin` (and use `mod_rewrite` or something similar to39``.cgi`` into a :file:`cgi-bin` (and use `mod_rewrite` or something similar to40rewrite the URL) or let the server point to the file directly.4142In Apache for example you can put something like this into the config:43
1 unmodified line
4546 ScriptAlias /app /path/to/the/application.cgi4748On shared webhosting, though, you might not have access to your Apache config.49In this case, a file called `.htaccess`, sitting in the public directory you want50your app to be available, works too but the `ScriptAlias` directive won't49In this case, a file called ``.htaccess``, sitting in the public directory you want50your app to be available, works too but the ``ScriptAlias`` directive won't51work in that case:5253.. sourcecode:: apache54 5455 RewriteEngine On56 RewriteCond %{REQUEST_FILENAME} !-f # Don't interfere with static files57 RewriteRule ^(.*)$ /path/to/the/application.cgi/$1 [L]5859For more information consult the documentation of your webserver.6061.. _App Engine: http://code.google.com/appengine/61.. _App Engine: https://developers.google.com/appengine/
modified:docs/deploying/fastcgi.rst+19 added-19 removed
38 unmodified lines
3940The path has to be the exact same path you define in the server41config.4243Save the `yourapplication.fcgi` file somewhere you will find it again.44It makes sense to have that in `/var/www/yourapplication` or something43Save the :file:`yourapplication.fcgi` file somewhere you will find it again.44It makes sense to have that in :file:`/var/www/yourapplication` or something45similar.4647Make sure to set the executable bit on that file so that the servers48can execute it:
6 unmodified lines
55------------------5657The example above is good enough for a basic Apache deployment but your58`.fcgi` file will appear in your application URL e.g.59example.com/yourapplication.fcgi/news/. There are few ways to configure59``example.com/yourapplication.fcgi/news/``. There are few ways to configure60your application so that yourapplication.fcgi does not appear in the URL.61A preferable way is to use the ScriptAlias and SetHandler configuration62directives to route requests to the FastCGI server. The following example63uses FastCgiServer to start 5 instances of the application which will
14 unmodified lines
78 SetHandler fastcgi-script79 </Location>80 </VirtualHost>8182These processes will be managed by Apache. If you're using an standalone82These processes will be managed by Apache. If you're using a standalone83FastCGI server, you can use the FastCgiExternalServer directive instead.84Note that in the following the path is not real, it's simply used as an85identifier to other86directives such as AliasMatch::8788 FastCgiServer /var/www/html/yourapplication -host 127.0.0.1:30008990If you cannot set ScriptAlias, for example on an shared web host, you can use90If you cannot set ScriptAlias, for example on a shared web host, you can use91WSGI middleware to remove yourapplication.fcgi from the URLs. Set .htaccess::9293 <IfModule mod_fcgid.c>94 AddHandler fcgid-script .fcgi
48 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",152 "^(/.*)$" => "/yourapplication.fcgi$1"153 )154155Remember to enable the FastCGI, alias and rewrite modules. This configuration156binds the application to `/yourapplication`. If you want the application to156binds the application to ``/yourapplication``. If you want the application to157work in the URL root you have to work around a lighttpd bug with the158: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/wiki/lighttpd/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-----------------167168Installing FastCGI applications on nginx is a bit different because by169default no FastCGI parameters are forwarded.170171A basic flask FastCGI configuration for nginx looks like this::171A basic Flask FastCGI configuration for nginx looks like this::172173 location = /yourapplication { rewrite ^ /yourapplication/ last; }174 location /yourapplication { try_files $uri @yourapplication; }175 location @yourapplication {
3 unmodified lines
179 fastcgi_param SCRIPT_NAME $fastcgi_script_name;180 fastcgi_pass unix:/tmp/yourapplication-fcgi.sock;181 }182183This configuration binds the application to `/yourapplication`. If you183This configuration binds the application to ``/yourapplication``. If you184want to have it in the URL root it's a bit simpler because you don't185have to figure out how to calculate `PATH_INFO` and `SCRIPT_NAME`::185have to figure out how to calculate ``PATH_INFO`` and ``SCRIPT_NAME``::186187 location / { try_files $uri @yourapplication; }188 location @yourapplication {189 include fastcgi_params;
4 unmodified lines
194195Running FastCGI Processes196-------------------------197198Since Nginx and others do not load FastCGI apps, you have to do it by198Since nginx and others do not load FastCGI apps, you have to do it by199yourself. `Supervisor can manage FastCGI processes.200<http://supervisord.org/configuration.html#fcgi-program-x-section-settings>`_201You can look around for other FastCGI process managers or write a script202to run your `.fcgi` file at boot, e.g. using a SysV ``init.d`` script.
6 unmodified lines
209210Debugging211---------212213FastCGI deployments tend to be hard to debug on most webservers. Very213FastCGI deployments tend to be hard to debug on most web servers. Very214often the only thing the server log tells you is something along the215lines of "premature end of headers". In order to debug the application216the only thing that can really give you ideas why it breaks is switching217to the correct user and executing the application by hand.218219This example assumes your application is called `application.fcgi` and220that your webserver user is `www-data`::220that your web server user is `www-data`::221222 $ su www-data223 $ cd /var/www/yourapplication224 $ python application.fcgi
3 unmodified lines
228229In this case the error seems to be "yourapplication" not being on the230python path. Common problems are:231232- Relative paths being used. Don't rely on the current working directory232- Relative paths being used. Don't rely on the current working directory.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/239.. _cherokee: http://www.cherokee-project.com/240.. _flup: http://trac.saddi.com/flup237.. _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+23 added-10 removed
1 unmodified line
23Deployment Options4==================56Depending on what you have available there are multiple ways to run7Flask applications. You can use the builtin server during development,8but you should use a full deployment option for production applications.9(Do not use the builtin development server in production.) Several10options are available and documented here.6While lightweight and easy to use, **Flask's built-in server is not suitable7for production** as it doesn't scale well and by default serves only one8request at a time. Some of the options available for properly running Flask in9production are documented here.1012If you have a different WSGI server look up the server documentation13about how to use a WSGI app with it. Just remember that your14:class:`Flask` application object is the actual WSGI application.11If you want to deploy your Flask application to a WSGI server not listed here,12look up the server documentation about how to use a WSGI app with it. Just13remember that your :class:`Flask` application object is the actual WSGI14application.1516For hosted options to get up and running quickly, see17:ref:`quickstart_deployment` in the Quickstart.1617Hosted options18--------------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 Flask on Webfaction <http://flask.pocoo.org/snippets/65/>`_23- `Deploying Flask on Google App Engine <https://github.com/kamalgill/flask-appengine-template>`_24- `Deploying Flask on AWS Elastic Beanstalk <https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-flask.html>`_25- `Sharing your Localhost Server with Localtunnel <http://flask.pocoo.org/snippets/89/>`_26- `Deploying on Azure (IIS) <https://azure.microsoft.com/documentation/articles/web-sites-python-configure/>`_27- `Deploying on PythonAnywhere <https://help.pythonanywhere.com/pages/Flask/>`_2829Self-hosted options30-------------------3132.. toctree::33 :maxdepth: 23435 mod_wsgi
4 unmodified lines
modified:docs/deploying/mod_wsgi.rst+47 added-16 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
7 unmodified lines
28.. sourcecode:: text2930 # apt-get install libapache2-mod-wsgi3132If you are using a yum based distribution (Fedora, OpenSUSE, etc..) you33can install it as follows:3435.. sourcecode:: text3637 # yum install mod_wsgi3839On FreeBSD install `mod_wsgi` by compiling the `www/mod_wsgi` port or by40using pkg_add:4142.. sourcecode:: text4337 # pkg_add -r mod_wsgi44 # pkg install ap22-mod_wsgi24546If you are using pkgsrc you can install `mod_wsgi` by compiling the47`www/ap2-wsgi` package.48
2 unmodified lines
5152Creating a `.wsgi` file53-----------------------5448To run your application you need a `yourapplication.wsgi` file. This file55To run your application you need a :file:`yourapplication.wsgi` file. This file56contains the code `mod_wsgi` is executing on startup to get the application57object. The object called `application` in that file is then used as58application.59
4 unmodified lines
64If you don't have a factory function for application creation but a singleton65instance you can directly import that one as `application`.6667Store that file somewhere that you will find it again (e.g.:61`/var/www/yourapplication`) and make sure that `yourapplication` and all68:file:`/var/www/yourapplication`) and make sure that `yourapplication` and all69the libraries that are in use are on the python load path. If you don't70want to install it system wide consider using a `virtual python`_71instance. Keep in mind that you will have to actually install your72application into the virtualenv as well. Alternatively there is the66option to just patch the path in the `.wsgi` file before the import::73option to just patch the path in the ``.wsgi`` file before the import::7475 import sys76 sys.path.insert(0, '/path/to/the/application')77
19 unmodified lines
97 Allow from all98 </Directory>99 </VirtualHost>10094Note: WSGIDaemonProcess isn't implemented in Windows and Apache will 101Note: WSGIDaemonProcess isn't implemented in Windows and Apache will102refuse to run with the above configuration. On a Windows system, eliminate those lines:103104.. sourcecode:: apache105
5 unmodified lines
111 Allow from all112 </Directory>113 </VirtualHost>114108For more information consult the `mod_wsgi wiki`_.115Note: There have been some changes in access control configuration for `Apache 2.4`_.116110.. _mod_wsgi: http://code.google.com/p/modwsgi/111.. _installation instructions: http://code.google.com/p/modwsgi/wiki/QuickInstallationGuide112.. _virtual python: http://pypi.python.org/pypi/virtualenv113.. _mod_wsgi wiki: http://code.google.com/p/modwsgi/wiki/117.. _Apache 2.4: https://httpd.apache.org/docs/trunk/upgrading.html118119Most notably, the syntax for directory permissions has changed from httpd 2.2120121.. 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/virtualenv138.. _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 ignored121 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 it124 into a separate `run.py` file or put it into such an if block.149 into a separate :file:`run.py` file or put it into such an if block.150151**Problem:** application gives permission errors152 Probably caused by your application running as the wrong user. Make153 sure the folders the application needs access to have the proper
30 unmodified lines
184Support for Automatic Reloading185-------------------------------186187To help deployment tools you can activate support for automatic163reloading. Whenever something changes the `.wsgi` file, `mod_wsgi` will188reloading. Whenever something changes the ``.wsgi`` file, `mod_wsgi` will189reload all the daemon processes for us.190191For that, just add the following directive to your `Directory` section:192
6 unmodified lines
199200Virtual environments have the advantage that they never install the201required dependencies system wide so you have a better control over what202is used where. If you want to use a virtual environment with mod_wsgi178you have to modify your `.wsgi` file slightly.203you have to modify your ``.wsgi`` file slightly.204180Add the following lines to the top of your `.wsgi` file::205Add the following lines to the top of your ``.wsgi`` file::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+21 added-16 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 }5954This 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::60This configuration binds the application to ``/yourapplication``. If you want61to 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/66.. _cherokee: http://www.cherokee-project.com/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+12 added-33 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/2930Tornado31--------3233`Tornado`_ is an open source version of the scalable, non-blocking web34server and tools that power `FriendFeed`_. Because it is non-blocking and35uses epoll, it can handle thousands of simultaneous standing connections,36which means it is ideal for real-time web services. Integrating this37service with Flask is straightforward::3839 from tornado.wsgi import WSGIContainer40 from tornado.httpserver import HTTPServer41 from tornado.ioloop import IOLoop42 from yourapplication import app4344 http_server = HTTPServer(WSGIContainer(app))45 http_server.listen(5000)46 IOLoop.instance().start()474849.. _Tornado: http://www.tornadoweb.org/50.. _FriendFeed: http://friendfeed.com/5130Gevent31-------3233`Gevent`_ is a coroutine-based Python networking library that uses56`greenlet`_ to provide a high-level synchronous API on top of `libevent`_34`greenlet`_ to provide a high-level synchronous API on top of `libev`_35event loop::3637 from gevent.wsgi import WSGIServer38 from yourapplication import app
1 unmodified line
40 http_server = WSGIServer(('', 5000), app)41 http_server.serve_forever()4243.. _Gevent: http://www.gevent.org/66.. _greenlet: http://greenlet.readthedocs.org/en/latest/67.. _libevent: http://monkey.org/~provos/libevent/44.. _greenlet: https://greenlet.readthedocs.io/en/latest/45.. _libev: http://software.schmorp.de/pkg/libev.html4647Twisted Web48-----------49
23 unmodified lines
73------------7475If you deploy your application using one of these servers behind an HTTP proxy76you will need to rewrite a few headers in order for the application to work.99The two problematic values in the WSGI environment usually are `REMOTE_ADDR`100and `HTTP_HOST`. You can configure your httpd to pass these headers, or you77The two problematic values in the WSGI environment usually are ``REMOTE_ADDR``78and ``HTTP_HOST``. You can configure your httpd to pass these headers, or you79can fix them in middleware. Werkzeug ships a fixer that will solve some common80setups, but you might want to write your own WSGI middleware for specific81setups.82
13 unmodified lines
96 location / {97 proxy_pass http://127.0.0.1:8000/;98 proxy_redirect off;99122 proxy_set_header Host $host;123 proxy_set_header X-Real-IP $remote_addr;124 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;100 proxy_set_header Host $host;101 proxy_set_header X-Real-IP $remote_addr;102 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;103 proxy_set_header X-Forwarded-Proto $scheme;104 }105 }106107If your httpd is not providing these headers, the most common setup invokes the129host being set from `X-Forwarded-Host` and the remote address from130`X-Forwarded-For`::108host being set from ``X-Forwarded-Host`` and the remote address from109``X-Forwarded-For``::110111 from werkzeug.contrib.fixers import ProxyFix112 app.wsgi_app = ProxyFix(app.wsgi_app)113
21 unmodified lines
modified:docs/patterns/apierrors.rst+2 added-2 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``text/html`` they are emitting is not very useful for API consumers.7:mimetype:`text/html` they are emitting is not very useful for API consumers.89The better solution than using ``abort`` to signal errors for invalid API10usage is to implement your own exception type and install an error handler11for it that produces the errors in the format the user is expecting.
52 unmodified lines
modified:docs/patterns/appdispatch.rst+12 added-12 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.
13 unmodified lines
2930Note 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 debuggger, debugging must be enabled both on34the application and the simple server, here is the "hello world" example with33In order to use the interactive debugger, debugging must be enabled both on34the 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`::62For example you could have your main application run on ``/`` and your63backend interface on ``/backend``::6465 from werkzeug.wsgi import DispatcherMiddleware66 from frontend_app import application as frontend67 from backend_app import application as backend
75 unmodified lines
143Dispatch by Path144----------------145146Dispatching by a path on the URL is very similar. Instead of looking at147the `Host` header to figure out the subdomain one simply looks at the147the ``Host`` header to figure out the subdomain one simply looks at the148request path up to the first slash::149150 from threading import Lock151 from werkzeug.wsgi import pop_path_info, peek_path_info
23 unmodified lines
175 app = self.default_app176 return app(environ, start_response)177178The big difference between this and the subdomain one is that this one179falls back to another application if the creator function returns `None`::179falls back to another application if the creator function returns ``None``::180181 from myapplication import create_app, default_app, get_user_for_prefix182183 def make_app(prefix):
5 unmodified lines
modified:docs/patterns/appfactories.rst+14 added-8 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::65 6566 def create_app(config_filename):67 app = Flask(__name__)68 app.config.from_pyfile(config_filename)69
1 unmodified line
7172But, rather, in model.py (or equivalent)::7374 db = SQLAlchemy()75 7576and in your application.py (or equivalent)::7778 def create_app(config_filename):79 app = Flask(__name__)
2 unmodified lines
82 from yourapplication.model import db83 db.init_app(app)8485Using this design pattern, no application-specific state is stored on the86extension object, so one extension object can be used for multiple apps. 86extension object, so one extension object can be used for multiple apps.87For more information about the design of extensions refer to :doc:`/extensiondev`.8889Using Applications90------------------9192So to use such an application you then have to create the application93first. Here an example `run.py` file that runs such an application::93first in a separate file otherwise the :command:`flask` command won't be able94to find it. Here an example :file:`exampleapp.py` file that creates such95an application::9697 from yourapplication import create_app98 app = create_app('/path/to/config.cfg')97 app.run()99100It can then be used with the :command:`flask` command::101102 export FLASK_APP=exampleapp103 flask run104105Factory Improvements106--------------------107108The factory function from above is not very clever so far, you can improve
8 unmodified lines
modified:docs/patterns/caching.rst+3 added-3 removed
25 unmodified lines
26 from werkzeug.contrib.cache import SimpleCache27 cache = SimpleCache()2829If you want to use memcached, make sure to have one of the memcache modules30supported (you get them from `PyPI <http://pypi.python.org/>`_) and a30supported (you get them from `PyPI <https://pypi.python.org/pypi>`_) and a31memcached server running somewhere. This is how you connect to such an32memcached server then::3334 from werkzeug.contrib.cache import MemcachedCache
8 unmodified lines
43Using a Cache44-------------4546Now how can one use such a cache? There are two very important47operations: :meth:`~werkzeug.contrib.cache.BaseCache.get` and 47operations: :meth:`~werkzeug.contrib.cache.BaseCache.get` and48:meth:`~werkzeug.contrib.cache.BaseCache.set`. This is how to use them:4950To get an item from the cache call51:meth:`~werkzeug.contrib.cache.BaseCache.get` with a string as key name.52If something is in the cache, it is returned. Otherwise that function53will return `None`::53will return ``None``::5455 rv = cache.get('my-item')5657To add items to the cache, use the :meth:`~werkzeug.contrib.cache.BaseCache.set`
12 unmodified lines
modified:docs/patterns/celery.rst+44 added-35 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 ``pip`` or ``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, 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)41 TaskBase = celery.Task42 class ContextTask(TaskBase):43 abstract = True4849 class ContextTask(celery.Task):50 def __call__(self, *args, **kwargs):51 with app.app_context():46 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.6155Minimal Example62An example task63---------------6458With what we have above this is the minimal example of using Celery with59Flask::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)777078 @celery.task()79 def add_together(a, b):80 return a + b8175This task can now be called in the background:82This task can now be called in the background::8377>>> result = add_together.delay(23, 42)78>>> result.wait()796584 result = add_together.delay(23, 42)85 result.wait() # 658681Running the Celery Worker82-------------------------87Run a worker88------------8984Now if you jumped in and already executed the above code you will be85disappointed to learn that your ``.wait()`` will never actually return.86That's because you also need to run celery. You can do that by running87celery 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 package92or 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+64 added-53 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**: `easy_install`, which comes with distribute22 can install other libraries for you. You can also use `pip`_ which23 sooner or later will replace `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`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.30:file:`yourapplication.py` and you are not using a module, but a :ref:`package31<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>`.4751Your setup code always goes into a file named `setup.py` next to your48Your 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.52A basic :file:`setup.py` file for a Flask application looks like this::5359A basic `setup.py` file for a Flask application looks like this::6054 from setuptools import setup5556 setup(57 name='Your Application',
5 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 `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 that101folders like `static` or `templates` are not installed for you. The102reason for this is that distribute does not know which files to add for103you. What you should do, is to create a `MANIFEST.in` file next to your104`setup.py` file. This file lists all the files that should be added to113folders like :file:`static` or :file:`templates` are not installed for you. The114reason 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::118119 recursive-include yourapplication/templates *120 recursive-include yourapplication/static *121110Don't forget that even if you enlist them in your `MANIFEST.in` file, they122Don'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`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: http://pypi.python.org/pypi/distribute165.. _pip: http://pypi.python.org/pypi/pip166.. _distribute_setup.py: http://python-distribute.org/distribute_setup.py176.. _pip: https://pypi.python.org/pypi/pip177.. _Setuptools: https://pypi.python.org/pypi/setuptools
modified:docs/patterns/errorpages.rst+39 added-17 removed
1.. _errorpages:23Custom Error Pages4==================56Flask comes with a handy :func:`~flask.abort` function that aborts a
31 unmodified lines
38 looking for was deleted for all eternity.3940*500 Internal Server Error*41 Usually happens on programming errors or if the server is overloaded.40 A terrible good idea to have a nice page there, because your42 A terribly good idea is to have a nice page there, because your43 application *will* fail sooner or later (see also:44 :ref:`application-errors`).454647Error Handlers48--------------4948An error handler is a function, just like a view function, but it is49called when an error happens and is passed that error. The error is most50likely a :exc:`~werkzeug.exceptions.HTTPException`, but in one case it51can be a different error: a handler for internal server errors will be52passed 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`55decorator and the error code of the exception. Keep in mind that Flask56will *not* set the error code for you, so make sure to also provide the57HTTP 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.6059Here an example implementation for a "404 Page Not Found" exception::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.6465A 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+jinja9271 {% extends "layout.html" %}72 {% block title %}Page Not Found{% endblock %}73 {% block body %}74 <h1>Page Not Found</h1>75 <p>What you were looking for is just not there.76 <p><a href="{{ url_for('index') }}">go somewhere nice</a>77 {% endblock %}93 {% extends "layout.html" %}94 {% block title %}Page Not Found{% endblock %}95 {% block body %}96 <h1>Page Not Found</h1>97 <p>What you were looking for is just not there.98 <p><a href="{{ url_for('index') }}">go somewhere nice</a>99 {% endblock %}
modified:docs/patterns/fabric.rst+32 added-42 removed
13 unmodified lines
1415- Fabric 1.0 has to be installed locally. This tutorial assumes the16 latest version of Fabric.17- The application already has to be a package and requires a working18 `setup.py` file (:ref:`distribute-deployment`).18 :file:`setup.py` file (:ref:`distribute-deployment`).19- In the following example we are using `mod_wsgi` for the remote20 servers. You can of course use your own favourite server there, but21 for this example we chose Apache + `mod_wsgi` because it's very easy22 to setup and has a simple way to reload applications without root
1 unmodified line
2425Creating the first Fabfile26--------------------------2728A fabfile is what controls what Fabric executes. It is named `fabfile.py`28A fabfile is what controls what Fabric executes. It is named :file:`fabfile.py`29and executed by the `fab` command. All the functions defined in that file30will show up as `fab` subcommands. They are executed on one or more31hosts. These hosts can be defined either in the fabfile or on the command32line. In this case we will add them to the fabfile.3334This is a basic first example that has the ability to upload the current35sourcecode to the server and install it into a pre-existing35source code to the server and install it into a pre-existing36virtual environment::3738 from fabric.api import *39
2 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
2 unmodified lines
7273 $ fab pack deploy7475However this requires that our server already has the87``/var/www/yourapplication`` folder created and88``/var/www/yourapplication/env`` to be a virtual environment. Furthermore89are we not creating the configuration or `.wsgi` file on the server. So76:file:`/var/www/yourapplication` folder created and77:file:`/var/www/yourapplication/env` to be a virtual environment. Furthermore78are we not creating the configuration or ``.wsgi`` file on the server. So79how do we bootstrap a new server into our infrastructure?8081This now depends on the number of servers we want to set up. If we just82have one application server (which the majority of applications will
5 unmodified lines
88 $ fab -H newserver.example.com bootstrap8990To setup a new server you would roughly do these steps:911031. Create the directory structure in ``/var/www``::921. Create the directory structure in :file:`/var/www`::9394 $ mkdir /var/www/yourapplication95 $ cd /var/www/yourapplication96 $ virtualenv --distribute env971092. Upload a new `application.wsgi` file to the server and the110 configuration file for the application (eg: `application.cfg`)982. Upload a new :file:`application.wsgi` file to the server and the99 configuration file for the application (eg: :file:`application.cfg`)1001123. Create a new Apache config for `yourapplication` and activate it.113 Make sure to activate watching for changes of the `.wsgi` file so1013. Create a new Apache config for ``yourapplication`` and activate it.102 Make sure to activate watching for changes of the ``.wsgi`` file so103 that we can automatically reload the application by touching it.104 (See :ref:`mod_wsgi-deployment` for more information)105117So now the question is, where do the `application.wsgi` and118`application.cfg` files come from?106So now the question is, where do the :file:`application.wsgi` and107:file:`application.cfg` files come from?108109The WSGI File110-------------111
18 unmodified lines
130The Configuration File131----------------------132133Now as mentioned above, the application will find the correct145configuration file by looking up the `YOURAPPLICATION_CONFIG` environment134configuration file by looking up the ``YOURAPPLICATION_CONFIG`` environment135variable. So we have to put the configuration in a place where the136application will able to find it. Configuration files have the unfriendly137quality of being different on all computers, so you do not version them138usually.139140A popular approach is to store configuration files for different servers141in a separate version control repository and check them out on all142servers. Then symlink the file that is active for the server into the154location where it's expected (eg: ``/var/www/yourapplication``).143location where it's expected (eg: :file:`/var/www/yourapplication`).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
4 unmodified lines
157158Fabric will now connect to all servers and run the commands as written159down in the fabfile. First it will execute pack so that we have our160tarball ready and then it will execute deploy and upload the source code171to all servers and install it there. Thanks to the `setup.py` file we161to all servers and install it there. Thanks to the :file:`setup.py` file we162will automatically pull in the required libraries into our virtual163environment.164165Next Steps
9 unmodified lines
175- You could also put your application code into a repository and check176 out the latest version on the server and then install. That way you177 can also easily go back to older versions.178- hook in testing functionality so that you can deploy to an external189 server and run the testsuite. 179 server and run the test suite.180181Working with Fabric is fun and you will notice that it's quite magical to182type ``fab deploy`` and see your application being deployed automatically183to one or more remote servers.184185196.. _Fabric: http://fabfile.org/186.. _Fabric: http://www.fabfile.org/
modified:docs/patterns/favicon.rst+4 added-4 removed
2 unmodified lines
34A "favicon" is an icon used by browsers for tabs and bookmarks. This helps5to distinguish your website and to give it a unique brand.67A common question is how to add a favicon to a flask application. First, of7A common question is how to add a favicon to a Flask application. First, of8course, you need an icon. It should be 16 × 16 pixels and in the ICO file9format. This is not a requirement but a de-facto standard supported by all10relevant browsers. Put the icon in your static directory as11:file:`favicon.ico`.
7 unmodified lines
1920That's all you need for most browsers, however some really old ones do not21support this standard. The old de-facto standard is to serve this file,22with this name, at the website root. If your application is not mounted at23the root path of the domain you either need to configure the webserver to23the root path of the domain you either need to configure the web server to24serve the icon at the root or if you can't do that you're out of luck. If25however your application is the root you can simply route a redirect::2627 app.add_url_rule('/favicon.ico',
15 unmodified lines
43same.4445The above will serve the icon via your application and if possible it's46better to configure your dedicated web server to serve it; refer to the47webserver's documentation.47web server's documentation.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+33 added-30 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'])
2 unmodified lines
31 app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER3233So first we need a couple of imports. Most should be straightforward, the34:func:`werkzeug.secure_filename` is explained a little bit later. The35`UPLOAD_FOLDER` is where we will store the uploaded files and the36`ALLOWED_EXTENSIONS` is the set of allowed file extensions. Then we add a37URL rule by hand to the application. Now usually we're not doing that, so38why here? The reasons is that we want the webserver (or our development39server) to serve these files for us and so we only need a rule to generate40the URL to these files.35``UPLOAD_FOLDER`` is where we will store the uploaded files and the36``ALLOWED_EXTENSIONS`` is the set of allowed file extensions.3738Why do we limit the extensions that are allowed? You probably don't want39your 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 (see46:ref:`xss`). Also make sure to disallow `.php` files if the server47executes them, but who has PHP installed on his server, right? :)42:ref:`xss`). Also make sure to disallow ``.php`` files if the server43executes 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 \54 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':55 # check if the post request has the file part56 if 'file' not in request.files: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 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):66 filename = secure_filename(file.filename)67 file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))68 return redirect(url_for('uploaded_file',
1 unmodified line
70 return '''71 <!doctype html>72 <title>Upload new File</title>73 <h1>Upload new File</h1>69 <form action="" method=post enctype=multipart/form-data>70 <p><input type=file name=file>71 <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?
12 unmodified lines
9394 filename = "../../../../home/username/.bashrc"9596 Assuming the number of ``../`` is correct and you would join this with92 the `UPLOAD_FOLDER` the user might have the ability to modify a file on97 the ``UPLOAD_FOLDER`` the user might have the ability to modify a file on98 the server's filesystem he or she should not modify. This does require some99 knowledge about how the application looks like, but trust me, hackers100 are patient :)101
1 unmodified line
103104 >>> secure_filename('../../../../home/username/.bashrc')105 'home_username_.bashrc'106102Now one last thing is missing: the serving of the uploaded files. As of103Flask 0.5 we can use a function that does that for us::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_directory114115 @app.route('/uploads/<filename>')
51 unmodified lines
167client asks the server every 5 seconds how much it has transmitted168already. Do you realize the irony? The client is asking for something it169should already know.170163Now there are better solutions to that work faster and more reliable. The164web changed a lot lately and you can use HTML5, Java, Silverlight or Flash165to get a nicer uploading experience on the client side. Look at the166following libraries for some nice examples how to do that:167168- `Plupload <http://www.plupload.com/>`_ - HTML5, Java, Flash169- `SWFUpload <http://www.swfupload.org/>`_ - Flash170- `JumpLoader <http://jumploader.com/>`_ - Java171172171An Easier Solution172------------------173174Now there are better solutions that work faster and are more reliable. There175are JavaScript libraries like jQuery_ that have form plugins to ease the176construction of progress bar.177178Because the common pattern for file uploads exists almost unchanged in all177applications dealing with uploads, there is a Flask extension called178`Flask-Uploads`_ that implements a full fledged upload mechanism with179white and blacklisting of extensions and more.179applications dealing with uploads, there is also a Flask extension called180`Flask-Uploads`_ that implements a full fledged upload mechanism with white and181blacklisting of extensions and more.182183.. _jQuery: https://jquery.com/181.. _Flask-Uploads: http://packages.python.org/Flask-Uploads/184.. _Flask-Uploads: https://pythonhosted.org/Flask-Uploads/
modified:docs/patterns/flashing.rst+8 added-9 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
20 unmodified lines
39 flash('You were successfully logged in')40 return redirect(url_for('index'))41 return render_template('login.html', error=error)4241 if __name__ == "__main__":42 app.run()43And here is the :file:`layout.html` template which does the magic:444445And here the ``layout.html`` template which does the magic:4645.. sourcecode:: html+jinja4647 <!doctype html>48 <title>My Application</title>
7 unmodified lines
56 {% endif %}57 {% endwith %}58 {% block body %}{% endblock %}5962And here the index.html template:60Here is the :file:`index.html` template which inherits from :file:`layout.html`:6162.. sourcecode:: html+jinja6364 {% extends "layout.html" %}
1 unmodified line
66 <h1>Overview</h1>67 <p>Do you want to <a href="{{ url_for('login') }}">log in?</a>68 {% endblock %}6972And of course the login template:70And here is the :file:`login.html` template which also inherits from71:file:`layout.html`:7273.. sourcecode:: html+jinja7475 {% extends "layout.html" %}
1 unmodified line
77 <h1>Login</h1>78 {% if error %}79 <p class=error><strong>Error:</strong> {{ error }}80 {% endif %}82 <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+8 added-8 removed
17 unmodified lines
1819In order to use jQuery, you have to download it first and place it in the20static folder of your application and then ensure it's loaded. Ideally21you have a layout template that is used for all pages where you just have22to add a script statement to the bottom of your `<body>` to load jQuery:22to add a script statement to the bottom of your ``<body>`` to load jQuery:2324.. sourcecode:: html2526 <script type=text/javascript src="{{
37 unmodified lines
64 </script>6566The ``|safe`` is necessary in Flask before 0.10 so that Jinja does not67escape the JSON encoded string with HTML rules. Usually this would be68necessary, but we are inside a `script` block here where different rules68necessary, but we are inside a ``script`` block here where different rules69apply.7071.. admonition:: Information for Pros7273 In HTML the `script` tag is declared `CDATA` which means that entities73 In HTML the ``script`` tag is declared ``CDATA`` which means that entities74 will not be parsed. Everything until ``</script>`` is handled as script.75 This also means that there must never be any ``</`` between the script76 tags. ``|tojson`` is kind enough to do the right thing here and77 escape slashes for you (``{{ "</script>"|tojson|safe }}`` is rendered as
40 unmodified lines
118119The HTML120--------121122Your index.html template either has to extend a `layout.html` template with122Your index.html template either has to extend a :file:`layout.html` template with123jQuery loaded and the `$SCRIPT_ROOT` variable set, or do that on the top.124Here's the HTML code needed for our little application (`index.html`).124Here's the HTML code needed for our little application (:file:`index.html`).125Notice that we also drop the script directly into the HTML here. It is126usually a better idea to have that in a separate script file:127128.. sourcecode:: html
26 unmodified lines
1553. ``element.bind('event', func)`` specifies a function that should run156 when the user clicked on the element. If that function returns157 `false`, the default behavior will not kick in (in this case, navigate158 to the `#` URL).1594. ``$.getJSON(url, data, func)`` sends a `GET` request to `url` and will1594. ``$.getJSON(url, data, func)`` sends a ``GET`` request to `url` and will160 send the contents of the `data` object as query parameters. Once the161 data arrived, it will call the given function with the return value as162 argument. Note that we can use the `$SCRIPT_ROOT` variable here that163 we set earlier.164165If you don't get the whole picture, download the `sourcecode166for this example167<http://github.com/mitsuhiko/flask/tree/master/examples/jqueryexample>`_168from github.167<https://github.com/pallets/flask/tree/master/examples/jqueryexample>`_168from GitHub.
modified:docs/patterns/lazyloading.rst+13 added-8 removed
30 unmodified lines
31 @app.route('/user/<username>')32 def user(username):33 pass3435Then the centralized approach you would have one file with the views36(`views.py`) but without any decorator::35Then, with the centralized approach you would have one file with the views36(:file:`views.py`) but without any decorator::3738 def index():39 pass40
12 unmodified lines
53Loading Late54------------5556So far we only split up the views and the routing, but the module is still57loaded upfront. The trick to actually load the view function as needed.57loaded upfront. The trick is to actually load the view function as needed.58This can be accomplished with a helper class that behaves just like a59function but internally imports the real function on first use::6061 from werkzeug import import_string, cached_property
27 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+7 added-4 removed
18 unmodified lines
1920The default behavior of MongoKit is the declarative one that is based on21common ideas from Django or the SQLAlchemy declarative extension.2223Here an example `app.py` module for your application::23Here an example :file:`app.py` module for your application::2425 from flask import Flask26 from mongokit import Connection, Document27
18 unmodified lines
46MongoDB is schemaless. This means you can modify the data structure from one47insert 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 `app.py`, e.g.)::50Here 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):56 if len(value) <= length:57 return True56 raise Exception('%s must be at most %s characters long' % length)58 # must have %s in error format string to have mongokit place key in there59 raise ValidationError('%s must be at most {} characters long'.format(length))60 return validate6162 class User(Document):63 structure = {
14 unmodified lines
7879This example shows you how to define your schema (named structure), a80validator for the maximum character length and uses a special MongoKit feature81called `use_dot_notation`. Per default MongoKit behaves like a python79dictionary but with `use_dot_notation` set to `True` you can use your82dictionary but with `use_dot_notation` set to ``True`` you can use your83documents like you use models in nearly any other ORM by using dots to84separate between attributes.8586You can insert entries into the database like this:
58 unmodified lines
modified:docs/patterns/packages.rst+51 added-21 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 folder24`yourapplication` inside the existing one and move everything below it.25Then rename `yourapplication.py` to `__init__.py`. (Make sure to delete26all `.pyc` files first, otherwise things would most likely break)28:file:`yourapplication` inside the existing one and move everything below it.29Then rename :file:`yourapplication.py` to :file:`__init__.py`. (Make sure to delete30all ``.pyc`` files first, otherwise things would most likely break)3132You 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 `runserver.py` next to the inner45`yourapplication` folder with the following contents::48a 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:82831. the `Flask` application object creation has to be in the55 `__init__.py` file. That way each module can import it safely and the84 :file:`__init__.py` file. That way each module can import it safely and the85 `__name__` variable will resolve to the correct package.862. all the view functions (the ones with a :meth:`~flask.Flask.route`58 decorator on top) have to be imported in the `__init__.py` file.87 decorator on top) have to be imported in the :file:`__init__.py` file.88 Not the object itself, but the module it is in. Import the view module89 **after the application object is created**.9062Here's an example `__init__.py`::91Here's an example :file:`__init__.py`::9293 from flask import Flask94 app = Flask(__name__)9596 import yourapplication.views9769And this is what `views.py` would look like::98And this is what :file:`views.py` would look like::99100 from yourapplication import app101102 @app.route('/')
2 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
2 unmodified lines
121.. admonition:: Circular Imports122123 Every Python programmer hates them, and yet we just added some:124 circular imports (That's when two modules depend on each other. In this96 case `views.py` depends on `__init__.py`). Be advised that this is a125 case :file:`views.py` depends on :file:`__init__.py`). Be advised that this is a126 bad idea in general but here it is actually fine. The reason for this is98 that we are not actually using the views in `__init__.py` and just127 that we are not actually using the views in :file:`__init__.py` and just128 ensuring the module is imported and we are doing that at the bottom of129 the file.130131 There are still some problems with that approach but if you want to use
1 unmodified line
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+12 added-12 removed
18 unmodified lines
19there is a Flask extension that handles that for you. This is recommended20if you want to get started quickly.2122You can download `Flask-SQLAlchemy`_ from `PyPI23<http://pypi.python.org/pypi/Flask-SQLAlchemy>`_.23<https://pypi.python.org/pypi/Flask-SQLAlchemy>`_.2425.. _Flask-SQLAlchemy: http://packages.python.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 `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
28 unmodified lines
69 @app.teardown_appcontext70 def shutdown_session(exception=None):71 db_session.remove()7273Here is an example model (put this into `models.py`, e.g.)::73Here is an example model (put this into :file:`models.py`, e.g.)::7475 from sqlalchemy import Column, Integer, String76 from yourapplication.database import Base77
29 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://www.sqlalchemy.org/docs/orm/extensions/declarative.html113 https://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/114115Manual Object Relational Mapping116--------------------------------117
3 unmodified lines
121flexible but a little more to type. In general it works like the122declarative approach, so make sure to also split up your application into123multiple modules in a package.124125Here is an example `database.py` module for your application::125Here is an example :file:`database.py` module for your application::126127 from sqlalchemy import create_engine, MetaData128 from sqlalchemy.orm import scoped_session, sessionmaker129
4 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
1 unmodified line
144 @app.teardown_appcontext145 def shutdown_session(exception=None):146 db_session.remove()147148Here is an example table and model (put this into `models.py`)::148Here is an example table and model (put this into :file:`models.py`)::149150 from sqlalchemy import Table, Column, Integer, String151 from sqlalchemy.orm import mapper152 from yourapplication.database import metadata, db_session
23 unmodified lines
176177If you just want to use the database system (and SQL) abstraction layer178you basically only need the engine::179180 from sqlalchemy import create_engine, MetaData180 from sqlalchemy import create_engine, MetaData, Table181182 engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)183 metadata = MetaData(bind=engine)184185Then you can either declare the tables in your code like in the examples186above, or automatically load them::187188 from sqlalchemy import Table189 189190 users = Table('users', metadata, autoload=True)191192To insert data you can use the `insert` method. We have to get a193connection first so that we can use a transaction:
20 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://sqlalchemy.org/>`_.218`website <https://www.sqlalchemy.org/>`_.
modified:docs/patterns/sqlite3.rst+36 added-20 removed
1 unmodified line
23Using SQLite 3 with Flask4=========================56In Flask you can implement the opening of database connections on demand7and closing it when the context dies (usually at the end of the request)8easily.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::1112 import sqlite3
12 unmodified lines
25 db = getattr(g, '_database', None)26 if db is not None:27 db.close()2829All the application needs to do in order to now use the database is having30an active application context (which is always true if there is an request31in flight) or to create an application context itself. At that point the32``get_db`` function can be used to get the current database connection.33Whenever the context is destroyed the database connection will be34terminated.29Now, to use the database, the application must either have an active30application context (which is always true if there is a request in flight)31or create an application context itself. At that point the ``get_db``32function can be used to get the current database connection. Whenever the33context is destroyed the database connection will be terminated.3435Note: if you use Flask 0.9 or older you need to use36``flask._app_ctx_stack.top`` instead of ``g`` as the :data:`flask.g`37object was bound to the request and not application context.
16 unmodified lines
54Connect on Demand55-----------------5657The upside of this approach (connecting on first use) is that this will59only opening the connection if truly necessary. If you want to use this58only open the connection if truly necessary. If you want to use this59code outside a request context you can use it in a Python shell by opening60the application context by hand::6162 with app.app_context():
6 unmodified lines
6970Now 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 returned74from the database to convert the result. For instance in order to get75dictionaries instead of tuples this could be inserted into ``get_db``::73from the database to convert the result. For instance, in order to get74dictionaries 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_dicts8283Or 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 M10287Additionally it is a good idea to provide a query function that combines103Additionally, it is a good idea to provide a query function that combines104getting the cursor, executing and fetching the results::89 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 rv11196This handy little function in combination with a row factory makes working97with the database much more pleasant than it is by just using the raw98cursor and connection objects.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::117118 for user in query_db('select * from users'):
11 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 Injections118<http://en.wikipedia.org/wiki/SQL_injection>`_.134<https://en.wikipedia.org/wiki/SQL_injection>`_.135136Initial Schemas137---------------138
8 unmodified lines
147 with app.open_resource('schema.sql', mode='r') as f:148 db.cursor().executescript(f.read())149 db.commit()150135You can then create such a database from the python shell:151You can then create such a database from the Python shell:152153>>> from yourapplication import init_db154>>> init_db()
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/templateinheritance.rst+1 added-1 removed
12 unmodified lines
1314Base Template15-------------1617This template, which we'll call ``layout.html``, defines a simple HTML skeleton17This template, which we'll call :file:`layout.html`, defines a simple HTML skeleton18document that you might use for a simple two-column page. It's the job of19"child" templates to fill the empty blocks with content:2021.. sourcecode:: html+jinja
49 unmodified lines
modified:docs/patterns/viewdecorators.rst+31 added-27 removed
1View Decorators2===============34Python has a really interesting feature called function decorators. This5allow some really neat things for web applications. Because each view in6Flask is a function decorators can be used to inject additional5allows some really neat things for web applications. Because each view in6Flask is a function, decorators can be used to inject additional7functionality to one or more functions. The :meth:`~flask.Flask.route`8decorator is the one you probably used already. But there are use cases9for implementing your own decorator. For instance, imagine you have a10view that should only be used by people that are logged in to. If a user10view that should only be used by people that are logged in. If a user11goes to the site and is not logged in, they should be redirected to the12login page. This is a good example of a use case where a decorator is an13excellent solution.1415Login 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 and60because of that you would like to cache the generated results for a61certain amount of time. A decorator would be nice for that. We're62assuming you have set up a cache like mentioned in :ref:`caching-pattern`.6357Here an example cache function. It generates the cache key from a64Here is an example cache function. It generates the cache key from a65specific prefix (actually a format string) and the current path of the66request. Notice that we are using a function that first creates the67decorator that then decorates the function. Sounds awful? Unfortunately68it is a little bit more complex, but the code should still be
57 unmodified lines
126As you can see, if no template name is provided it will use the endpoint127of the URL map with dots converted to slashes + ``'.html'``. Otherwise128the provided template name is used. When the decorated function returns,129the dictionary returned is passed to the template rendering function. If123`None` is returned, an empty dictionary is assumed, if something else than130``None`` is returned, an empty dictionary is assumed, if something else than131a dictionary is returned we return it from the function unchanged. That132way you can still use the redirect function or return simple strings.133127Here the code for that decorator::134Here is the code for that decorator::135136 from functools import wraps130 from flask import request137 from flask import request, render_template138139 def templated(template=None):140 def decorator(f):141 @wraps(f)
15 unmodified lines
157Endpoint Decorator158------------------159160When you want to use the werkzeug routing system for more flexibility you154need to map the endpoint as defined in the :class:`~werkzeug.routing.Rule` 155to a view function. This is possible with this decorator. For example:: 161need to map the endpoint as defined in the :class:`~werkzeug.routing.Rule`162to a view function. This is possible with this decorator. For example::163164 from flask import Flask165 from werkzeug.routing import Rule166160 app = Flask(__name__) 161 app.url_map.add(Rule('/', endpoint='index')) 167 app = Flask(__name__)168 app.url_map.add(Rule('/', endpoint='index'))169163 @app.endpoint('index') 164 def my_index(): 165 return "Hello world" 166167168170 @app.endpoint('index')171 def my_index():172 return "Hello world"
modified:docs/patterns/wtforms.rst+28 added-28 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.910When you are working with WTForms you have to define your forms as classes11first. I recommend breaking up the application into multiple modules 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 <http://pypi.python.org/pypi/Flask-WTF>`_.20 <https://pypi.python.org/pypi/Flask-WTF>`_.2122.. _Flask-WTF: http://packages.python.org/Flask-WTF/22.. _Flask-WTF: https://flask-wtf.readthedocs.io/en/stable/2324The Forms25---------2627This is an example form for a typical registration page::2829 from wtforms import Form, BooleanField, TextField, PasswordField, validators29 from wtforms import Form, BooleanField, StringField, PasswordField, validators3031 class RegistrationForm(Form):32 username = TextField('Username', [validators.Length(min=4, max=25)])33 email = TextField('Email Address', [validators.Length(min=6, max=35)])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`.64 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.7980Here's an example `_formhelpers.html` template with such a macro:80Here's an example :file:`_formhelpers.html` template with such a macro:8182.. sourcecode:: html+jinja8384 {% macro render_field(field) %}
9 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 escaped103with the `|safe` filter.102strings, so we have to tell Jinja2 that this data is already HTML-escaped103with the ``|safe`` filter.104105Here the `register.html` template for the function we used above which106takes advantage of the `_formhelpers.html` template:105Here 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.simplecodes.com/126.. _WTForms website: http://wtforms.simplecodes.com/125.. _WTForms: https://wtforms.readthedocs.io/126.. _WTForms website: https://wtforms.readthedocs.io/
modified:docs/tutorial/css.rst+3 added-3 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 `style.css` in the `static`8folder we created before:7application. Just create a stylesheet called :file:`style.css` in the8:file:`static` folder:910.. sourcecode:: css1112 body { font-family: sans-serif; background: #eee; }
19 unmodified lines
modified:docs/tutorial/dbcon.rst+23 added-26 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. So how can we elegantly do that with Flask?6You currently have a function for establishing a database connection with7`connect_db`, but by itself, it is not particularly useful. Creating and8closing database connections all the time is very inefficient, so you will9need to keep it around for longer. Because database connections10encapsulate a transaction, you will need to make sure that only one11request at a time uses the connection. An elegant way to do this is by12utilizing the *application context*.1313This is where the application context comes into play. So let's start14there.1516Flask provides us with two contexts: the application context and the17request context. For the time being all you have to know is that there18are special variables that use these. For instance the14Flask provides two contexts: the *application context* and the15*request context*. For the time being, all you have to know is that there16are special variables that use these. For instance, the17:data:`~flask.request` variable is the request object associated with18the 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.19variable associated with the current application context. The tutorial20will cover some more details of this later on.2124For the time being all you have to know is that you can store information22For the time being, all you have to know is that you can store information23safely on the :data:`~flask.g` object.2425So when do you put it on there? To do that you can make a helper28function. The first time the function is called it will create a database29connection for the current context and successive calls will return the26function. The first time the function is called, it will create a database27connection for the current context, and successive calls will return the28already established connection::2930 def get_db():31 """Opens a new database connection if there is none yet for the
2 unmodified lines
34 if not hasattr(g, 'sqlite_db'):35 g.sqlite_db = connect_db()36 return g.sqlite_db374041So now we know how to connect, but how do we properly disconnect? For42that flask provides us with the :meth:`~flask.Flask.teardown_appcontext`38Now you know how to connect, but how can you properly disconnect? For39that, Flask provides us with the :meth:`~flask.Flask.teardown_appcontext`40decorator. It's executed every time the application context tears down::4142 @app.teardown_appcontext43 def close_db(error):
1 unmodified line
45 if hasattr(g, 'sqlite_db'):46 g.sqlite_db.close()4748Functions marked with :meth:`~flask.Flask.teardown_appcontext` are called52every time the app context tears down. So what does this mean?53Essentially the app context is created before the request comes in and is54destroyed (teared down) whenever the request finishes. A teardown can49every time the app context tears down. What does this mean?50Essentially, the app context is created before the request comes in and is51destroyed (torn down) whenever the request finishes. A teardown can52happen because of two reasons: either everything went well (the error56parameter will be `None`) or an exception happend in which case the error53parameter will be ``None``) or an exception happened, in which case the error54is passed to the teardown function.5556Curious about what these contexts mean? Have a look at the57:ref:`app-context` documentation to learn more.
13 unmodified lines
71 into a single Python module. You don't have to, and if your app :ref:`grows72 larger <larger-applications>`, it's a good idea not to.7374.. _example source:78 http://github.com/mitsuhiko/flask/tree/master/examples/flaskr/75 https://github.com/pallets/flask/tree/master/examples/flaskr/
modified:docs/tutorial/dbinit.rst+42 added-38 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. So9before starting the server for the first time it's important to create8systems 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 the12Such a schema can 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 also19require that we provide the path to the database which can introduce17The downside of this is that it requires the ``sqlite3`` command to be18installed, which is not necessarily the case on every system. This also19requires that you 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.21for you, to the application.2223To do this we can create a function called `init_db` that initializes the24database. Let me show you the code first. Just add this function below25the `connect_db` function in `flaskr.py`::23To do this, you can create a function and hook it into a :command:`flask`24command that initializes the database. For now just take a look at the25code segment below. A good place to add this function, and command, is26just below the `connect_db` function in :file:`flaskr.py`::2728 def init_db():28 with app.app_context():29 db = get_db()30 with app.open_resource('schema.sql', mode='r') as f:31 db.cursor().executescript(f.read())32 db.commit()29 db = get_db()30 with app.open_resource('schema.sql', mode='r') as f:31 db.cursor().executescript(f.read())32 db.commit()3334So what's happening here? Remember how we learned last chapter that the35application context is created every time a request comes in? Here we36don't have a request yet, so we need to create the application context by37hand. Without an application context the :data:`~flask.g` object does not38know yet to which application it becomes as there could be more than one!34 @app.cli.command('initdb')35 def initdb_command():36 """Initializes the database."""37 init_db()38 print('Initialized the database.')3940The ``with app.app_context()`` statement establishes the application41context for us. In the body of the with statement the :data:`~flask.g`42object will be associated with ``app``. At the end of the with statement43the association is released and all teardown functions are executed. This44means that our database connection is disconnected after the commit.40The ``app.cli.command()`` decorator registers a new command with the41:command:`flask` script. When the command executes, Flask will automatically42create an application context which is bound to the right application.43Within the function, you can then access :attr:`flask.g` and other things as44you might expect. When the script ends, the application context tears down45and the database connection is released.4647You will want to keep an actual function around that initializes the database,48though, so that we can easily create databases in unit tests later on. (For49more information see :ref:`testing`.)5051The :func:`~flask.Flask.open_resource` method of the application object52is a convenient helper function that will open a resource that the53application provides. This function opens a file from the resource49location (your `flaskr` folder) and allows you to read from it. We are50using this here to execute a script on the database connection.54location (the :file:`flaskr/flaskr` folder) and allows you to read from it.55It is used in this example to execute a script on the database connection.5652The connection object provided by SQLite can give us a cursor object.53On that cursor there is a method to execute a complete script. Finally we54only have to commit the changes. SQLite 3 and other transactional57The connection object provided by SQLite can give you a cursor object.58On that cursor, there is a method to execute a complete script. Finally, you59only have to commit the changes. SQLite3 and other transactional60databases will not commit unless you explicitly tell it to.6157Now it is possible to create a database by starting up a Python shell and58importing and calling that function::62Now, it is possible to create a database with the :command:`flask` script::6360>>> from flaskr import init_db61>>> init_db()64 flask initdb65 Initialized the database.6667.. admonition:: Troubleshooting6865 If you get an exception later that a table cannot be found check that66 you did call the `init_db` function and that your table names are67 correct (singular vs. plural for example).69 If you get an exception later on stating that a table cannot be found, check70 that you did execute the ``initdb`` command and that your table names are71 correct (singular vs. plural, for example).7273Continue with :ref:`tutorial-views`
modified:docs/tutorial/folders.rst+16 added-12 removed
1 unmodified line
23Step 0: Creating The Folders4============================56Before we get started, let's create the folders needed for this6Before getting started, you will need to create the folders needed for this7application::89 /flaskr10 /flaskr10 /static11 /templates11 /static12 /templates1313The `flaskr` folder is not a python package, but just something where we14drop our files. We will then put our database schema as well as main module15into this folder. It is done in the following way. The files inside16the `static` folder are available to users of the application via `HTTP`.17This is the place where css and javascript files go. Inside the18`templates` folder Flask will look for `Jinja2`_ templates. The19templates you create later in the tutorial will go in this directory.14The application will be installed and run as Python package. This is the15recommended way to install and run Flask applications. You will see exactly16how to run ``flaskr`` later on in this tutorial. For now go ahead and create17the applications directory structure. In the next few steps you will be18creating the database schema as well as the main module.1921Continue with :ref:`tutorial-schema`.20As a quick side note, the files inside of the :file:`static` folder are21available to users of the application via HTTP. This is the place where CSS and22JavaScript files go. Inside the :file:`templates` folder, Flask will look for23`Jinja2`_ templates. You will see examples of this later on.2425For now you should continue with :ref:`tutorial-schema`.2623.. _Jinja2: http://jinja.pocoo.org/2/27.. _Jinja2: http://jinja.pocoo.org/
modified:docs/tutorial/index.rst+6 added-5 removed
2 unmodified lines
3Tutorial4========56You want to develop an application with Python and Flask? Here you have7the chance to learn that by example. In this tutorial we will create a8simple microblog application. It only supports one user that can create7the 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 database which comes out of the box with Python, so there is nothing11as a database (which comes out of the box with Python) so there is nothing12else you need.1314If you want the full sourcecode in advance or for comparison, check out14If you want the full source code in advance or for comparison, check out15the `example source`_.1617.. _example source:18 http://github.com/mitsuhiko/flask/tree/master/examples/flaskr/18 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+13 added-12 removed
1 unmodified line
23Introducing Flaskr4==================56We will call our blogging application flaskr here, feel free to choose a7less web-2.0-ish name ;) Basically 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:991. let the user sign in and out with credentials specified in the101. Let the user sign in and out with credentials specified in the11 configuration. Only one user is supported.112. when the user is logged in they can add new entries to the page122. When the user is logged in, they can add new entries to the page13 consisting of a text-only title and some HTML for the text. This HTML14 is not sanitized because we trust the user here.143. the page shows all entries so far in reverse order (newest on top) and15 the user can add new ones from there if logged in.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 that application because it's good18enough for an application of that size. For larger applications however19it makes a lot of sense to use `SQLAlchemy`_ that handles database20connections in a more intelligent way, allows you to target different18SQLite3 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 from the final application:25Here 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+108 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 involves 13creating two new files; :file:`setup.py` and :file:`MANIFEST.in` in the 14projects root directory. You also need to add an :file:`__init__.py` 15file to make the :file:`flaskr/flaskr` directory a package. After these 16changes, your code structure should be::1718 /flaskr19 /flaskr20 __init__.py21 /static22 /templates23 flaskr.py24 schema.sql25 setup.py26 MANIFEST.in2728The content of the ``setup.py`` file for ``flaskr`` is:2930.. sourcecode:: python3132 from setuptools import setup3334 setup(35 name='flaskr',36 packages=['flaskr'],37 include_package_data=True,38 install_requires=[39 'flask',40 ],41 )4243When using setuptools, it is also necessary to specify any special files44that should be included in your package (in the :file:`MANIFEST.in`).45In this case, the static and templates directories need to be included,46as well as the schema. Create the :file:`MANIFEST.in` and add the47following lines::4849 graft flaskr/templates50 graft flaskr/static51 include flaskr/schema.sql5253To simplify locating the application, add the following import statement 54into this file, :file:`flaskr/__init__.py`:5556.. sourcecode:: python5758 from .flaskr import app5960This import statement brings the application instance into the top-level 61of the application package. When it is time to run the application, the 62Flask development server needs the location of the app instance. This 63import statement simplifies the location process. Without it the export 64statement a few steps below would need to be 65``export FLASK_APP=flaskr.flaskr``.6667At this point you should be able to install the application. As usual, it68is recommended to install your Flask application within a `virtualenv`_.69With that said, go ahead and install the application with::7071 pip install --editable .7273The above installation command assumes that it is run within the projects 74root directory, `flaskr/`. The `editable` flag allows editing 75source code without having to reinstall the Flask app each time you make 76changes. The flaskr app is now installed in your virtualenv (see output 77of ``pip freeze``).7879With that out of the way, you should be able to start up the application.80Do this with the following commands::8182 export FLASK_APP=flaskr83 export FLASK_DEBUG=true84 flask run8586(In case you are on Windows you need to use `set` instead of `export`).87The :envvar:`FLASK_DEBUG` flag enables or disables the interactive debugger.88*Never leave debug mode activated in a production system*, because it will89allow users to execute code on the server!9091You will see a message telling you that server has started along with92the address at which you can access it.9394When you head over to the server in your browser, you will get a 404 error95because we don't have any views yet. That will be addressed a little later,96but first, you should get the database working.9798.. admonition:: Externally Visible Server99100 Want your server to be publicly available? Check out the101 :ref:`externally visible server <public-server>` section for more102 information.103104Continue with :ref:`tutorial-dbcon`.105106.. _Click: http://click.pocoo.org107.. _Python Packaging Guide: https://packaging.python.org108.. _virtualenv: https://virtualenv.pypa.io
modified:docs/tutorial/schema.rst+7 added-7 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;14 create table entries (15 id integer primary key autoincrement,16 title text not null,17 text text not null17 'text' text not null18 );1920This schema consists of a single table called `entries` and each row in21this table has an `id`, a `title` and a `text`. The `id` is an20This 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.2425Continue with :ref:`tutorial-setup`.
modified:docs/tutorial/setup.rst+41 added-63 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 flask folder.8We 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. However11a cleaner solution would be to create a separate `.ini` or `.py` file and12load that or import the values from there.6Now that the schema is in place, you can create the application module,7:file:`flaskr.py`. This file should be placed inside of the8:file:`flaskr/flaskr` folder. The first several lines of code in the9application module are the needed import statements. After that there will be a10few lines of configuration code. For small applications like ``flaskr``, it is11possible to drop the configuration directly into the module. However, a cleaner12solution is to create a separate ``.ini`` or ``.py`` file, load that, and13import the values from there.1414First we add the imports in `flaskr.py`::15Here are the import statements (in :file:`flaskr.py`)::1617 # all the imports18 import os19 import sqlite320 from flask import Flask, request, session, g, redirect, url_for, abort, \21 render_template, flash2222Next we can create our actual application and initialize it with the23config from the same file, in `flaskr.py`::23The next couple lines will create the actual application instance and24initialize it with the config from the same file in :file:`flaskr.py`:2525 # create our little application :)26 app = Flask(__name__)27 app.config.from_object(__name__)26.. sourcecode:: python2728 app = Flask(__name__) # create the application instance :)29 app.config.from_object(__name__) # load config from this file , flaskr.py3031 # Load default config and override config from an environment variable32 app.config.update(dict(33 DATABASE=os.path.join(app.root_path, 'flaskr.db'),32 DEBUG=True,34 SECRET_KEY='development key',35 USERNAME='admin',36 PASSWORD='default'37 ))38 app.config.from_envvar('FLASKR_SETTINGS', silent=True)3939The :class:`~flask.Config` object works similar to a dictionary so we40can update it with new values.40The :class:`~flask.Config` object works similarly to a dictionary, so it can be41updated with new values.4243.. admonition:: Database Path4445 Operating systems know the concept of a current working directory for45 each process. Unfortunately you cannot depend on this in web46 each process. Unfortunately, you cannot depend on this in web47 applications because you might have more than one application in the48 same process.4950 For this reason the ``app.root_path`` attribute can be used to50 get the path to the application. Together with the ``os.path`` module51 files can then easily be found. In this example we place the51 get the path to the application. Together with the ``os.path`` module,52 files can then easily be found. In this example, we place the53 database right next to it.5454 For a real-work application it's recommended to use55 For a real-world application, it's recommended to use56 :ref:`instance-folders` instead.5757Usually, it is a good idea to load a separate, environment specific58configuration file. Flask allows you to import multiple configurations and it 59will use the setting defined in the last import. This enables robust 60configuration setups. :meth:`~flask.Config.from_envvar` can help achieve this. 61 62 app.config.from_envvar('FLASKR_SETTINGS', silent=True)58Usually, it is a good idea to load a separate, environment-specific59configuration file. Flask allows you to import multiple configurations and it60will use the setting defined in the last import. This enables robust61configuration setups. :meth:`~flask.Config.from_envvar` can help achieve this.6263.. sourcecode:: python6465 app.config.from_envvar('FLASKR_SETTINGS', silent=True)6664Simply define the environment variable :envvar:`FLASKR_SETTINGS` that points to 65a config file to be loaded. The silent switch just tells Flask to not complain 67Simply define the environment variable :envvar:`FLASKR_SETTINGS` that points to68a config file to be loaded. The silent switch just tells Flask to not complain69if no such environment key is set.7068In addition to that you can use the :meth:`~flask.Config.from_object`71In addition to that, you can use the :meth:`~flask.Config.from_object`72method on the config object and provide it with an import name of a70module. Flask will the initialize the variable from that module. Note71that in all cases only variable names that are uppercase are considered.73module. Flask will then initialize the variable from that module. Note74that in all cases, only variable names that are uppercase are considered.7576The ``SECRET_KEY`` is needed to keep the client-side sessions secure.74Choose that key wisely and as hard to guess and complex as possible. The75debug flag enables or disables the interactive debugger. *Never leave76debug mode activated in a production system*, because it will allow users to77execute code on the server!77Choose that key wisely and as hard to guess and complex as possible.7879We will also add a method that allows for easily connecting to the79Lastly, you will add a method that allows for easy connections to the80specified database. This can be used to open a connection on request and81also from the interactive Python shell or a script. This will come in82handy later. We create a simple database connection through SQLite and82handy later. You can create a simple database connection through SQLite and83then tell it to use the :class:`sqlite3.Row` object to represent rows.84This allows us to treat the rows as if they were dictionaries instead of84This allows the rows to be treated as if they were dictionaries instead of85tuples.8687::87.. sourcecode:: python8889 def connect_db():90 """Connects to the specific database."""91 rv = sqlite3.connect(app.config['DATABASE'])92 rv.row_factory = sqlite3.Row93 return rv9495Finally we just add a line to the bottom of the file that fires up the96server if we want to run that file as a standalone application::95In the next section you will see how to run the application.9698 if __name__ == '__main__':99 app.run()100101With that out of the way you should be able to start up the application102without problems. Do this with the following command::103104 python flaskr.py105106You will see a message telling you that server has started along with107the address at which you can access it.108109When you head over to the server in your browser you will get an 404110page not found error because we don't have any views yet. But we will111focus on that a little later. First we should get the database working.112113.. admonition:: Externally Visible Server114115 Want your server to be publicly available? Check out the116 :ref:`externally visible server <public-server>` section for more117 information.118119Continue with :ref:`tutorial-dbcon`.97Continue with :ref:`tutorial-packaging`.
modified:docs/tutorial/templates.rst+15 added-14 removed
1.. _tutorial-templates:23Step 6: The Templates3Step 7: The Templates4=====================56Now we should start working on the templates. If we request the URLs now7we 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 `templates` folder:18Put the following templates into the :file:`templates` folder:1919.. _Jinja2: http://jinja.pocoo.org/2/documentation/templates20.. _Jinja2: http://jinja.pocoo.org/docs/templates2122layout.html23-----------24
30 unmodified lines
5556show_entries.html57-----------------5858This template extends the `layout.html` template from above to display the59messages. 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 `HTTP`62method:59This template extends the :file:`layout.html` template from above to display the60messages. Note that the ``for`` loop iterates over the messages we passed61in with the :func:`~flask.render_template` function. Notice that the form is62configured to submit to the `add_entry` view function and use ``POST`` as63HTTP method:6465.. sourcecode:: html+jinja6667 {% extends "layout.html" %}
10 unmodified lines
78 </form>79 {% endif %}80 <ul class=entries>81 {% for entry in entries %}81 <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}82 <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}</li>83 {% else %}83 <li><em>Unbelievable. No entries here so far</em>84 <li><em>Unbelievable. No entries here so far</em></li>85 {% endfor %}86 </ul>87 {% endblock %}8889login.html90----------9191Finally the login template which basically just displays a form to allow92This is the login template, which basically just displays a form to allow93the user to login:9495.. sourcecode:: html+jinja96
16 unmodified lines
modified:docs/tutorial/testing.rst+87 added-1 removed
4 unmodified lines
56Now that you have finished the application and everything works as7expected, 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 unittesting in the :ref:`testing` section of the9example 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+35 added-16 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:89Show Entries10------------1112This view shows all the entries stored in the database. It listens on the13root of the application and will select title and text from the database.14The 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 using15returned from the cursor look a bit like dictionaries because we are using16the :class:`sqlite3.Row` row factory.1718The view function will pass the entries as dicts to the19`show_entries.html` template and return the rendered one::18The view function will pass the entries to the :file:`show_entries.html`19template and return the rendered one::2021 @app.route('/')22 def show_entries():23 db = get_db()
4 unmodified lines
28Add New Entry29-------------3031This view lets the user add new entries if they are logged in. This only32responds to `POST` requests, the actual form is shown on the33`show_entries` page. If everything worked out well we will32responds to ``POST`` requests; the actual form is shown on the33`show_entries` page. If everything worked out well, it will34:func:`~flask.flash` an information message to the next request and35redirect back to the `show_entries` page::3637 @app.route('/add', methods=['POST'])
6 unmodified lines
44 db.commit()45 flash('New entry was successfully posted')46 return redirect(url_for('show_entries'))4748Note that we check that the user is logged in here (the `logged_in` key is49present in the session and `True`).48Note that this view checks that the user is logged in (that is, if the49`logged_in` key is present in the session and ``True``).5051.. admonition:: Security Note5253 Be sure to use question marks when building SQL statements, as done in the
5 unmodified lines
59----------------6061These functions are used to sign the user in and out. Login checks the62username and password against the ones from the configuration and sets the63`logged_in` key in the session. If the user logged in successfully, that64key is set to `True`, and the user is redirected back to the `show_entries`63`logged_in` key for the session. If the user logged in successfully, that64key is set to ``True``, and the user is redirected back to the `show_entries`65page. In addition, a message is flashed that informs the user that he or66she was logged in successfully. If an error occurred, the template is67notified about that, and the user is asked again::68
10 unmodified lines
79 flash('You were logged in')80 return redirect(url_for('show_entries'))81 return render_template('login.html', error=error)8283The 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` method83The `logout` function, on the other hand, removes that key from the session84again. There is a neat trick here: if you use the :meth:`~dict.pop` method85of the dict and pass a second parameter to it (the default), the method86will 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.87key is not in there. This is helpful because now it is not necessary to88check if the user was logged in.8990::9192 @app.route('/logout')
1 unmodified line
94 session.pop('logged_in', None)95 flash('You were logged out')96 return redirect(url_for('show_entries'))9798.. admonition:: Security Note99100 Passwords should never be stored in plain text in a production101 system. This tutorial uses plain text passwords for simplicity. If you102 plan to release a project based off this tutorial out into the world,103 passwords should be both `hashed and salted`_ before being stored in a104 database or file.105106 Fortunately, there are Flask extensions for the purpose of107 hashing passwords and verifying passwords against hashes, so adding108 this functionality is fairly straight forward. There are also109 many general python libraries that can be used for hashing.110111 You can find a list of recommended Flask extensions112 `here <http://flask.pocoo.org/extensions/>`_113114115Continue with :ref:`tutorial-templates`.116117.. _hashed and salted: https://blog.codinghorror.com/youre-probably-storing-passwords-incorrectly/
modified:docs/advanced_foreword.rst+5 added-19 removed
6 unmodified lines
7----------------------89One of the design decisions in Flask was that simple tasks should be simple;10they should not take a lot of code and yet they should not limit you. Because11of that, Flask has few design choices that some people might find surprising or11of that, Flask has a few design choices that some people might find surprising or12unorthodox. For example, Flask uses thread-local objects internally so that you13don’t have to pass objects around from function to function within a request in14order to stay threadsafe. This approach is convenient, but requires a valid15request context for dependency injection or when attempting to reuse code which
29 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.6 and 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+190 added-110 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:: url43 .. attribute:: base_url44 .. attribute:: url_root4594 Provides different ways to look at the current URL. Imagine your95 application is listening on the following URL::46 Provides different ways to look at the current `IRI47 <http://tools.ietf.org/html/rfc3987>`_. Imagine your application is48 listening on the following application root::4950 http://www.example.com/myapplication5199 And a user requests the following URL::52 And a user requests the following URI::53101 http://www.example.com/myapplication/page.html?x=y54 http://www.example.com/myapplication/%CF%80/page.html?x=y5556 In this case the values of the above mentioned attributes would be57 the following:5859 ============= ======================================================107 `path` ``/page.html``108 `script_root` ``/myapplication``109 `base_url` ``http://www.example.com/myapplication/page.html``110 `url` ``http://www.example.com/myapplication/page.html?x=y``111 `url_root` ``http://www.example.com/myapplication/``60 `path` ``u'/π/page.html'``61 `full_path` ``u'/π/page.html?x=y'``62 `script_root` ``u'/myapplication'``63 `base_url` ``u'http://www.example.com/myapplication/π/page.html'``64 `url` ``u'http://www.example.com/myapplication/π/page.html?x=y'``65 `url_root` ``u'http://www.example.com/myapplication/'``66 ============= ======================================================67114 .. attribute:: is_xhr68116 `True` if the request was triggered via a JavaScript117 `XMLHttpRequest`. This only works with libraries that support the118 ``X-Requested-With`` header and set it to `XMLHttpRequest`.119 Libraries that do that are prototype, jQuery and Mochikit and120 probably some more.69.. attribute:: request70122.. class:: request12371 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
13 unmodified lines
88 :members: set_cookie, data, mimetype8990 .. attribute:: headers91145 A :class:`Headers` object representing the response headers.92 A :class:`~werkzeug.datastructures.Headers` object representing the response headers.9394 .. attribute:: status9596 A string with a response status.
25 unmodified lines
122 The following attributes are interesting:123124 .. attribute:: new125179 `True` if the session is new, `False` otherwise.126 ``True`` if the session is new, ``False`` otherwise.127128 .. attribute:: modified129183 `True` if the session object detected a modification. Be advised130 ``True`` if the session object detected a modification. Be advised131 that modifications on mutable structures are not picked up132 automatically, in that situation you have to explicitly set the186 attribute to `True` yourself. Here an example::133 attribute to ``True`` yourself. Here an example::134135 # this change is not picked up because a mutable object (here136 # a list) is changed.137 session['objects'].append(42)
1 unmodified line
139 session.modified = True140141 .. attribute:: permanent142196 If set to `True` the session lives for143 If set to ``True`` the session lives for144 :attr:`~flask.Flask.permanent_session_lifetime` seconds. The198 default is 31 days. If set to `False` (which is the default) the145 default is 31 days. If set to ``False`` (which is the default) the146 session will be deleted when the user closes the browser.147148149Session Interface
73 unmodified lines
223 is especially useful when combined with the :ref:`faking-resources`224 pattern for testing.225226 Additionally as of 0.10 you can use the :meth:`get` method to280 get an attribute or `None` (or the second argument) if it's not set.227 get an attribute or ``None`` (or the second argument) if it's not set.228 These two usages are now equivalent::229230 user = getattr(flask.g, 'user', None)231 user = flask.g.get('user', None)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_for262313.. function:: abort(code)263.. autofunction:: abort264315 Raises an :exc:`~werkzeug.exceptions.HTTPException` for the given316 status code. For example to abort request handling with a page not317 found exception, you would call ``abort(404)``.318319 :param code: the HTTP error code.320265.. autofunction:: redirect266267.. autofunction:: make_response268
22 unmodified lines
291292.. module:: flask.json293294Flask uses ``simplejson`` for the JSON implementation. Since simplejson351is provided both by the standard library as well as extension Flask will295is provided by both the standard library as well as extension, Flask will296try simplejson first and then fall back to the stdlib json module. On top297of that it will delegate access to the current application's JSON encoders298and decoders for easier customization.299
17 unmodified lines
317 will have that method called and then the return value is serialized318 as string.319320The :func:`~htmlsafe_dumps` function of this json module is also available377as filter called ``|tojson`` in Jinja2. Note that inside `script`321as filter called ``|tojson`` in Jinja2. Note that inside ``script``322tags no escaping must take place, so make sure to disable escaping379with ``|safe`` if you intend to use it inside `script` tags unless323with ``|safe`` if you intend to use it inside ``script`` tags unless324you are using Flask 0.10 which implies that:325326.. sourcecode:: html+jinja327
120 unmodified lines
448449.. autoclass:: flask.blueprints.BlueprintSetupState450 :members:451452.. _core-signals-list:453454Signals455-------456511.. when modifying this list, also update the one in signals.rst512457.. versionadded:: 0.6458515.. data:: signals_available459.. data:: signals.signals_available460517 `True` if the signaling system is available. This is the case461 ``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_started500528 This signal is sent before any request processing started but when the529 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_down544547 This signal is sent when the application is tearing down the request.548 This is always called, even if an error happened. An `exc` keyword549 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.549551 .. versionchanged:: 0.9552 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_down563556 This signal is sent when the application is tearing down the557 application context. This is always called, even if an error happened.558 An `exc` keyword argument is passed with the exception that caused the559 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 sender564 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`.623582 .. versionadded:: 0.10624 Example subscriber::625584.. currentmodule:: None626 recorded = []627 def record(sender, message, category, **extra):628 recorded.append((message, category))629586.. 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.648600.. _blinker: http://pypi.python.org/pypi/blinker649650.. _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`.697698Here are some examples::699700 @app.route('/')701 def index():
54 unmodified lines
756 subdomain is assumed.757`**options` the options to be forwarded to the underlying758 :class:`~werkzeug.routing.Rule` object. A change to759 Werkzeug is handling of method options. methods is a list705 of methods this rule should be limited to (`GET`, `POST`706 etc.). By default a rule just listens for `GET` (and707 implicitly `HEAD`). Starting with Flask 0.6, `OPTIONS` is760 of methods this rule should be limited to (``GET``, ``POST``761 etc.). By default a rule just listens for ``GET`` (and762 implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is763 implicitly added and handled by the standard request764 handling. They have to be specified as keyword arguments.765=============== ==========================================================766
12 unmodified lines
779 will be prefixed with the name of the blueprint by default which780 cannot be customized from the function itself.781782- `methods`: If methods are not provided when the URL rule is added,728 Flask will look on the view function object itself is an `methods`783 Flask will look on the view function object itself if a `methods`784 attribute exists. If it does, it will pull the information for the785 methods from there.786787- `provide_automatic_options`: if this attribute is set Flask will788 either force enable or disable the automatic implementation of the734 HTTP `OPTIONS` response. This can be useful when working with735 decorators that want to customize the `OPTIONS` response on a per-view789 HTTP ``OPTIONS`` response. This can be useful when working with790 decorators that want to customize the ``OPTIONS`` response on a per-view791 basis.792793- `required_methods`: if this attribute is set, Flask will always add794 these methods when registering a URL rule even if the methods were
12 unmodified lines
807 app.add_url_rule('/', index)808809.. versionadded:: 0.8810 The `provide_automatic_options` functionality was added.811812Command Line Interface813----------------------814815.. currentmodule:: flask.cli816817.. autoclass:: FlaskGroup818 :members:819820.. autoclass:: AppGroup821 :members:822823.. autoclass:: ScriptInfo824 :members:825826.. autofunction:: with_appcontext827828.. autofunction:: pass_script_info829830 Marks a function so that an instance of :class:`ScriptInfo` is passed831 as first argument to the click callback.832833.. autodata:: run_command834835.. autodata:: shell_command
modified:docs/appcontext.rst+19 added-14 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`
2 unmodified lines
37Purpose of the Application Context38----------------------------------3940The main reason for the application's context existence is that in the41past a bunch of functionality was attached to the request context in lack42of a better solution. Since one of the pillar's of Flask's design is that41past a bunch of functionality was attached to the request context for lack42of a better solution. Since one of the pillars of Flask's design is that43you can have more than one application in the same Python process.4445So how does the code find the “right” application? In the past we46recommended passing applications around explicitly, but that caused issues47with libraries that were not designed with that in mind.4849A common workaround for that problem was to use the50:data:`~flask.current_app` proxy later on, which was bound to the current51request's application reference. Since however creating such a request52context is an unnecessarily expensive operation in case there is no53request around, the application context was introduced.51request's application reference. Since creating such a request context is52an unnecessarily expensive operation in case there is no request around,53the application context was introduced.5455Creating an Application Context56-------------------------------5758To make an application context there are two ways. The first one is the59implicit one: whenever a request context is pushed, an application context60will be created alongside if this is necessary. As a result of that, you61can ignore the existence of the application context unless you need it.58There are two ways to make an application context. The first one is59implicit: whenever a request context is pushed, an application context60will be created alongside if this is necessary. As a result, you can61ignore the existence of the application context unless you need it.6263The second way is the explicit way using the64:meth:`~flask.Flask.app_context` method::65
7 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
9 unmodified lines
9596Context Usage97-------------9894The context is typically used to cache resources on there that need to be95created on a per-request or usage case. For instance database connects96are destined to go there. When storing things on the application context99The context is typically used to cache resources that need to be created100on a per-request or usage case. For instance, database connections are101destined to go there. When storing things on the application context102unique names should be chosen as this is a place that is shared between103Flask applications and extensions.104105The most common usage is to split resource management into two parts:
33 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 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+55 added-8 removed
1 unmodified line
23Modular Applications with Blueprints4====================================56.. currentmodule:: flask78.. versionadded:: 0.7910Flask uses a concept of *blueprints* for making application components and11supporting common patterns within an application or across applications.
86 unmodified lines
98 [<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>,99 <Rule '/<page>' (HEAD, OPTIONS, GET) -> simple_page.show>,100 <Rule '/' (HEAD, OPTIONS, GET) -> simple_page.show>]101100The first one is obviously from the application ifself for the static102The first one is obviously from the application itself for the static103files. The other two are for the `show` function of the ``simple_page``104blueprint. As you can see, they are also prefixed with the name of the105blueprint and separated by a dot (``.``).106
51 unmodified lines
158159 admin = Blueprint('admin', __name__, static_folder='static')160161By default the rightmost part of the path is where it is exposed on the160web. Because the folder is called ``static`` here it will be available at162web. Because the folder is called :file:`static` here it will be available at163the location of the blueprint + ``/static``. Say the blueprint is164registered for ``/admin`` the static folder will be at ``/admin/static``.165166The endpoint is named `blueprint_name.static` so you can generate URLs to
8 unmodified lines
175the `template_folder` parameter to the :class:`Blueprint` constructor::176177 admin = Blueprint('admin', __name__, template_folder='templates')178177As for static files, the path can be absolute or relative to the blueprint178resource folder. The template folder is added to the searchpath of179templates but with a lower priority than the actual application's template180folder. That way you can easily override templates that a blueprint181provides 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 like186this: ``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::202203 yourpackage/204 blueprints/205 admin/206 templates/207 admin/208 index.html209 __init__.py210211And then when you want to render the template, use :file:`admin/index.html` as212the name to look up the template by. If you encounter problems loading213the correct templates enable the ``EXPLAIN_TEMPLATE_LOADING`` config214variable which will instruct Flask to print out the steps it goes through215to locate templates on every ``render_template`` call.216217Building URLs218-------------219220If you want to link from one page to another you can use the
23 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`.
added:docs/cli.rst+260 added
1.. _cli:23Command Line Interface4======================56.. versionadded:: 0.1178.. currentmodule:: flask910One 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` 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 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`` or34optionally 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``39this is how it can be run.4041Environment variables (On Windows use ``set`` instead of ``export``)::4243 export FLASK_APP=hello44 flask run4546Or with a filename::4748 export FLASK_APP=/path/to/hello.py49 flask run5051Virtualenv 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----------7374The :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::8485 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 the90application. By default you have access to your ``app`` and :data:`g`.9192Custom Commands93---------------9495If you want to add more commands to the shell script you can do this96easily. 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."""108 click.echo('Init the db')109110The command will then show up on the command line::111112 $ flask initdb113 Init the db114115Application Context116-------------------117118Most commands operate on the application so it makes a lot of sense if119they have the application context setup. Because of this, if you register120a callback on ``app.cli`` with the :meth:`~flask.cli.AppGroup.command` the121callback will automatically be wrapped through :func:`cli.with_appcontext`122which informs the cli system to ensure that an application context is set123up. This behavior is not available if a command is added later with124:func:`~click.Group.add_command` or through other means.125126It can also be disabled by passing ``with_appcontext=False`` to the127decorator::128129 @app.cli.command(with_appcontext=False)130 def example():131 pass132133Factory Functions134-----------------135136In case you are using factory functions to create your application (see137: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 instantiates141applications. 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.147148This could be a file named :file:`autoapp.py` with these contents::149150 import os151 from yourapplication import create_app152 app = create_app(os.environ['YOURAPPLICATION_CONFIG'])153154Once 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.py159160From this point onwards :command:`flask` will find your application.161162.. _custom-scripts:163164Custom Scripts165--------------166167While 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 how177click 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.187188To 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 click194 from flask.cli import FlaskGroup195196 def create_wiki_app(info):197 from yourwiki import create_app198 return create_app(199 config=os.environ.get('WIKI_CONFIG', 'wikiconfig.py'))200201 @click.group(cls=FlaskGroup, create_app=create_wiki_app)202 def cli():203 """This is a management script for the wiki application."""204205 if __name__ == '__main__':206 cli()207208That's a lot of code for not much, so let's go through all parts step by209step.2102111. First we import the ``click`` library as well as the click extensions212 from the ``flask.cli`` package. Primarily we are here interested213 in the :class:`~flask.cli.FlaskGroup` click group.2142. The next thing we do is defining a function that is invoked with the215 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 (see218 :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.2264. All is rounded up by invoking the script.227228CLI Plugins229-----------230231Flask 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:236237Example :file:`setup.py`::238239 from setuptools import setup240241 setup(242 name='flask-my-extension',243 ...244 entry_points='''245 [flask.commands]246 my-command=mypackage.commands:cli247 ''',248 )249250Inside :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.
modified:docs/conf.py+87 added-46 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'2014, 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 'http://docs.python.org/dev': None,248 'http://werkzeug.pocoo.org/docs/': None,249 'http://www.sqlalchemy.org/docs/': None,250 'http://wtforms.simplecodes.com/docs/0.5/': None,251 'http://discorporate.us/projects/Blinker/docs/1.1/': 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}275254pygments_style = 'flask_theme_support.FlaskyStyle'255256# fall back if theme is not there276try:277 __import__('flask_theme_support')259except ImportError, e:260 print '-' * 74261 print 'Warning: Flask themes unavailable. Building with default theme'262 print 'If you want the Flask themes, run this command and build again:'263 print264 print ' git submodule update --init'265 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)290267 pygments_style = 'tango'268 html_theme = 'default'269 html_theme_options = {}291292# unwrap decorators293def unwrap_decorators():294 import sphinx.util.inspect as inspect295 import functools296297 old_getargspec = inspect.getargspec298 def getargspec(x):299 return old_getargspec(getattr(x, '_original_function', x))300 inspect.getargspec = getargspec301302 old_update_wrapper = functools.update_wrapper303 def update_wrapper(wrapper, wrapped, *a, **kw):304 rv = old_update_wrapper(wrapper, wrapped, *a, **kw)305 rv._original_function = wrapped306 return rv307 functools.update_wrapper = update_wrapper308309unwrap_decorators()310del unwrap_decorators
modified:docs/config.rst+72 added-43 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 or59 explicitly set to `None` this is60 implicitly true if either `TESTING` or61 `DEBUG` is true.75 explicitly set to ``None`` this is76 implicitly true if either ``TESTING`` or77 ``DEBUG`` is true.78``PRESERVE_CONTEXT_ON_EXCEPTION`` By default if the application is in79 debug mode the request context is not80 popped on exceptions to enable debuggers81 to introspect the data. This can be
13 unmodified lines
95 for all of ``APPLICATION_ROOT`` or if96 that is not set for ``'/'``.97``SESSION_COOKIE_HTTPONLY`` controls if the cookie should be set98 with the httponly flag. Defaults to83 `True`.99 ``True``.100``SESSION_COOKIE_SECURE`` controls if the cookie should be set101 with the secure flag. Defaults to86 `False`.102 ``False``.103``PERMANENT_SESSION_LIFETIME`` the lifetime of a permanent session as104 :class:`datetime.timedelta` object.105 Starting with Flask 0.8 this can also be106 an integer representing seconds.107``SESSION_REFRESH_EACH_REQUEST`` this flag controls how permanent92 sessions are refreshed. If set to `True`108 sessions are refreshed. If set to ``True``109 (which is the default) then the cookie110 is refreshed each request which111 automatically bumps the lifetime. If96 set to `False` a `set-cookie` header is112 set to ``False`` a `set-cookie` header is113 only sent if the session is modified.114 Non permanent sessions are not affected115 by this.116``USE_X_SENDFILE`` enable/disable x-sendfile117``LOGGER_NAME`` the name of the logger118``LOGGER_HANDLER_POLICY`` the policy of the default logging119 handler. The default is ``'always'``120 which means that the default logging121 handler is always active. ``'debug'``122 will only activate logging in debug123 mode, ``'production'`` will only log in124 production and ``'never'`` disables it125 entirely.126``SERVER_NAME`` the name and port number of the server.127 Required for subdomain support (e.g.:128 ``'myapp.dev:5000'``) Note that129 localhost does not support subdomains so
1 unmodified line
131 help. Setting a ``SERVER_NAME`` also132 by default enables URL generation133 without a request context but with an134 application context.111``APPLICATION_ROOT`` If the application does not occupy112 a whole domain or subdomain this can113 be set to the path where the application114 is configured to live. This is for115 session cookie as path value. If116 domains are used, this should be117 ``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.122``SEND_FILE_MAX_AGE_DEFAULT``: Default cache control max age to use with146``SEND_FILE_MAX_AGE_DEFAULT`` Default cache control max age to use with147 :meth:`~flask.Flask.send_static_file` (the148 default static file handler) and125 :func:`~flask.send_file`, in126 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 the171 cost of cachability.172``JSONIFY_PRETTYPRINT_REGULAR`` If this is set to ``True`` (the default)173 jsonify responses will be pretty printed174 if they are not requested by an175 XMLHttpRequest object (controlled by176 the ``X-Requested-With`` header)177``TEMPLATES_AUTO_RELOAD`` Flask checks if template was modified each178 time it is requested and reloads it if179 necessary. But disk I/O is costly and it may180 be viable to disable this feature by setting181 this key to ``False``. This option does not182 affect debug mode.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 checks205 original file only in debug mode.206``EXPLAIN_TEMPLATE_LOADING`` If this is enabled then every attempt to207 load a template will write an info208 message to the logger explaining the209 attempts to locate the template. This210 can be useful to figure out why211 templates cannot be found or wrong212 templates appear to be loaded.213================================= =========================================214215.. admonition:: More on ``SERVER_NAME``216
6 unmodified lines
223 what subdomains are, your web browser does as well. Most modern web224 browsers will not allow cross-subdomain cookies to be set on a225 server name without dots in it. So if your server name is226 ``'localhost'`` you will not be able to set a cookie for197 ``'localhost'`` and every subdomain of it. Please chose a different227 ``'localhost'`` and every subdomain of it. Please choose a different228 server name in that case, like ``'myapplication.local'`` and add229 this name + the subdomains you want to use into your host config230 or setup a local `bind`_.231202.. _bind: https://www.isc.org/software/bind232.. _bind: https://www.isc.org/downloads/bind/233234.. versionadded:: 0.4235 ``LOGGER_NAME``236
17 unmodified lines
254255.. versionadded:: 0.10256 ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_PRETTYPRINT_REGULAR``257228.. versionadded:: 1.0229 ``SESSION_REFRESH_EACH_REQUEST``258.. versionadded:: 0.11259 ``SESSION_REFRESH_EACH_REQUEST``, ``TEMPLATES_AUTO_RELOAD``,260 ``LOGGER_HANDLER_POLICY``, ``EXPLAIN_TEMPLATE_LOADING``261231.. versionadded:: 1.0232 ``TEMPLATES_AUTO_RELOAD``233262Configuring from Files263----------------------264265Configuration becomes more useful if you can store it in a separate file,
48 unmodified lines
314a little harder. There is no single 100% solution for this problem in315general, but there are a couple of things you can keep in mind to improve316that experience:3172901. create your application in a function and register blueprints on it.3181. Create your application in a function and register blueprints on it.319 That way you can create multiple instances of your application with320 different configurations attached which makes unittesting a lot321 easier. You can use this to pass in configuration as needed.3223232. 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
7 unmodified lines
339 app = Flask(__name__)340 app.config.from_object('yourapplication.default_settings')341 app.config.from_envvar('YOURAPPLICATION_SETTINGS')342314Then you just have to add a separate `config.py` file and export343Then you just have to add a separate :file:`config.py` file and export344``YOURAPPLICATION_SETTINGS=/path/to/config.py`` and you are done. However345there 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 in320the 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.
22 unmodified lines
376377There are many different ways and it's up to you how you want to manage378your configuration files. However here a list of good recommendations:379351- keep a default configuration in version control. Either populate the380- Keep a default configuration in version control. Either populate the381 config with this default configuration or import it in your own382 configuration files before overriding values.354- use an environment variable to switch between the configurations.383- Use an environment variable to switch between the configurations.384 This can be done from outside the Python interpreter and makes385 development and deployment much easier because you can quickly and386 easily switch between different configs without having to touch the387 code at all. If you are working often on different projects you can
3 unmodified lines
391 configurations separately to the production server(s). For some392 details about how to do that, head over to the393 :ref:`fabric-deployment` pattern.394366.. _fabric: http://fabfile.org/395.. _fabric: http://www.fabfile.org/396397398.. _instance-folders:399
80 unmodified lines
modified:docs/contents.rst.inc+2 added
21 unmodified lines
22 appcontext23 reqcontext24 blueprints25 extensions26 cli27 server28 shell29 patterns/index30 deploying/index31 becomingbig
30 unmodified lines
modified:docs/errorhandling.rst+115 added-23 removed
1.. _application-errors:23Logging Application Errors4==========================3Application Errors4==================56.. versionadded:: 0.378Applications fail, servers fail. Sooner or later you will see an exception9in production. Even if your code is 100% correct, you will still see10exceptions from time to time. Why? Because everything else involved will11fail. Here some situations where perfectly fine code can lead to server11fail. Here are some situations where perfectly fine code can lead to server12errors:1314- the client terminated the request early and the application was still15 reading from the incoming data.16- the database server was overloaded and could not handle the query.15 reading from the incoming data16- the database server was overloaded and could not handle the query17- a filesystem is full18- a harddrive crashed19- a backend server overloaded20- a programming error in a library you are using21- network connection of the server to another system failed.21- network connection of the server to another system failed2223And that's just a small sample of issues you could be facing. So how do we24deal with that sort of problem? By default if your application runs in25production mode, Flask will display a very simple page for you and log the
1 unmodified line
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--------------7576You 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 for80routes, they are registered for exceptions that are raised while trying to81do something else.8283Registering84```````````8586Register error handlers using :meth:`~flask.Flask.errorhandler` or87:meth:`~flask.Flask.register_error_handler`::8889 @app.errorhandler(werkzeug.exceptions.BadRequest)90 def handle_bad_request(e):91 return 'bad request!'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 codes99are interchangeable when handed to the registration methods or decorator100(``BadRequest.code == 400``).101102You are however not limited to :exc:`~werkzeug.exceptions.HTTPException`103or HTTP status codes but can register a handler for every exception class you104like.105106.. versionchanged:: 0.11107108 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.117118E.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.122123Error Mails124-----------125126If the application runs in production mode (which it will do on your35server) you won't see any log messages by default. Why is that? Flask36tries to be a zero-configuration framework. Where should it drop the logs37for you if there is no configuration? Guessing is not a good idea because38chances are, the place it guessed is not the place where the user has39permission to create a logfile. Also, for most small applications nobody40will look at the logs anyways.127server) you might not see any log messages. The reason for that is that128Flask by default will just report to the WSGI error stream or stderr129(depending on what's available). Where this ends up is sometimes hard to130find. Often it's in your webserver's log files.13142In fact, I promise you right now that if you configure a logfile for the43application errors you will never look at it except for debugging an issue44when a user reported it for you. What you want instead is a mail the45second the exception happened. Then you get an alert and you can do46something about it.132I can pretty much promise you however that if you only use a logfile for133the application errors you will never look at it except for debugging an134issue when a user reported it for you. What you probably want instead is135a mail the second the exception happened. Then you get an alert and you136can do something about it.137138Flask uses the Python builtin logging system, and it can actually send139you mails for errors which is probably what you want. Here is how you can140configure the Flask logger to send you mails for exceptions::
29 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 to84debug a problem. Please note that Flask itself will not issue any85warnings in the core system, so it's your responsibility to warn in the86code if something seems odd.174debug 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.178179There are a couple of handlers provided by the logging system out of the180box but not all of them are useful for basic error logging. The most181interesting are probably the following:
33 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.218128Here 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+------------------+----------------------------------------------------+188| ``%(asctime)s`` | Human-readable time when the LogRecord` was |189| | 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+20 added-30 removed
25 unmodified lines
26The name of the actual extension (the human readable name) however would27be something like "Flask-SimpleXML". Make sure to include the name28"Flask" somewhere in that name and that you check the capitalization.29This is how users can then register dependencies to your extension in30their `setup.py` files.30their :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 is37crucial that your application supports that kind of behavior.3845Most importantly the extension must be shipped with a `setup.py` file and39Most importantly the extension must be shipped with a :file:`setup.py` file and40registered on PyPI. Also the development checkout link should work so41that people can easily install the development version into their42virtualenv without having to download the library by hand.43
19 unmodified lines
6364setup.py65````````6673The next file that is absolutely required is the `setup.py` file which is67The next file that is absolutely required is the :file:`setup.py` file which is68used to install your Flask extension. The following contents are69something you can work with::7071 """
180 unmodified lines
252 with app.app_context():253 cur = db.connection.cursor()254 cur.execute(...)255262At the end of the `with` block the teardown handles will be executed256At the end of the ``with`` block the teardown handles will be executed257automatically.258259Additionally, the ``init_app`` method is used to support the factory pattern260for creating apps::
92 unmodified lines
353 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 module363 named ``flask_extensionname``. They might also reside inside a364 ``flaskext`` namespace packages though this is discouraged now.357 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.py369 test``, test dependencies can be specified in the `setup.py` file. The362 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:366
5 unmodified lines
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 the383 `setup.py` file unless a dependency cannot be met because it is not376 :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 to
5 unmodified lines
38610. An extension currently has to support Python 2.6 as well as387 Python 2.7388389397.. _ext-import-transition:398390Extension Import Transition391---------------------------392402For a while we recommended using namespace packages for Flask extensions.403This turned out to be problematic in practice because many different404competing namespace package systems exist and pip would automatically405switch between different systems and this caused a lot of problems for406users.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.398408Instead we now recommend naming packages ``flask_foo`` instead of the now409deprecated ``flaskext.foo``. Flask 0.8 introduces a redirect import410system that lets uses import from ``flask.ext.foo`` and it will try411``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.402413Flask extensions should urge users to import from ``flask.ext.foo``414instead of ``flask_foo`` or ``flaskext_foo`` so that extensions can415transition 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``.406407418.. _OAuth extension: http://packages.python.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+17 added-7 removed
1.. _extensions:23Flask Extensions4================56Flask extensions extend the functionality of Flask in various different
2 unmodified lines
9Finding Extensions10------------------1112Flask extensions are listed on the `Flask Extension Registry`_ and can be11downloaded with ``easy_install`` or ``pip``. If you add a Flask extension12as dependency to your ``requirements.rst`` or ``setup.py`` file they are13downloaded with :command:`easy_install` or :command:`pip`. If you add a Flask extension14as dependency to your :file:`requirements.txt` or :file:`setup.py` file they are15usually installed with a simple command or when your application installs.1617Using Extensions18----------------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
1 unmodified line
40depending on how the extension is distributed. If you want to develop an41application that supports Flask 0.7 or earlier you should still import42from the :data:`flask.ext` package. We provide you with a compatibility43module that provides this package for older versions of Flask. You can35download it from github: `flaskext_compat.py`_44download it from GitHub: `flaskext_compat.py`_4546And here is how you can use it::4748 import flaskext_compat
3 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://github.com/mitsuhiko/flask/raw/master/scripts/flaskext_compat.py58.. _flaskext_compat.py: https://raw.githubusercontent.com/pallets/flask/master/scripts/flaskext_compat.py
modified:docs/foreword.rst+3 added-3 removed
7 unmodified lines
8What does "micro" mean?9-----------------------1011“Micro” does not mean that your whole web application has to fit into a single12Python file, although it certainly can. Nor does it mean that Flask is lacking12Python file (although it certainly can), nor does it mean that Flask is lacking13in functionality. The "micro" in microframework means Flask aims to keep the14core simple but extensible. Flask won't make many decisions for you, such as15what database to use. Those decisions that it does make, such as what16templating engine to use, are easy to change. Everything else is up to you, so
10 unmodified lines
27Configuration and Conventions28-----------------------------2930Flask has many configuration values, with sensible defaults, and a few31conventions when getting started. By convention templates and static files are31conventions when getting started. By convention, templates and static files are32stored in subdirectories within the application's Python source tree, with the33names `templates` and `static` respectively. While this can be changed you33names :file:`templates` and :file:`static` respectively. While this can be changed, you34usually don't have to, especially when getting started.3536Growing with Flask37------------------
20 unmodified lines
modified:docs/htmlfaq.rst+3 added-3 removed
14 unmodified lines
15However, barely any websites on the Internet are actual XHTML (which is16HTML processed using XML rules). There are a couple of major reasons17why this is the case. One of them is Internet Explorer's lack of proper18XHTML support. The XHTML spec states that XHTML must be served with the MIME19type `application/xhtml+xml`, but Internet Explorer refuses to read files19type :mimetype:`application/xhtml+xml`, but Internet Explorer refuses to read files20with that MIME type.21While it is relatively easy to configure Web servers to serve XHTML properly,22few people do. This is likely because properly using XHTML can be quite23painful.
5 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
147 unmodified lines
185Many other features have been added, as well. A good guide to new features186in HTML5 is Mark Pilgrim's soon-to-be-published book, `Dive Into HTML5`_.187Not all of them are supported in browsers yet, however, so use caution.188189.. _Dive Into HTML5: http://www.diveintohtml5.org/189.. _Dive Into HTML5: http://diveintohtml5.info/190191What should be used?192--------------------193
14 unmodified lines
modified:docs/index.rst+3 added-3 removed
19 unmodified lines
20engine and the `Werkzeug`_ WSGI toolkit. These libraries are not documented21here. If you want to dive into their documentation, check out the22following links:2324- `Jinja2 Documentation <http://jinja.pocoo.org/2/documentation/>`_25- `Werkzeug Documentation <http://werkzeug.pocoo.org/documentation/>`_24- `Jinja2 Documentation <http://jinja.pocoo.org/docs>`_25- `Werkzeug Documentation <http://werkzeug.pocoo.org/docs>`_262728.. _Jinja2: http://jinja.pocoo.org/2/28.. _Jinja2: http://jinja.pocoo.org/29.. _Werkzeug: http://werkzeug.pocoo.org/3031.. include:: contents.rst.inc
modified:docs/installation.rst+119 added-125 removed
1 unmodified line
23Installation4============56Flask depends on some external libraries, like `Werkzeug7<http://werkzeug.pocoo.org/>`_ and `Jinja2 <http://jinja.pocoo.org/2/>`_.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 `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 `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 `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:8384Now you can just enter the following command to get Flask activated in your85virtualenv::84.. code-block:: bat8587 $ pip install Flask86 py -3 -m venv venv8789A few seconds later and you are good to go.88If you needed to install virtualenv because you are on an older version of89Python, use the following command instead:9091.. code-block:: sh9292System-Wide Installation93------------------------93 virtualenv venv9495This is possible as well, though I do not recommend it. Just run96`pip` with root privileges::95On Windows:9698 $ sudo pip install Flask97.. code-block:: bat98100(On Windows systems, run it in a command-prompt window with administrator101privileges, and leave out `sudo`.)99 \Python27\Scripts\virtualenv.exe venv100101Activate the environment102~~~~~~~~~~~~~~~~~~~~~~~~103104Living on the Edge105------------------104Before you work on your project, activate the corresponding environment:105107If you want to work with the latest version of Flask, there are two ways: you108can either let `pip` pull in the development version, or you can tell109it to operate on a git checkout. Either way, virtualenv is recommended.106.. code-block:: sh107111Get the git checkout in a new virtualenv and run in development mode::108 . venv/bin/activate109113 $ git clone http://github.com/mitsuhiko/flask.git114 Initialized empty Git repository in ~/dev/flask/.git/115 $ cd flask116 $ virtualenv venv117 New python executable in venv/bin/python118 Installing setuptools, pip............done.119 $ . venv/bin/activate120 $ python setup.py develop121 ...122 Finished processing dependencies for Flask110On Windows:111124This will pull in the dependencies and activate the git head as the current125version inside the virtualenv. Then all you have to do is run ``git pull126origin`` to update to the latest version.112.. code-block:: bat113128To just get the development version without git, do this instead::114 venv\Scripts\activate115130 $ mkdir flask131 $ cd flask132 $ virtualenv venv133 $ . venv/bin/activate134 New python executable in venv/bin/python135 Installing setuptools, pip............done.136 $ pip install Flask==dev137 ...138 Finished processing dependencies for Flask==dev116Your shell prompt will change to show the name of the activated environment.117140.. _windows-easy-install:118Install Flask119-------------120142`pip` and `setuptools` on Windows143---------------------------------121Within the activated environment, use the following command to install Flask:122145Sometimes getting the standard "Python packaging tools" like *pip*, *setuptools*146and *virtualenv* can be a little trickier, but nothing very hard. The two crucial147packages you will need are setuptools and pip - these will let you install148anything else (like virtualenv). Fortunately there are two "bootstrap scripts"149you can run to install either.123.. code-block:: sh124151If you don't currently have either, then `get-pip.py` will install both for you152(you won't need to run ez_setup.py).125 pip install Flask126154`get-pip.py`_127Living on the edge128~~~~~~~~~~~~~~~~~~129156To install the latest setuptools, you can use its bootstrap file:130If you want to work with the latest Flask code before it's released, install or131update the code from the master branch:132158`ez_setup.py`_133.. code-block:: sh134160Either should be double-clickable once you download them. If you already have pip,161you can upgrade them by running::135 pip install -U https://github.com/pallets/flask/archive/master.tar.gz136163 > pip install --upgrade pip setuptools137.. _install-install-virtualenv:138165Most often, once you pull up a command prompt you want to be able to type ``pip``166and ``python`` which will run those things, but this might not automatically happen167on Windows, because it doesn't know where those executables are (give either a try!).139Install virtualenv140------------------141169To fix this, you should be able to navigate to your Python install directory170(e.g ``C:\Python27``), then go to ``Tools``, then ``Scripts``; then find the171``win_add2path.py`` file and run that. Open a **new** Command Prompt and172check that you can now just type ``python`` to bring up the interpreter.142If you are using Python 2, the venv module is not available. Instead,143install `virtualenv`_.144174Finally, to install `virtualenv`_, you can simply run::145On Linux, virtualenv is provided by your package manager:146176 > pip install virtualenv177 178Then you can be off on your way following the installation instructions above.147.. code-block:: sh148180.. _get-pip.py: https://raw.github.com/pypa/pip/master/contrib/get-pip.py181.. _ez_setup.py: https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py149 # Debian, Ubuntu150 sudo apt-get install python-virtualenv151152 # CentOS, Fedora153 sudo yum install python-virtualenv154155 # Arch156 sudo pacman -S python-virtualenv157158If you are on Mac OS X or Windows, download `get-pip.py`_, then:159160.. code-block:: sh161162 sudo python2 Downloads/get-pip.py163 sudo python2 -m pip install virtualenv164165On Windows, as an administrator:166167.. code-block:: bat168169 \Python27\python.exe Downloads\get-pip.py170 \Python27\python.exe -m pip install virtualenv171172Now you can continue to :ref:`install-create-env`.173174.. _virtualenv: https://virtualenv.pypa.io/175.. _get-pip.py: https://bootstrap.pypa.io/get-pip.py
modified:docs/license.rst+1 added-1 removed
24 unmodified lines
2526- "AUTHORS" hereby refers to all the authors listed in the27 :ref:`authors` section.2829- The ":ref:`flask-license`" applies to all the sourcecode shipped as29- The ":ref:`flask-license`" applies to all the source code shipped as30 part of Flask (Flask itself as well as the examples and the unittests)31 as well as documentation.3233- The ":ref:`artwork-license`" applies to the project's Horn-Logo.
15 unmodified lines
modified:docs/python3.rst+14 added-52 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.910Requirements11------------10You need to use Python 3.3 or higher. 3.2 and older are *not* supported.1113If you want to use Flask with Python 3 you will need to use Python 3.3 or14higher. 3.2 and older are *not* supported.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.1416In addition to that you need to use the latest and greatest versions of17`itsdangerous`, `Jinja2` and `Werkzeug`.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.1919API Stability20-------------2122Some of the decisions made in regards to unicode and byte untilization on23Python 3 make it hard to write low level code. This mainly affects WSGI24middlewares and interacting with the WSGI provided information. Werkzeug25wraps all that information in high-level helpers but some of those were26specifically added for the Python 3 support and are quite new.2728A lot of the documentation out there on using WSGI leaves out those29details as it was written before WSGI was updated to Python 3. While the30API for Werkzeug and Flask on Python 2.x should not change much we cannot31guarantee that this won't happen on Python 3.3233Few Users34---------3536Python 3 currently has less than 1% of the users of Python 2 going by PyPI37download stats. As a result many of the problems you will encounter are38probably hard to search for on the internet if they are Python 3 specific.3940Small Ecosystem41---------------4243The majority of the Flask extensions, all of the documentation and the44vast majority of the PyPI provided libraries do not support Python 3 yet.45Even if you start your project with knowing that all you will need is46supported by Python 3 you don't know what happens six months from now. If47you are adventurous you can start porting libraries on your own, but that48is nothing for the faint of heart.4950Recommendations51---------------5253Unless you are already familiar with the differences in the versions we54recommend sticking to current versions of Python until the ecosystem55caught up.5657The majority of the upgrade pain is in the lower-level libararies like58Flask and Werkzeug and not in the actual high-level application code. For59instance all of the Flask examples that are in the Flask repository work60out of the box on both 2.x and 3.x and did not require a single line of61code 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+231 added-249 removed
16 unmodified lines
17 app = Flask(__name__)1819 @app.route('/')20 def hello_world():21 return 'Hello World!'21 return 'Hello, World!'2223 if __name__ == '__main__':24 app.run()2526Just save it as `hello.py` (or something similar) and run it with your Python27interpreter. Make sure to not call your application `flask.py` because this28would conflict with Flask itself.2930::3132 $ python hello.py33 * Running on http://127.0.0.1:5000/3435Now head over to `http://127.0.0.1:5000/ <http://127.0.0.1:5000/>`_, and you36should see your hello world greeting.3723So what did that code do?24251. First we imported the :class:`~flask.Flask` class. An instance of this41 class will be our WSGI application. 26 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 (as44 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.
1 unmodified line
35 should trigger our function.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.545. Finally we use the :meth:`~flask.Flask.run` function to run the local server55 with our application. The ``if __name__ == '__main__':`` makes sure the56 server only runs if the script is executed directly from the Python57 interpreter and not used as an imported module.3959To stop the server, hit control-C.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 ``-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.py50 $ flask run51 * Running on http://127.0.0.1:5000/5253If you are on Windows you need to use ``set`` instead of ``export``.5455Alternatively you can use :command:`python -m flask`::5657 $ export FLASK_APP=hello.py58 $ python -m flask run59 * Running on http://127.0.0.1:5000/6061This launches a very simple builtin server, which is good enough for testing62but probably not what you want to use in production. For deployment options see63:ref:`deployment`.6465Now head over to `http://127.0.0.1:5000/ <http://127.0.0.1:5000/>`_, and you66should see your hello world greeting.6768.. _public-server:6970.. admonition:: Externally Visible Server71
1 unmodified line
73 from your own computer, not from any other in the network. This is the74 default because in debugging mode a user of the application can execute75 arbitrary Python code on your computer.7670 If you have `debug` disabled or trust the users on your network, you can71 make the server publicly available simply by changing the call of the72 :meth:`~flask.Flask.run` method to look like this::77 If you have the debugger disabled or trust the users on your network,78 you can make the server publicly available simply by adding79 ``--host=0.0.0.0`` to the command line::8074 app.run(host='0.0.0.0')81 flask run --host=0.0.0.08283 This tells your operating system to listen on all public IPs.848586What to do if the Server does not Start87---------------------------------------8889In case the :command:`python -m flask` fails or :command:`flask` does not exist,90there are multiple reasons this might be the case. First of all you need91to look at the error message.9293Old Version of Flask94````````````````````9596Versions of Flask older than 0.11 use to have different ways to start the97application. In short, the :command:`flask` command did not exist, and98neither did :command:`python -m flask`. In that case you have two options:99either upgrade to newer Flask versions or have a look at the :ref:`server`100docs to see the alternative method for running a server.101102Invalid Import Name103```````````````````104105The ``FLASK_APP`` environment variable is the name of the module to import at106:command:`flask run`. In case that module is incorrectly named you will get an107import error upon start (or if debug is enabled when you navigate to the108application). It will tell you what it tried to import and why it failed.109110The most common reason is a typo or because you did not actually create an111``app`` object.112113.. _debug-mode:114115Debug Mode116----------11784The :meth:`~flask.Flask.run` method is nice to start a local85development server, but you would have to restart it manually after each86change to your code. That is not very nice and Flask can do better. If87you enable debug support the server will reload itself on code changes,88and it will also provide you with a helpful debugger if things go wrong.118(Want to just log errors and stack traces? See :ref:`application-errors`)11990There are two ways to enable debugging. Either set that flag on the91application object::120The :command:`flask` script is nice to start a local development server, but121you would have to restart it manually after each change to your code.122That is not very nice and Flask can do better. If you enable debug123support the server will reload itself on code changes, and it will also124provide you with a helpful debugger if things go wrong.12593 app.debug = True94 app.run()126To enable debug mode you can export the ``FLASK_DEBUG`` environment variable127before running the server::12896Or pass it as a parameter to run::129 $ export FLASK_DEBUG=1130 $ flask run13198 app.run(debug=True)132(On Windows you need to use ``set`` instead of ``export``).133100Both methods have the exact same effect.134This does the following things:1351361. it activates the debugger1372. it activates the automatic reloader1383. it enables the debug mode on the Flask application.139140There are more parameters that are explained in the :ref:`server` docs.141142.. admonition:: Attention143144 Even though the interactive debugger does not work in forking environments145 (which makes it nearly impossible to use on production servers), it still
12 unmodified lines
158159Routing160-------161122Modern web applications have beautiful URLs. This helps people remember123the URLs, which is especially handy for applications that are used from124mobile devices with slower network connections. If the user can directly125go to the desired page without having to hit the index page it is more126likely they will like the page and come back next time.162Modern web applications use meaningful URLs to help users. Users are more163likely to like a page and come back if the page uses a meaningful URL they can164remember and use to directly visit a page.165128As you have seen above, the :meth:`~flask.Flask.route` decorator is used to129bind a function to a URL. Here are some basic examples::166Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::167168 @app.route('/')169 def index():170 return 'Index Page'171172 @app.route('/hello')173 def hello():137 return 'Hello World'174 return 'Hello, World'175139But there is more to it! You can make certain parts of the URL dynamic and140attach multiple rules to a function.176You can do more! You can make parts of the URL dynamic and attach multiple177rules to a function.178179Variable Rules180``````````````181145To add variable parts to a URL you can mark these special sections as146``<variable_name>``. Such a part is then passed as a keyword argument to your147function. Optionally a converter can be used by specifying a rule with148``<converter:variable_name>``. Here are some nice examples::182You can add variable sections to a URL by marking sections with183``<variable_name>``. Your function then receives the ``<variable_name>``184as a keyword argument. Optionally, you can use a converter to specify the type185of the argument like ``<converter:variable_name>``. ::186187 @app.route('/user/<username>')188 def show_user_profile(username):189 # show the user profile for that user
3 unmodified lines
193 def show_post(post_id):194 # show the post with the given id, the id is an integer195 return 'Post %d' % post_id196160The following converters exist:197 @app.route('/path/<path:subpath>')198 def show_subpath(subpath):199 # show the subpath after /path/200 return 'Subpath %s' % subpath201162=========== ===========================================163`int` accepts integers164`float` like `int` but for floating point values165`path` like the default but also accepts slashes166=========== ===========================================202Converter types:203168.. admonition:: Unique URLs / Redirection Behavior204========== ==========================================205``string`` (default) accepts any text without a slash206``int`` accepts positive integers207``float`` accepts positive floating point values208``path`` like ``string`` but also accepts slashes209``uuid`` accepts UUID strings210========== ==========================================211170 Flask's URL rules are based on Werkzeug's routing module. The idea171 behind that module is to ensure beautiful and unique URLs based on172 precedents laid down by Apache and earlier HTTP servers.212Unique URLs / Redirection Behavior213``````````````````````````````````214174 Take these two rules::215Take these two rules::216176 @app.route('/projects/')177 def projects():178 return 'The project page'217 @app.route('/projects/')218 def projects():219 return 'The project page'220180 @app.route('/about')181 def about():182 return 'The about page'221 @app.route('/about')222 def about():223 return 'The about page'224184 Though they look rather similar, they differ in their use of the trailing185 slash in the URL *definition*. In the first case, the canonical URL for the186 `projects` endpoint has a trailing slash. In that sense, it is similar to187 a folder on a file system. Accessing it without a trailing slash will cause188 Flask to redirect to the canonical URL with the trailing slash.225Though they look similar, they differ in their use of the trailing slash in226the URL. In the first case, the canonical URL for the ``projects`` endpoint227uses a trailing slash. It's similar to a folder in a file system; if you228access the URL without a trailing slash, Flask redirects you to the229canonical URL with the trailing slash.230190 In the second case, however, the URL is defined without a trailing slash,191 rather like the pathname of a file on UNIX-like systems. Accessing the URL192 with a trailing slash will produce a 404 "Not Found" error.231In the second case, however, the URL definition lacks a trailing slash,232like the pathname of a file on UNIX-like systems. Accessing the URL with a233trailing slash produces a 404 “Not Found” error.234194 This behavior allows relative URLs to continue working even if the trailing195 slash is omitted, consistent with how Apache and other servers work. Also,196 the URLs will stay unique, which helps search engines avoid indexing the197 same page twice.235This behavior allows relative URLs to continue working even if the trailing236slash is omitted, consistent with how Apache and other servers work. Also,237the URLs will stay unique, which helps search engines avoid indexing the238same page twice.239199240.. _url-building:241242URL Building243````````````244205If it can match URLs, can Flask also generate them? Of course it can. To206build a URL to a specific function you can use the :func:`~flask.url_for`207function. It accepts the name of the function as first argument and a number208of keyword arguments, each corresponding to the variable part of the URL rule.209Unknown variable parts are appended to the URL as query parameters. Here are210some examples:245To build a URL to a specific function, use the :func:`~flask.url_for` function.246It accepts the name of the function as its first argument and any number of247keyword arguments, each corresponding to a variable part of the URL rule.248Unknown variable parts are appended to the URL as query parameters.249212>>> from flask import Flask, url_for213>>> app = Flask(__name__)214>>> @app.route('/')215... def index(): pass216...217>>> @app.route('/login')218... def login(): pass219...220>>> @app.route('/user/<username>')221... def profile(username): pass222...223>>> with app.test_request_context():224... print url_for('index')225... print url_for('login')226... print url_for('login', next='/')227... print url_for('profile', username='John Doe')228...229/230/login231/login?next=/232/user/John%20Doe250Why would you want to build URLs using the URL reversing function251:func:`~flask.url_for` instead of hard-coding them into your templates?252234(This also uses the :meth:`~flask.Flask.test_request_context` method, explained235below. It tells Flask to behave as though it is handling a request, even236though we are interacting with it through a Python shell. Have a look at the237explanation below. :ref:`context-locals`).2531. Reversing is often more descriptive than hard-coding the URLs.2542. You can change your URLs in one go instead of needing to remember to255 manually change hard-coded URLs.2563. URL building handles escaping of special characters and Unicode data257 transparently.2584. If your application is placed outside the URL root, for example, in259 ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly260 handles that for you.261239Why would you want to build URLs using the URL reversing function :func:`~flask.url_for` 240instead of hard-coding them into your templates? There are three good reasons 241for this:262For example, here we use the :meth:`~flask.Flask.test_request_context` method263to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`264tells Flask to behave as though it's handling a request even while we use a265Python shell. See :ref:`context-locals`. ::2662431. Reversing is often more descriptive than hard-coding the URLs. More244 importantly, it allows you to change URLs in one go, without having to245 remember to change URLs all over the place.2462. URL building will handle escaping of special characters and Unicode247 data transparently for you, so you don't have to deal with them.2483. If your application is placed outside the URL root (say, in249 ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will handle250 that properly for you.267 from flask import Flask, url_for268269 app = Flask(__name__)270271 @app.route('/')272 def index():273 return 'index'274275 @app.route('/login')276 def login():277 return 'login'278279 @app.route('/user/<username>')280 def profile(username):281 return '{}'s profile'.format(username)282283 with app.test_request_context():284 print(url_for('index'))285 print(url_for('login'))286 print(url_for('login', next='/'))287 print(url_for('profile', username='John Doe'))288289 /290 /login291 /login?next=/292 /user/John%20Doe293294HTTP Methods295````````````296256HTTP (the protocol web applications are speaking) knows different methods for257accessing URLs. By default, a route only answers to `GET` requests, but that258can be changed by providing the `methods` argument to the259:meth:`~flask.Flask.route` decorator. Here are some examples::297Web applications use different HTTP methods when accessing URLs. You should298familiarize yourself with the HTTP methods as you work with Flask. By default,299a route only answers to ``GET`` requests. You can use the ``methods`` argument300of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.301::302261 from flask import request262303 @app.route('/login', methods=['GET', 'POST'])304 def login():305 if request.method == 'POST':306 do_the_login()307 else:308 show_the_login_form()309270If `GET` is present, `HEAD` will be added automatically for you. You271don't have to deal with that. It will also make sure that `HEAD` requests272are handled as the `HTTP RFC`_ (the document describing the HTTP273protocol) demands, so you can completely ignore that part of the HTTP274specification. Likewise, as of Flask 0.6, `OPTIONS` is implemented for you275automatically as well.310If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method311and handles ``HEAD`` requests according to the the `HTTP RFC`_. Likewise,312``OPTIONS`` is automatically implemented for you.313277You have no idea what an HTTP method is? Worry not, here is a quick278introduction to HTTP methods and why they matter:314.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt315280The HTTP method (also often called "the verb") tells the server what the281clients wants to *do* with the requested page. The following methods are282very common:283284`GET`285 The browser tells the server to just *get* the information stored on286 that page and send it. This is probably the most common method.287288`HEAD`289 The browser tells the server to get the information, but it is only290 interested in the *headers*, not the content of the page. An291 application is supposed to handle that as if a `GET` request was292 received but to not deliver the actual content. In Flask you don't293 have to deal with that at all, the underlying Werkzeug library handles294 that for you.295296`POST`297 The browser tells the server that it wants to *post* some new298 information to that URL and that the server must ensure the data is299 stored and only stored once. This is how HTML forms usually300 transmit data to the server.301302`PUT`303 Similar to `POST` but the server might trigger the store procedure304 multiple times by overwriting the old values more than once. Now you305 might be asking why this is useful, but there are some good reasons306 to do it this way. Consider that the connection is lost during307 transmission: in this situation a system between the browser and the308 server might receive the request safely a second time without breaking309 things. With `POST` that would not be possible because it must only310 be triggered once.311312`DELETE`313 Remove the information at the given location.314315`OPTIONS`316 Provides a quick way for a client to figure out which methods are317 supported by this URL. Starting with Flask 0.6, this is implemented318 for you automatically.319320Now the interesting part is that in HTML4 and XHTML1, the only methods a321form can submit to the server are `GET` and `POST`. But with JavaScript322and future HTML standards you can use the other methods as well. Furthermore323HTTP has become quite popular lately and browsers are no longer the only324clients that are using HTTP. For instance, many revision control systems325use it.326327.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt328316Static Files317------------318319Dynamic web applications also need static files. That's usually where320the CSS and JavaScript files are coming from. Ideally your web server is321configured to serve them for you, but during development Flask can do that335as well. Just create a folder called `static` in your package or next to336your module and it will be available at `/static` on the application.322as well. Just create a folder called :file:`static` in your package or next to323your module and it will be available at ``/static`` on the application.324325To generate URLs for static files, use the special ``'static'`` endpoint name::326327 url_for('static', filename='style.css')328342The file has to be stored on the filesystem as ``static/style.css``.329The file has to be stored on the filesystem as :file:`static/style.css`.330331Rendering Templates332-------------------333334Generating HTML from within Python is not fun, and actually pretty335cumbersome because you have to do the HTML escaping on your own to keep336the application secure. Because of that Flask configures the `Jinja2350<http://jinja.pocoo.org/2/>`_ template engine for you automatically.337<http://jinja.pocoo.org/>`_ template engine for you automatically.338339To render a template you can use the :func:`~flask.render_template`340method. All you have to do is provide the name of the template and the341variables you want to pass to the template engine as keyword arguments.
5 unmodified lines
347 @app.route('/hello/<name>')348 def hello(name=None):349 return render_template('hello.html', name=name)350364Flask will look for templates in the `templates` folder. So if your351Flask will look for templates in the :file:`templates` folder. So if your352application is a module, this folder is next to that module, if it's a353package it's actually inside your package:354355**Case 1**: a module::
10 unmodified lines
366 /hello.html367368For templates you can use the full power of Jinja2 templates. Head over369to the official `Jinja2 Template Documentation383<http://jinja.pocoo.org/2/documentation/templates>`_ for more information.370<http://jinja.pocoo.org/docs/templates>`_ for more information.371372Here is an example template:373374.. sourcecode:: html+jinja
2 unmodified lines
377 <title>Hello from Flask</title>378 {% if name %}379 <h1>Hello {{ name }}!</h1>380 {% else %}394 <h1>Hello World!</h1>381 <h1>Hello, World!</h1>382 {% endif %}383384Inside templates you also have access to the :class:`~flask.request`,385:class:`~flask.session` and :class:`~flask.g` [#]_ objects
3 unmodified lines
389know how that works, head over to the :ref:`template-inheritance` pattern390documentation. Basically template inheritance makes it possible to keep391certain elements on each page (like header, navigation and footer).392406Automatic escaping is enabled, so if `name` contains HTML it will be escaped393Automatic escaping is enabled, so if ``name`` contains HTML it will be escaped394automatically. If you can trust a variable and you know that it will be395safe HTML (for example because it came from a module that converts wiki396markup to HTML) you can mark it as safe by using the397:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the398template. Head over to the Jinja 2 documentation for more examples.399413Here is a basic introduction to how the :class:`~jinja2.Markup` class works:400Here is a basic introduction to how the :class:`~jinja2.Markup` class works::401415>>> from flask import Markup416>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'417Markup(u'<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')418>>> Markup.escape('<blink>hacker</blink>')419Markup(u'&lt;blink&gt;hacker&lt;/blink&gt;')420>>> Markup('<em>Marked up</em> &raquo; HTML').striptags()421u'Marked up \xbb HTML'402 >>> from flask import Markup403 >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'404 Markup(u'<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')405 >>> Markup.escape('<blink>hacker</blink>')406 Markup(u'&lt;blink&gt;hacker&lt;/blink&gt;')407 >>> Markup('<em>Marked up</em> &raquo; HTML').striptags()408 u'Marked up \xbb HTML'409410.. versionchanged:: 0.5411412 Autoescaping is no longer enabled for all templates. The following
9 unmodified lines
422423Accessing Request Data424----------------------425439For web applications it's crucial to react to the data a client sent to426For web applications it's crucial to react to the data a client sends to427the server. In Flask this information is provided by the global428:class:`~flask.request` object. If you have some experience with Python429you might be wondering how that object can be global and how Flask430manages to still be threadsafe. The answer is context locals:
27 unmodified lines
458will notice that code which depends on a request object will suddenly break459because there is no request object. The solution is creating a request460object yourself and binding it to the context. The easiest solution for461unit testing is to use the :meth:`~flask.Flask.test_request_context`475context manager. In combination with the `with` statement it will bind a462context manager. In combination with the ``with`` statement it will bind a463test request so that you can interact with it. Here is an example::464465 from flask import request466
14 unmodified lines
481The Request Object482``````````````````483484The request object is documented in the API section and we will not cover498it here in detail (see :class:`~flask.request`). Here is a broad overview of485it here in detail (see :class:`~flask.Request`). Here is a broad overview of486some of the most common operations. First of all you have to import it from500the `flask` module::487the ``flask`` module::488489 from flask import request490491The current request method is available by using the505:attr:`~flask.request.method` attribute. To access form data (data506transmitted in a `POST` or `PUT` request) you can use the507:attr:`~flask.request.form` attribute. Here is a full example of the two492:attr:`~flask.Request.method` attribute. To access form data (data493transmitted in a ``POST`` or ``PUT`` request) you can use the494:attr:`~flask.Request.form` attribute. Here is a full example of the two495attributes mentioned above::496497 @app.route('/login', methods=['POST', 'GET'])498 def login():
7 unmodified lines
506 # the code below is executed if the request method507 # was GET or the credentials were invalid508 return render_template('login.html', error=error)509523What happens if the key does not exist in the `form` attribute? In that510What happens if the key does not exist in the ``form`` attribute? In that511case a special :exc:`KeyError` is raised. You can catch it like a512standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request513error page is shown instead. So for many situations you don't have to514deal with that problem.515516To access parameters submitted in the URL (``?key=value``) you can use the530:attr:`~flask.request.args` attribute::517:attr:`~flask.Request.args` attribute::518519 searchword = request.args.get('key', '')520521We recommend accessing URL parameters with `get` or by catching the535`KeyError` because users might change the URL and presenting them a 400522:exc:`KeyError` because users might change the URL and presenting them a 400523bad request page in that case is not user friendly.524525For a full list of methods and attributes of the request object, head over539to the :class:`~flask.request` documentation.526to the :class:`~flask.Request` documentation.527528529File Uploads530````````````
28 unmodified lines
559pass it through the :func:`~werkzeug.utils.secure_filename` function that560Werkzeug provides for you::561562 from flask import request576 from werkzeug import secure_filename563 from werkzeug.utils import secure_filename564565 @app.route('/upload', methods=['GET', 'POST'])566 def upload_file():567 if request.method == 'POST':
80 unmodified lines
648Note the ``404`` after the :func:`~flask.render_template` call. This649tells Flask that the status code of that page should be 404 which means650not found. By default 200 is assumed which translates to: all went well.651652See :ref:`error-handlers` for more details.653654.. _about-responses:655656About Responses657---------------658659The return value from a view function is automatically converted into a660response object for you. If the return value is a string it's converted661into a response object with the string as response body, a ``200 OK``673status code and a ``text/html`` mimetype. The logic that Flask applies to662status code and a :mimetype:`text/html` mimetype. The logic that Flask applies to663converting return values into response objects is as follows:6646651. If a response object of the correct type is returned it's directly666 returned from the view.
1 unmodified line
668 default parameters.6693. If a tuple is returned the items in the tuple can provide extra670 information. Such tuples have to be in the form ``(response, status,671 headers)`` or ``(response, headers)`` where at least one item has683 to be in the tuple. The `status` value will override the status code684 and `headers` can be a list or dictionary of additional header values.672 to be in the tuple. The ``status`` value will override the status code673 and ``headers`` can be a list or dictionary of additional header values.6744. If none of that works, Flask will assume the return value is a675 valid WSGI application and convert that into a response object.676677If you want to get hold of the resulting response object inside the view678you can use the :func:`~flask.make_response` function.679691Imagine you have a view like this:680Imagine you have a view like this::681693.. sourcecode:: python694682 @app.errorhandler(404)683 def not_found(error):684 return render_template('error.html'), 404685686You just need to wrap the return expression with687:func:`~flask.make_response` and get the response object to modify it, then701return it:688return it::689703.. sourcecode:: python704690 @app.errorhandler(404)691 def not_found(error):692 resp = make_response(render_template('error.html'), 404)693 resp.headers['X-Something'] = 'A value'
29 unmodified lines
723 if request.method == 'POST':724 session['username'] = request.form['username']725 return redirect(url_for('index'))726 return '''742 <form action="" method="post">727 <form method="post">728 <p><input type=text name=username>729 <p><input type=submit value=Login>730 </form>731 '''
14 unmodified lines
746747 The problem with random is that it's hard to judge what is truly random. And748 a secret key should be as random as possible. Your operating system749 has ways to generate pretty random stuff based on a cryptographic765 random generator which can be used to get such a key:750 random generator which can be used to get such a key::751767 >>> import os768 >>> os.urandom(24)769 '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'752 >>> import os753 >>> os.urandom(24)754 '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'755771 Just take that thing and copy/paste it into your code and you're done.756 Just take that thing and copy/paste it into your code and you're done.757758A note on cookie-based sessions: Flask will take the values you put into the759session object and serialize them into a cookie. If you are finding some760values do not persist across requests, cookies are indeed enabled, and you are761not getting a clear error message, check the size of the cookie in your page762responses compared to the size supported by web browsers.763764Besides the default client-side based sessions, if you want to handle765sessions on the server-side instead, there are several766Flask extensions that support this.767768Message Flashing769----------------770
34 unmodified lines
805 app.logger.error('An error occurred')806807The attached :attr:`~flask.Flask.logger` is a standard logging808:class:`~logging.Logger`, so head over to the official `logging821documentation <http://docs.python.org/library/logging.html>`_ for more809documentation <https://docs.python.org/library/logging.html>`_ for more810information.811812Read more on :ref:`application-errors`.813814Hooking in WSGI Middlewares815---------------------------816817If you want to add a WSGI middleware to your application you can wrap the
3 unmodified lines
821822 from werkzeug.contrib.fixers import LighttpdCGIRootFix823 app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)824835.. _quickstart_deployment:825Using Flask Extensions826----------------------827828Extensions are packages that help you accomplish common tasks. For829example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple830and easy to use with Flask.831832For more on Flask extensions, have a look at :ref:`extensions`.833834Deploying to a Web Server835-------------------------836840Ready to deploy your new Flask app? To wrap up the quickstart, you can841immediately deploy to a hosted platform, all of which offer a free plan for842small projects:843844- `Deploying Flask on Heroku <http://devcenter.heroku.com/articles/python>`_845- `Deploying WSGI on dotCloud <http://docs.dotcloud.com/services/python/>`_846 with `Flask-specific notes <http://flask.pocoo.org/snippets/48/>`_847848Other places where you can host your Flask app:849850- `Deploying Flask on Webfaction <http://flask.pocoo.org/snippets/65/>`_851- `Deploying Flask on Google App Engine <https://github.com/kamalgill/flask-appengine-template>`_852- `Sharing your Localhost Server with Localtunnel <http://flask.pocoo.org/snippets/89/>`_853854If you manage your own hosts and would like to host yourself, see the chapter855on :ref:`deployment`.837Ready to deploy your new Flask app? Go to :ref:`deployment`.
modified:docs/reqcontext.rst+4 added-4 removed
35 unmodified lines
36us a :class:`~flask.ctx.RequestContext`:3738>>> ctx = app.test_request_context('/?next=http://example.com/')3940This context can be used in two ways. Either with the `with` statement40This context can be used in two ways. Either with the ``with`` statement41or by calling the :meth:`~flask.ctx.RequestContext.push` and42:meth:`~flask.ctx.RequestContext.pop` methods:4344>>> ctx.push()
23 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 new77:class:`~flask.ctx.RequestContext` object and uses it in combination with78the `with` statement to bind the context. Everything that is called from79the same thread from this point onwards until the end of the `with`78the ``with`` statement to bind the context. Everything that is called from79the same thread from this point onwards until the end of the ``with``80statement will have access to the request globals (:data:`flask.request`81and others).8283The request context internally works like a stack: The topmost level on
140 unmodified lines
modified:docs/security.rst+13 added-82 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
1 unmodified line
2425- generating HTML without the help of Jinja226- calling :class:`~flask.Markup` on data submitted by users27- sending out HTML from uploaded files, never do that, use the28 `Content-Disposition: attachment` header to prevent that problem.28 ``Content-Disposition: attachment`` header to prevent that problem.29- sending out textfiles from uploaded files. Some browsers are using30 content-type guessing based on the first few bytes so users could31 trick a browser to execute HTML.32
36 unmodified lines
69don't keep that in mind, some people might be able to trick your70application's users with social engineering to do stupid things without71them knowing.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 an73Say 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 ``application/json``165mimetype if ``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.
added:docs/server.rst+52 added
1.. _server:23Development Server4==================56.. currentmodule:: flask78Starting 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 Line13------------1415The :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 $ 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::2930 $ flask run --no-reload3132In Code33-------3435The alternative way to start the application is through the36:meth:`Flask.run` method. This will immediately launch a local server37exactly the same way the :command:`flask` script does.3839Example::4041 if __name__ == '__main__':42 app.run()4344This works well for the common case but it does not work well for45development 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+12 added-2 removed
24 unmodified lines
2526Generally it's recommended that you read the :ref:`request-context`27chapter of the documentation first.2829Command Line Interface30----------------------3132Starting 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.3637For more information see :ref:`cli`.3839Creating a Request Context40--------------------------4142The easiest way to create a proper request context from the shell is by
1 unmodified line
44us a :class:`~flask.ctx.RequestContext`:4546>>> ctx = app.test_request_context()4738Normally you would use the `with` statement to make this request object48Normally you would use the ``with`` statement to make this request object49active, but in the shell it's easier to use the50:meth:`~flask.ctx.RequestContext.push` and51:meth:`~flask.ctx.RequestContext.pop` methods by hand:52
44 unmodified lines
97with stuff you want to star import into your interactive session. There98you could also define some more helper methods for common things such as99initializing the database, dropping tables etc.10091Just put them into a module (like `shelltools` and import from there):101Just put them into a module (like `shelltools`) and import from there:102103>>> from shelltools import *
modified:docs/signals.rst+13 added-175 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 the split of a second. These temporary29subscribe to them for just a split second. These temporary30subscriptions are helpful for unittesting for example. Say you want to31know what templates were rendered as part of a request: signals allow you32to do exactly that.33
7 unmodified lines
41signal, you can use the :meth:`~blinker.base.Signal.disconnect` method.4243For all core Flask signals, the sender is the application that issued the44signal. When you subscribe to a signal, be sure to also provide a sender45unless you really want to listen for signals of all applications. This is45unless you really want to listen for signals from all applications. This is46especially true if you are developing an extension.4748Here for example a helper context manager that can be used to figure out49in a unittest which templates were rendered and what variables were passed48For example, here is a helper context manager that can be used in a unittest49to determine which templates were rendered and what variables were passed50to the template::5152 from flask import template_rendered53 from contextlib import contextmanager
22 unmodified lines
76Make sure to subscribe with an extra ``**extra`` argument so that your77calls don't fail if Flask introduces new arguments to the signals.7879All the template rendering in the code issued by the application `app`80in the body of the `with` block will now be recorded in the `templates`80in the body of the ``with`` block will now be recorded in the `templates`81variable. Whenever a template is rendered, the template object as well as82context are appended to it.8384Additionally there is a convenient helper method85(:meth:`~blinker.base.Signal.connected_to`). that allows you to85(:meth:`~blinker.base.Signal.connected_to`) that allows you to86temporarily subscribe a function to a signal with a context manager on87its own. Because the return value of the context manager cannot be88specified that way one has to pass the list in as argument::88specified that way, you have to pass the list in as an argument::8990 from flask import template_rendered9192 def captured_templates(app, recorded, **extra):
54 unmodified lines
147 def save(self):148 model_saved.send(self)149150Try to always pick a good sender. If you have a class that is emitting a151signal, pass `self` as sender. If you emitting a signal from a random151signal, pass ``self`` as sender. If you are emitting a signal from a random152function, you can pass ``current_app._get_current_object()`` as sender.153154.. admonition:: Passing Proxies as Senders155
27 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 before any request processing started but when the212 request context was set up. 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.10351352.. _blinker: http://pypi.python.org/pypi/blinker190.. _blinker: https://pypi.python.org/pypi/blinker
modified:docs/styleguide.rst+2 added-2 removed
106 unmodified lines
107Comparisons:108 - against arbitrary types: ``==`` and ``!=``109 - against singletons with ``is`` and ``is not`` (eg: ``foo is not110 None``)111 - never compare something with `True` or `False` (for example never111 - never compare something with ``True`` or ``False`` (for example never112 do ``foo == False``, do ``not foo`` instead)113114Negated containment checks:115 use ``foo not in bar`` instead of ``not foo in bar``
50 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+9 added-6 removed
7 unmodified lines
89This section only gives a very quick introduction into how Jinja210is integrated into Flask. If you want information on the template11engine's syntax itself, head over to the official `Jinja2 Template12Documentation <http://jinja.pocoo.org/2/documentation/templates>`_ for12Documentation <http://jinja.pocoo.org/docs/templates>`_ for13more information.1415Jinja Setup16-----------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
78 unmodified lines
107 This function converts the given object into JSON representation. This108 is for example very helpful if you try to generate JavaScript on the109 fly.110108 Note that inside `script` tags no escaping must take place, so make111 Note that inside ``script`` tags no escaping must take place, so make112 sure to disable escaping with ``|safe`` before Flask 0.10 if you intend110 to use it inside `script` tags:113 to use it inside ``script`` tags:114115 .. sourcecode:: html+jinja116117 <script type=text/javascript>
3 unmodified lines
121Controlling Autoescaping122------------------------123124Autoescaping is the concept of automatically escaping special characters122of you. Special characters in the sense of HTML (or XML, and thus XHTML)125for you. Special characters in the sense of HTML (or XML, and thus XHTML)126are ``&``, ``>``, ``<``, ``"`` as well as ``'``. Because these characters127carry specific meanings in documents on their own you have to replace them128by so called "entities" if you want to use them for text. Not doing so129would not only cause user frustration by the inability to use these
1 unmodified line
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+45 added-40 removed
9 unmodified lines
10improve 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 Werkzeug 14Flask 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.1819The Application20---------------2122First, we need an application to test; we will use the application from 23the :ref:`tutorial`. If you don't have that application yet, get the 22First, we need an application to test; we will use the application from23the :ref:`tutorial`. If you don't have that application yet, get the24sources from `the examples`_.2526.. _the examples:27 http://github.com/mitsuhiko/flask/tree/master/examples/flaskr/27 https://github.com/pallets/flask/tree/master/examples/flaskr/2829The Testing Skeleton30--------------------3132In order to test the application, we add a second module 33(`flaskr_tests.py`) and create a unittest skeleton there::32In order to test the application, we add a second module33(:file:`flaskr_tests.py`) and create a unittest skeleton there::3435 import os36 import flaskr36 from flaskr import flaskr37 import unittest38 import tempfile3940 class FlaskrTestCase(unittest.TestCase):4142 def setUp(self):43 self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()44 flaskr.app.config['TESTING'] = True44 flaskr.app.testing = True45 self.app = flaskr.app.test_client()46 with flaskr.app.app_context():46 flaskr.init_db()47 flaskr.init_db()4849 def tearDown(self):50 os.close(self.db_fd)51 os.unlink(flaskr.app.config['DATABASE'])
2 unmodified lines
54 unittest.main()5556The code in the :meth:`~unittest.TestCase.setUp` method creates a new test57client and initializes a new database. This function is called before57each individual test function is run. To delete the database after the 58each 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 the60``TESTING`` config flag is activated. What it does is disabling the error61``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.6464This test client will give us a simple interface to the application. We can 65trigger test requests to the application, and the client will also keep track 65This 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.6869Because SQLite3 is filesystem-based we can easily use the tempfile module70to create a temporary database and initialize it. The
17 unmodified lines
8889The First Test90--------------9191Now it's time to start testing the functionality of the application. 92Let's check that the application shows "No entries here so far" if we 92Now it's time to start testing the functionality of the application.93Let'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::9697 class FlaskrTestCase(unittest.TestCase):9899 def setUp(self):100 self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()101 flaskr.app.testing = True102 self.app = flaskr.app.test_client()103 with flaskr.app.app_context():101 flaskr.init_db()104 flaskr.init_db()105106 def tearDown(self):107 os.close(self.db_fd)108 os.unlink(flaskr.app.config['DATABASE'])109110 def test_empty_db(self):111 rv = self.app.get('/')109 assert 'No entries here so far' in rv.data112 assert b'No entries here so far' in rv.data113111Notice that our test functions begin with the word `test`; this allows 112:mod:`unittest` to automatically identify the method as a test to run. 114Notice that our test functions begin with the word `test`; this allows115:mod:`unittest` to automatically identify the method as a test to run.116114By using `self.app.get` we can send an HTTP `GET` request to the application with 115the given path. The return value will be a :class:`~flask.Flask.response_class` object. 117By using `self.app.get` we can send an HTTP ``GET`` request to the application with118the given path. The return value will be a :class:`~flask.Flask.response_class` object.119We can now use the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect117the return value (as string) from the application. In this case, we ensure that 120the return value (as string) from the application. In this case, we ensure that121``'No entries here so far'`` is part of the output.122123Run it again and you should see one passing test::124
8 unmodified lines
133------------------134135The majority of the functionality of our application is only available for136the administrative user, so we need a way to log our test client in and out134of the application. To do this, we fire some requests to the login and logout 135pages with the required form data (username and password). And because the 137of the application. To do this, we fire some requests to the login and logout138pages with the required form data (username and password). And because the139login and logout pages redirect, we tell the client to `follow_redirects`.140141Add the following two methods to your `FlaskrTestCase` class::142
10 unmodified lines
153invalid credentials. Add this new test to the class::154155 def test_login_logout(self):156 rv = self.login('admin', 'default')154 assert 'You were logged in' in rv.data157 assert b'You were logged in' in rv.data158 rv = self.logout()156 assert 'You were logged out' in rv.data159 assert b'You were logged out' in rv.data160 rv = self.login('adminx', 'default')158 assert 'Invalid username' in rv.data161 assert b'Invalid username' in rv.data162 rv = self.login('admin', 'defaultx')160 assert 'Invalid password' in rv.data163 assert b'Invalid password' in rv.data164165Test Adding Messages166--------------------167
5 unmodified lines
173 rv = self.app.post('/add', data=dict(174 title='<Hello>',175 text='<strong>HTML</strong> allowed here'176 ), follow_redirects=True)174 assert 'No entries here so far' not in rv.data175 assert '&lt;Hello&gt;' in rv.data176 assert '<strong>HTML</strong> allowed here' in rv.data177 assert b'No entries here so far' not in rv.data178 assert b'&lt;Hello&gt;' in rv.data179 assert b'<strong>HTML</strong> allowed here' in rv.data180181Here we check that HTML is allowed in the text but not in the title,182which is the intended behavior.183
11 unmodified lines
195suite.196197198.. _MiniTwit Example:196 http://github.com/mitsuhiko/flask/tree/master/examples/minitwit/199 https://github.com/pallets/flask/tree/master/examples/minitwit/200201202Other Testing Tricks203--------------------204205Besides using the test client as shown above, there is also the206:meth:`~flask.Flask.test_request_context` method that can be used204in combination with the `with` statement to activate a request context207in combination with the ``with`` statement to activate a request context208temporarily. With this you can access the :class:`~flask.request`,209:class:`~flask.g` and :class:`~flask.session` objects like in view210functions. Here is a full example that demonstrates this approach::211212 import flask213214 app = flask.Flask(__name__)215216 with app.test_request_context('/?name=Peter'):217 assert flask.request.path == '/'
6 unmodified lines
224there does not seem to be a good way to do that, consider switching to225application factories (see :ref:`app-factories`).226227Note however that if you are using a test request context, the223:meth:`~flask.Flask.before_request` functions are not automatically called224same for :meth:`~flask.Flask.after_request` functions. However228:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`229functions are not called automatically. However230:meth:`~flask.Flask.teardown_request` functions are indeed executed when226the test request context leaves the `with` block. If you do want the231the test request context leaves the ``with`` block. If you do want the232:meth:`~flask.Flask.before_request` functions to be called as well, you233need to call :meth:`~flask.Flask.preprocess_request` yourself::234235 app = flask.Flask(__name__)
39 unmodified lines
275 g.user = user276 return user277278For a test it would be nice to override this user from the outside without274having to change some code. This can trivially be accomplished with279having to change some code. This can be accomplished with280hooking the :data:`flask.appcontext_pushed` signal::281282 from contextlib import contextmanager278 from flask import appcontext_pushed283 from flask import appcontext_pushed, g284285 @contextmanager286 def user_set(app, user):287 def handler(sender, **kwargs):
23 unmodified lines
311312Sometimes it is helpful to trigger a regular request but still keep the313context around for a little longer so that additional introspection can314happen. With Flask 0.4 this is possible by using the310:meth:`~flask.Flask.test_client` with a `with` block::315:meth:`~flask.Flask.test_client` with a ``with`` block::316317 app = flask.Flask(__name__)318319 with app.test_client() as c:320 rv = c.get('/?tequila=42')321 assert request.args['tequila'] == '42'322323If you were to use just the :meth:`~flask.Flask.test_client` without319the `with` block, the `assert` would fail with an error because `request`324the ``with`` block, the ``assert`` would fail with an error because `request`325is no longer available (because you are trying to use it outside of the actual request).326327328Accessing and Modifying Sessions
29 unmodified lines
modified:docs/upgrading.rst+124 added-24 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 `easy_install` command to upgrade your Flask18installation, make sure to pass it the ``-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-012:2324Version 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`````````7778Flask 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.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`.14546.. _Flask-OldSessions: http://packages.python.org/Flask-OldSessions/146.. _Flask-OldSessions: https://pythonhosted.org/Flask-OldSessions/147148Version 0.9149-----------150
12 unmodified lines
163If you maintain an extension that was using :data:`~flask._request_ctx_stack`164before, please consider changing to :data:`~flask._app_ctx_stack` if it makes165sense for your extension. For instance, the app context stack makes sense for166extensions which connect to databases. Using the app context stack instead of67the request context stack will make extensions more readily handle use cases 167the request context stack will make extensions more readily handle use cases168outside of requests.169170Version 0.8171-----------172173Flask introduced a new session interface system. We also noticed that74there 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.
2 unmodified lines
181:exc:`~werkzeug.exceptions.BadRequest` exception instead of letting the182default :exc:`ValueError` bubble up. This has the advantage that you no183longer have to handle that error to avoid an internal server error showing184up for the user. If you were catching this down explicitly in the past85as `ValueError` you will need to change this.185as :exc:`ValueError` you will need to change this.186187Due to a bug in the test client Flask 0.7 did not trigger teardown188handlers when the test client was used in a with statement. This was89since fixed but might require some changes in your testsuites if you189since fixed but might require some changes in your test suites if you190relied on this behavior.191192Version 0.7193-----------
3 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.200101The 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.py118 <https://raw.github.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
2 unmodified lines
225226 patch -p1 < patchfile.diff2272285. If you were using per-module template folders you need to move some129 templates around. Previously if you had a folder named ``templates``229 templates around. Previously if you had a folder named :file:`templates`230 next to a blueprint named ``admin`` the implicit template path131 automatically was ``admin/index.html`` for a template file called132 ``templates/index.html``. This no longer is the case. Now you need133 to name the template ``templates/admin/index.html``. The tool will231 automatically was :file:`admin/index.html` for a template file called232 :file:`templates/index.html`. This no longer is the case. Now you need233 to name the template :file:`templates/admin/index.html`. The tool will234 not detect this so you will have to do that on your own.235236Please 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.239140If 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 removed157in 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.
85 unmodified lines
347applications automatically, but there might be some cases where it fails348to upgrade. What changed?349350- Blueprints need explicit names. Modules had an automatic name251 guesssing scheme where the shortname for the module was taken from the351 guessing scheme where the shortname for the module was taken from the352 last part of the import module. The upgrade script tries to guess353 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 endpoint257 `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.362- Blueprints do not automatically provide static folders. They will363 also no longer automatically export templates from a folder called264 `templates` next to their location however but it can be enabled from364 :file:`templates` next to their location however but it can be enabled from365 the constructor. Same with static files: if you want to continue366 serving static files you need to tell the constructor explicitly the367 path to the static folder (which can be relative to the blueprint's368 module path).369- Rendering templates was simplified. Now the blueprints can provide370 template folders which are added to a general template searchpath.371 This means that you need to add another subfolder with the blueprint's272 name into that folder if you want ``blueprintname/template.html`` as372 name into that folder if you want :file:`blueprintname/template.html` as373 the template name.374275If 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.
5 unmodified lines
385Flask 0.6 comes with a backwards incompatible change which affects the386order of after-request handlers. Previously they were called in the order387of the registration, now they are called in reverse order. This change388was made so that Flask behaves more like people expected it to work and289how other systems handle request pre- and postprocessing. If you389how other systems handle request pre- and post-processing. If you390depend on the order of execution of post-request functions, be sure to391change the order.392393Another change that breaks backwards compatibility is that context394processors will no longer override values passed directly to the template295rendering 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.321- 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
modified:docs/views.rst+2 added-2 removed
44 unmodified lines
45:meth:`~flask.views.View.as_view` class method. The string you pass to46that function is the name of the endpoint that view will then have. But47this by itself is not helpful, so let's refactor the code a bit::4849 4950 from flask.views import View5152 class ListView(View):53
16 unmodified lines
70 return User.query.all()7172This of course is not that helpful for such a small example, but it's good73enough to explain the basic principle. When you have a class-based view74the question comes up what `self` points to. The way this works is that74the question comes up what ``self`` points to. The way this works is that75whenever the request is dispatched a new instance of the class is created76and the :meth:`~flask.views.View.dispatch_request` method is called with77the parameters from the URL rule. The class itself is instantiated with78the parameters passed to the :meth:`~flask.views.View.as_view` function.
159 unmodified lines
modified:examples/blueprintexample/simple_page/templates/pages/layout.html+2 added-2 removed
1<!doctype html>2<title>Simple Page Blueprint</title>3<div class=page>3<div class="page">4 <h1>This is blueprint example</h1>5 <p>6 A simple page blueprint is registered under / and /pages7 you can access it using this urls:7 you can access it using this URLs:8 <ul>9 <li><a href="{{ url_for('simple_page.show', page='hello') }}">/hello</a>10 <li><a href="{{ url_for('simple_page.show', page='world') }}">/world</a>11 </ul>
9 unmodified lines
deleted:examples/blueprintexample/blueprintexample_test.py-36 removed
1# -*- coding: utf-8 -*-2"""3 Blueprint Example Tests4 ~~~~~~~~~~~~~~56 Tests the Blueprint example app7"""8import blueprintexample9import unittest101112class BlueprintExampleTestCase(unittest.TestCase):1314 def setUp(self):15 self.app = blueprintexample.app.test_client()16 17 def test_urls(self):18 r = self.app.get('/')19 self.assertEquals(r.status_code, 200)20 21 r = self.app.get('/hello')22 self.assertEquals(r.status_code, 200)23 24 r = self.app.get('/world')25 self.assertEquals(r.status_code, 200)26 27 #second blueprint instance28 r = self.app.get('/pages/hello')29 self.assertEquals(r.status_code, 200)30 31 r = self.app.get('/pages/world')32 self.assertEquals(r.status_code, 200)33 34 35if __name__ == '__main__':36 unittest.main()
modified:examples/blueprintexample/blueprintexample.py+3 added-4 removed
2 unmodified lines
34app = Flask(__name__)5app.register_blueprint(simple_page)6# Blueprint can be registered many times7app.register_blueprint(simple_page, url_prefix='/pages') 7app.register_blueprint(simple_page, url_prefix='/pages')8910if __name__ == '__main__':11 app.run(debug=True)9if __name__=='__main__':10 app.run()
added:examples/blueprintexample/test_blueprintexample.py+33 added
1# -*- coding: utf-8 -*-2"""3 Blueprint Example Tests4 ~~~~~~~~~~~~~~56 Tests the Blueprint example app7"""8import pytest910import blueprintexample111213@pytest.fixture14def client():15 return blueprintexample.app.test_client()161718def test_urls(client):19 r = client.get('/')20 assert r.status_code == 2002122 r = client.get('/hello')23 assert r.status_code == 2002425 r = client.get('/world')26 assert r.status_code == 2002728 # second blueprint instance29 r = client.get('/pages/hello')30 assert r.status_code == 2003132 r = client.get('/pages/world')33 assert r.status_code == 200
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+76 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(request):20 db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()21 flaskr.app.config['TESTING'] = True22 client = flaskr.app.test_client()23 with flaskr.app.app_context():24 flaskr.init_db()2526 def teardown():27 os.close(db_fd)28 os.unlink(flaskr.app.config['DATABASE'])29 request.addfinalizer(teardown)3031 return client323334def login(client, username, password):35 return client.post('/login', data=dict(36 username=username,37 password=password38 ), follow_redirects=True)394041def logout(client):42 return client.get('/logout', follow_redirects=True)434445def test_empty_db(client):46 """Start with a blank database."""47 rv = client.get('/')48 assert b'No entries here so far' in rv.data495051def test_login_logout(client):52 """Make sure login and logout works"""53 rv = login(client, flaskr.app.config['USERNAME'],54 flaskr.app.config['PASSWORD'])55 assert b'You were logged in' in rv.data56 rv = logout(client)57 assert b'You were logged out' in rv.data58 rv = login(client, flaskr.app.config['USERNAME'] + 'x',59 flaskr.app.config['PASSWORD'])60 assert b'Invalid username' in rv.data61 rv = login(client, flaskr.app.config['USERNAME'],62 flaskr.app.config['PASSWORD'] + 'x')63 assert b'Invalid password' in rv.data646566def test_messages(client):67 """Test that messages work"""68 login(client, flaskr.app.config['USERNAME'],69 flaskr.app.config['PASSWORD'])70 rv = client.post('/add', data=dict(71 title='<Hello>',72 text='<strong>HTML</strong> allowed here'73 ), follow_redirects=True)74 assert b'No entries here so far' not in rv.data75 assert b'&lt;Hello&gt;' in rv.data76 assert b'<strong>HTML</strong> allowed here' in rv.data
added:examples/flaskr/.gitignore+2 added
1flaskr.db2.eggs/
deleted:examples/flaskr/flaskr_tests.py-75 removed
1# -*- coding: utf-8 -*-2"""3 Flaskr Tests4 ~~~~~~~~~~~~56 Tests the Flaskr application.78 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import os12import flaskr13import unittest14import tempfile151617class FlaskrTestCase(unittest.TestCase):1819 def setUp(self):20 """Before each test, set up a blank database"""21 self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()22 flaskr.app.config['TESTING'] = True23 self.app = flaskr.app.test_client()24 flaskr.init_db()2526 def tearDown(self):27 """Get rid of the database again after each test."""28 os.close(self.db_fd)29 os.unlink(flaskr.app.config['DATABASE'])3031 def login(self, username, password):32 return self.app.post('/login', data=dict(33 username=username,34 password=password35 ), follow_redirects=True)3637 def logout(self):38 return self.app.get('/logout', follow_redirects=True)3940 # testing functions4142 def test_empty_db(self):43 """Start with a blank database."""44 rv = self.app.get('/')45 assert b'No entries here so far' in rv.data4647 def test_login_logout(self):48 """Make sure login and logout works"""49 rv = self.login(flaskr.app.config['USERNAME'],50 flaskr.app.config['PASSWORD'])51 assert b'You were logged in' in rv.data52 rv = self.logout()53 assert b'You were logged out' in rv.data54 rv = self.login(flaskr.app.config['USERNAME'] + 'x',55 flaskr.app.config['PASSWORD'])56 assert b'Invalid username' in rv.data57 rv = self.login(flaskr.app.config['USERNAME'],58 flaskr.app.config['PASSWORD'] + 'x')59 assert b'Invalid password' in rv.data6061 def test_messages(self):62 """Test that messages work"""63 self.login(flaskr.app.config['USERNAME'],64 flaskr.app.config['PASSWORD'])65 rv = self.app.post('/add', data=dict(66 title='<Hello>',67 text='<strong>HTML</strong> allowed here'68 ), follow_redirects=True)69 assert b'No entries here so far' not in rv.data70 assert b'&lt;Hello&gt;' in rv.data71 assert b'<strong>HTML</strong> allowed here' in rv.data727374if __name__ == '__main__':75 unittest.main()
deleted:examples/flaskr/flaskr.py-109 removed
1# -*- coding: utf-8 -*-2"""3 Flaskr4 ~~~~~~56 A microblog example application written as Flask tutorial with7 Flask and sqlite3.89 :copyright: (c) 2014 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 """Creates the database tables."""42 with app.app_context():43 db = get_db()44 with app.open_resource('schema.sql', mode='r') as f:45 db.cursor().executescript(f.read())46 db.commit()474849def get_db():50 """Opens a new database connection if there is none yet for the51 current application context.52 """53 if not hasattr(g, 'sqlite_db'):54 g.sqlite_db = connect_db()55 return g.sqlite_db565758@app.teardown_appcontext59def close_db(error):60 """Closes the database again at the end of the request."""61 if hasattr(g, 'sqlite_db'):62 g.sqlite_db.close()636465@app.route('/')66def show_entries():67 db = get_db()68 cur = db.execute('select title, text from entries order by id desc')69 entries = cur.fetchall()70 return render_template('show_entries.html', entries=entries)717273@app.route('/add', methods=['POST'])74def add_entry():75 if not session.get('logged_in'):76 abort(401)77 db = get_db()78 db.execute('insert into entries (title, text) values (?, ?)',79 [request.form['title'], request.form['text']])80 db.commit()81 flash('New entry was successfully posted')82 return redirect(url_for('show_entries'))838485@app.route('/login', methods=['GET', 'POST'])86def login():87 error = None88 if request.method == 'POST':89 if request.form['username'] != app.config['USERNAME']:90 error = 'Invalid username'91 elif request.form['password'] != app.config['PASSWORD']:92 error = 'Invalid password'93 else:94 session['logged_in'] = True95 flash('You were logged in')96 return redirect(url_for('show_entries'))97 return render_template('login.html', error=error)9899100@app.route('/logout')101def logout():102 session.pop('logged_in', None)103 flash('You were logged out')104 return redirect(url_for('show_entries'))105106107if __name__ == '__main__':108 init_db()109 app.run()
added:examples/flaskr/MANIFEST.in+3 added
1graft flaskr/templates2graft flaskr/static3include flaskr/schema.sql
modified:examples/flaskr/README+20 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. now you can run the flaskr.py file with your17 python interpreter and the application will18 greet you on http://localhost:5000/19 16 2. install the app from the root of the project directory1718 pip install --editable .1920 3. Instruct flask to use the right application2122 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?3622 You betcha. Run the `flaskr_tests.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)
modified:examples/jqueryexample/templates/index.html+5 added-5 removed
1{% extends "layout.html" %}2{% block body %}3<script type=text/javascript>3<script type="text/javascript">4 $(function() {5 var submit_form = function(e) {6 $.getJSON($SCRIPT_ROOT + '/_add_numbers', {7 a: $('input[name="a"]').val(),
17 unmodified lines
25 });26</script>27<h1>jQuery Example</h1>28<p>29 <input type=text size=5 name=a> +30 <input type=text size=5 name=b> =31 <span id=result>?</span>32<p><a href=# id=calculate>calculate server side</a>29 <input type="text" size="5" name="a"> +30 <input type="text" size="5" name="b"> =31 <span id="result">?</span>32<p><a href=# id="calculate">calculate server side</a>33{% endblock %}
modified:examples/jqueryexample/templates/layout.html+2 added-2 removed
1<!doctype html>2<title>jQuery Example</title>3<script type=text/javascript3<script type="text/javascript"4 src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>5<script type=text/javascript>5<script type="text/javascript">6 var $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};7</script>8{% block body %}{% endblock %}
modified:examples/jqueryexample/jqueryexample.py+1 added-2 removed
3 unmodified lines
4 ~~~~~~~~~~~~~~56 A simple application that shows how Flask and jQuery get along.78 :copyright: (c) 2014 by Armin Ronacher.8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from flask import Flask, jsonify, render_template, request12app = Flask(__name__)
10 unmodified lines
23@app.route('/')24def index():25 return render_template('index.html')262727if __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+151 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(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/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_tests.py-149 removed
1# -*- coding: utf-8 -*-2"""3 MiniTwit Tests4 ~~~~~~~~~~~~~~56 Tests the MiniTwit application.78 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import os12import minitwit13import unittest14import tempfile151617class MiniTwitTestCase(unittest.TestCase):1819 def setUp(self):20 """Before each test, set up a blank database"""21 self.db_fd, minitwit.app.config['DATABASE'] = tempfile.mkstemp()22 self.app = minitwit.app.test_client()23 minitwit.init_db()2425 def tearDown(self):26 """Get rid of the database again after each test."""27 os.close(self.db_fd)28 os.unlink(minitwit.app.config['DATABASE'])2930 # helper functions3132 def register(self, 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 self.app.post('/register', data={39 'username': username,40 'password': password,41 'password2': password2,42 'email': email,43 }, follow_redirects=True)4445 def login(self, username, password):46 """Helper function to login"""47 return self.app.post('/login', data={48 'username': username,49 'password': password50 }, follow_redirects=True)5152 def register_and_login(self, username, password):53 """Registers and logs in in one go"""54 self.register(username, password)55 return self.login(username, password)5657 def logout(self):58 """Helper function to logout"""59 return self.app.get('/logout', follow_redirects=True)6061 def add_message(self, text):62 """Records a message"""63 rv = self.app.post('/add_message', data={'text': text},64 follow_redirects=True)65 if text:66 assert b'Your message was recorded' in rv.data67 return rv6869 # testing functions7071 def test_register(self):72 """Make sure registering works"""73 rv = self.register('user1', 'default')74 assert b'You were successfully registered ' \75 b'and can login now' in rv.data76 rv = self.register('user1', 'default')77 assert b'The username is already taken' in rv.data78 rv = self.register('', 'default')79 assert b'You have to enter a username' in rv.data80 rv = self.register('meh', '')81 assert b'You have to enter a password' in rv.data82 rv = self.register('meh', 'x', 'y')83 assert b'The two passwords do not match' in rv.data84 rv = self.register('meh', 'foo', email='broken')85 assert b'You have to enter a valid email address' in rv.data8687 def test_login_logout(self):88 """Make sure logging in and logging out works"""89 rv = self.register_and_login('user1', 'default')90 assert b'You were logged in' in rv.data91 rv = self.logout()92 assert b'You were logged out' in rv.data93 rv = self.login('user1', 'wrongpassword')94 assert b'Invalid password' in rv.data95 rv = self.login('user2', 'wrongpassword')96 assert b'Invalid username' in rv.data9798 def test_message_recording(self):99 """Check if adding messages works"""100 self.register_and_login('foo', 'default')101 self.add_message('test message 1')102 self.add_message('<test message 2>')103 rv = self.app.get('/')104 assert b'test message 1' in rv.data105 assert b'&lt;test message 2&gt;' in rv.data106107 def test_timelines(self):108 """Make sure that timelines work"""109 self.register_and_login('foo', 'default')110 self.add_message('the message by foo')111 self.logout()112 self.register_and_login('bar', 'default')113 self.add_message('the message by bar')114 rv = self.app.get('/public')115 assert b'the message by foo' in rv.data116 assert b'the message by bar' in rv.data117118 # bar's timeline should just show bar's message119 rv = self.app.get('/')120 assert b'the message by foo' not in rv.data121 assert b'the message by bar' in rv.data122123 # now let's follow foo124 rv = self.app.get('/foo/follow', follow_redirects=True)125 assert b'You are now following &#34;foo&#34;' in rv.data126127 # we should now see foo's message128 rv = self.app.get('/')129 assert b'the message by foo' in rv.data130 assert b'the message by bar' in rv.data131132 # but on the user's page we only want the user's message133 rv = self.app.get('/bar')134 assert b'the message by foo' not in rv.data135 assert b'the message by bar' in rv.data136 rv = self.app.get('/foo')137 assert b'the message by foo' in rv.data138 assert b'the message by bar' not in rv.data139140 # now unfollow and check if that worked141 rv = self.app.get('/foo/unfollow', follow_redirects=True)142 assert b'You are no longer following &#34;foo&#34;' in rv.data143 rv = self.app.get('/')144 assert b'the message by foo' not in rv.data145 assert b'the message by bar' in rv.data146147148if __name__ == '__main__':149 unittest.main()
deleted:examples/minitwit/minitwit.py-255 removed
1# -*- coding: utf-8 -*-2"""3 MiniTwit4 ~~~~~~~~56 A microblogging application written with Flask and sqlite3.78 :copyright: (c) 2014 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 """Creates the database tables."""54 with app.app_context():55 db = get_db()56 with app.open_resource('schema.sql', mode='r') as f:57 db.cursor().executescript(f.read())58 db.commit()596061def query_db(query, args=(), one=False):62 """Queries the database and returns a list of dictionaries."""63 cur = get_db().execute(query, args)64 rv = cur.fetchall()65 return (rv[0] if rv else None) if one else rv666768def get_user_id(username):69 """Convenience method to look up the id for a username."""70 rv = query_db('select user_id from user where username = ?',71 [username], one=True)72 return rv[0] if rv else None737475def format_datetime(timestamp):76 """Format a timestamp for display."""77 return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d @ %H:%M')787980def gravatar_url(email, size=80):81 """Return the gravatar image for the given email address."""82 return 'http://www.gravatar.com/avatar/%s?d=identicon&s=%d' % \83 (md5(email.strip().lower().encode('utf-8')).hexdigest(), size)848586@app.before_request87def before_request():88 g.user = None89 if 'user_id' in session:90 g.user = query_db('select * from user where user_id = ?',91 [session['user_id']], one=True)929394@app.route('/')95def timeline():96 """Shows a users timeline or if no user is logged in it will97 redirect to the public timeline. This timeline shows the user's98 messages as well as all the messages of followed users.99 """100 if not g.user:101 return redirect(url_for('public_timeline'))102 return render_template('timeline.html', messages=query_db('''103 select message.*, user.* from message, user104 where message.author_id = user.user_id and (105 user.user_id = ? or106 user.user_id in (select whom_id from follower107 where who_id = ?))108 order by message.pub_date desc limit ?''',109 [session['user_id'], session['user_id'], PER_PAGE]))110111112@app.route('/public')113def public_timeline():114 """Displays the latest messages of all users."""115 return render_template('timeline.html', messages=query_db('''116 select message.*, user.* from message, user117 where message.author_id = user.user_id118 order by message.pub_date desc limit ?''', [PER_PAGE]))119120121@app.route('/<username>')122def user_timeline(username):123 """Display's a users tweets."""124 profile_user = query_db('select * from user where username = ?',125 [username], one=True)126 if profile_user is None:127 abort(404)128 followed = False129 if g.user:130 followed = query_db('''select 1 from follower where131 follower.who_id = ? and follower.whom_id = ?''',132 [session['user_id'], profile_user['user_id']],133 one=True) is not None134 return render_template('timeline.html', messages=query_db('''135 select message.*, user.* from message, user where136 user.user_id = message.author_id and user.user_id = ?137 order by message.pub_date desc limit ?''',138 [profile_user['user_id'], PER_PAGE]), followed=followed,139 profile_user=profile_user)140141142@app.route('/<username>/follow')143def follow_user(username):144 """Adds the current user as follower of the given user."""145 if not g.user:146 abort(401)147 whom_id = get_user_id(username)148 if whom_id is None:149 abort(404)150 db = get_db()151 db.execute('insert into follower (who_id, whom_id) values (?, ?)',152 [session['user_id'], whom_id])153 db.commit()154 flash('You are now following "%s"' % username)155 return redirect(url_for('user_timeline', username=username))156157158@app.route('/<username>/unfollow')159def unfollow_user(username):160 """Removes the current user as follower of the given user."""161 if not g.user:162 abort(401)163 whom_id = get_user_id(username)164 if whom_id is None:165 abort(404)166 db = get_db()167 db.execute('delete from follower where who_id=? and whom_id=?',168 [session['user_id'], whom_id])169 db.commit()170 flash('You are no longer following "%s"' % username)171 return redirect(url_for('user_timeline', username=username))172173174@app.route('/add_message', methods=['POST'])175def add_message():176 """Registers a new message for the user."""177 if 'user_id' not in session:178 abort(401)179 if request.form['text']:180 db = get_db()181 db.execute('''insert into message (author_id, text, pub_date)182 values (?, ?, ?)''', (session['user_id'], request.form['text'],183 int(time.time())))184 db.commit()185 flash('Your message was recorded')186 return redirect(url_for('timeline'))187188189@app.route('/login', methods=['GET', 'POST'])190def login():191 """Logs the user in."""192 if g.user:193 return redirect(url_for('timeline'))194 error = None195 if request.method == 'POST':196 user = query_db('''select * from user where197 username = ?''', [request.form['username']], one=True)198 if user is None:199 error = 'Invalid username'200 elif not check_password_hash(user['pw_hash'],201 request.form['password']):202 error = 'Invalid password'203 else:204 flash('You were logged in')205 session['user_id'] = user['user_id']206 return redirect(url_for('timeline'))207 return render_template('login.html', error=error)208209210@app.route('/register', methods=['GET', 'POST'])211def register():212 """Registers the user."""213 if g.user:214 return redirect(url_for('timeline'))215 error = None216 if request.method == 'POST':217 if not request.form['username']:218 error = 'You have to enter a username'219 elif not request.form['email'] or \220 '@' not in request.form['email']:221 error = 'You have to enter a valid email address'222 elif not request.form['password']:223 error = 'You have to enter a password'224 elif request.form['password'] != request.form['password2']:225 error = 'The two passwords do not match'226 elif get_user_id(request.form['username']) is not None:227 error = 'The username is already taken'228 else:229 db = get_db()230 db.execute('''insert into user (231 username, email, pw_hash) values (?, ?, ?)''',232 [request.form['username'], request.form['email'],233 generate_password_hash(request.form['password'])])234 db.commit()235 flash('You were successfully registered and can login now')236 return redirect(url_for('login'))237 return render_template('register.html', error=error)238239240@app.route('/logout')241def logout():242 """Logs the user out."""243 flash('You were logged out')244 session.pop('user_id', None)245 return redirect(url_for('public_timeline'))246247248# add some filters to jinja249app.jinja_env.filters['datetimeformat'] = format_datetime250app.jinja_env.filters['gravatar'] = gravatar_url251252253if __name__ == '__main__':254 init_db()255 app.run()
modified:examples/minitwit/README+18 added-7 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 python shell and run this:17 2. install the app from the root of the project directory1819 >>> from minitwit import init_db; init_db()19 pip install --editable .2021 3. now you can run the minitwit.py file with your22 python interpreter and the application will23 greet you on http://localhost:5000/24 21 3. tell flask about the right application:2223 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?3727 You betcha. Run the `minitwit_tests.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)
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-59 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'565758if __name__ == '__main__':59 app.run()
modified:flask/ext/__init__.py+1 added-1 removed
12 unmodified lines
1314 We're switching from namespace packages because it was just too painful for15 everybody involved.1617 :copyright: (c) 2014 by Armin Ronacher.17 :copyright: (c) 2015 by Armin Ronacher.18 :license: BSD, see LICENSE for more details.19"""2021
8 unmodified lines
deleted:flask/testsuite/static/config.json-4 removed
1{2 "TEST_KEY": "foo",3 "SECRET_KEY": "devkey"4}
deleted:flask/testsuite/static/index.html-1 removed
1<h1>Hello World!</h1>
deleted:flask/testsuite/templates/nested/nested.txt-1 removed
1I'm nested
deleted:flask/testsuite/templates/_macro.html-1 removed
1{% macro hello(name) %}Hello {{ name }}!{% endmacro %}
deleted:flask/testsuite/templates/context_template.html-1 removed
1<p>{{ value }}|{{ injected_value }}
deleted:flask/testsuite/templates/escaping_template.html-6 removed
1{{ text }}2{{ html }}3{% autoescape false %}{{ text }}4{{ html }}{% endautoescape %}5{% autoescape true %}{{ text }}6{{ html }}{% endautoescape %}
deleted:flask/testsuite/templates/mail.txt-1 removed
1{{ foo}} Mail
deleted:flask/testsuite/templates/simple_template.html-1 removed
1<h1>{{ whiskey }}</h1>
deleted:flask/testsuite/templates/template_filter.html-1 removed
1{{ value|super_reverse }}
deleted:flask/testsuite/templates/template_test.html-3 removed
1{% if value is boolean %}2 Success!3{% endif %}
deleted:flask/testsuite/test_apps/blueprintapp/apps/admin/static/css/test.css-1 removed
1/* nested file */
deleted:flask/testsuite/test_apps/blueprintapp/apps/admin/static/test.txt-1 removed
1Admin File
deleted:flask/testsuite/test_apps/blueprintapp/apps/admin/templates/admin/index.html-1 removed
1Hello from the Admin
deleted:flask/testsuite/test_apps/blueprintapp/apps/admin/__init__.py-15 removed
1from flask import Blueprint, render_template23admin = Blueprint('admin', __name__, url_prefix='/admin',4 template_folder='templates',5 static_folder='static')678@admin.route('/')9def index():10 return render_template('admin/index.html')111213@admin.route('/index2')14def index2():15 return render_template('./admin/index.html')
deleted:flask/testsuite/test_apps/blueprintapp/apps/frontend/templates/frontend/index.html-1 removed
1Hello from the Frontend
deleted:flask/testsuite/test_apps/blueprintapp/apps/frontend/__init__.py-8 removed
1from flask import Blueprint, render_template23frontend = Blueprint('frontend', __name__, template_folder='templates')456@frontend.route('/')7def index():8 return render_template('frontend/index.html')
deleted:flask/testsuite/test_apps/blueprintapp/apps/__init__.py
deleted:flask/testsuite/test_apps/blueprintapp/__init__.py-7 removed
1from flask import Flask23app = Flask(__name__)4from blueprintapp.apps.admin import admin5from blueprintapp.apps.frontend import frontend6app.register_blueprint(admin)7app.register_blueprint(frontend)
deleted:flask/testsuite/test_apps/config_package_app/__init__.py-4 removed
1import os2import flask3here = os.path.abspath(os.path.dirname(__file__))4app = flask.Flask(__name__)
deleted:flask/testsuite/test_apps/flask_broken/__init__.py-2 removed
1import flask.ext.broken.b2import missing_module
deleted:flask/testsuite/test_apps/flask_broken/b.py
deleted:flask/testsuite/test_apps/flask_newext_package/__init__.py-1 removed
1ext_id = 'newext_package'
deleted:flask/testsuite/test_apps/flask_newext_package/submodule.py-2 removed
1def test_function():2 return 42
deleted:flask/testsuite/test_apps/flaskext/oldext_package/__init__.py-1 removed
1ext_id = 'oldext_package'
deleted:flask/testsuite/test_apps/flaskext/oldext_package/submodule.py-2 removed
1def test_function():2 return 42
deleted:flask/testsuite/test_apps/flaskext/__init__.py
deleted:flask/testsuite/test_apps/flaskext/oldext_simple.py-1 removed
1ext_id = 'oldext_simple'
deleted:flask/testsuite/test_apps/lib/python2.5/site-packages/site_package/__init__.py-3 removed
1import flask23app = flask.Flask(__name__)
deleted:flask/testsuite/test_apps/lib/python2.5/site-packages/site_app.py-3 removed
1import flask23app = flask.Flask(__name__)
deleted:flask/testsuite/test_apps/lib/python2.5/site-packages/SiteEgg.eggbinary

A binary file, deleted.

deleted:flask/testsuite/test_apps/moduleapp/apps/admin/static/css/test.css-1 removed
1/* nested file */
deleted:flask/testsuite/test_apps/moduleapp/apps/admin/static/test.txt-1 removed
1Admin File
deleted:flask/testsuite/test_apps/moduleapp/apps/admin/templates/index.html-1 removed
1Hello from the Admin
deleted:flask/testsuite/test_apps/moduleapp/apps/admin/__init__.py-14 removed
1from flask import Module, render_template234admin = Module(__name__, url_prefix='/admin')567@admin.route('/')8def index():9 return render_template('admin/index.html')101112@admin.route('/index2')13def index2():14 return render_template('./admin/index.html')
deleted:flask/testsuite/test_apps/moduleapp/apps/frontend/templates/index.html-1 removed
1Hello from the Frontend
deleted:flask/testsuite/test_apps/moduleapp/apps/frontend/__init__.py-9 removed
1from flask import Module, render_template234frontend = Module(__name__)567@frontend.route('/')8def index():9 return render_template('frontend/index.html')
deleted:flask/testsuite/test_apps/moduleapp/apps/__init__.py
deleted:flask/testsuite/test_apps/moduleapp/__init__.py-7 removed
1from flask import Flask23app = Flask(__name__)4from moduleapp.apps.admin import admin5from moduleapp.apps.frontend import frontend6app.register_module(admin)7app.register_module(frontend)
deleted:flask/testsuite/test_apps/path/installed_package/__init__.py-3 removed
1import flask23app = flask.Flask(__name__)
deleted:flask/testsuite/test_apps/subdomaintestmodule/static/hello.txt-1 removed
1Hello Subdomain
deleted:flask/testsuite/test_apps/subdomaintestmodule/__init__.py-4 removed
1from flask import Module234mod = Module(__name__, 'foo', subdomain='foo')
deleted:flask/testsuite/test_apps/config_module_app.py-4 removed
1import os2import flask3here = os.path.abspath(os.path.dirname(__file__))4app = flask.Flask(__name__)
deleted:flask/testsuite/test_apps/flask_newext_simple.py-1 removed
1ext_id = 'newext_simple'
deleted:flask/testsuite/test_apps/importerror.py-2 removed
1# NoImportsTestCase2raise NotImplementedError
deleted:flask/testsuite/test_apps/main_app.py-4 removed
1import flask23# Test Flask initialization with main module.4app = flask.Flask('__main__')
deleted:flask/testsuite/__init__.py-252 removed
1# -*- coding: utf-8 -*-2"""3 flask.testsuite4 ~~~~~~~~~~~~~~~56 Tests Flask itself. The majority of Flask is already tested7 as part of Werkzeug.89 :copyright: (c) 2014 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213from __future__ import print_function1415import os16import sys17import flask18import warnings19import unittest20from functools import update_wrapper21from contextlib import contextmanager22from werkzeug.utils import import_string, find_modules23from flask._compat import reraise, StringIO242526def add_to_path(path):27 """Adds an entry to sys.path if it's not already there. This does28 not append it but moves it to the front so that we can be sure it29 is loaded.30 """31 if not os.path.isdir(path):32 raise RuntimeError('Tried to add nonexisting path')3334 def _samefile(x, y):35 if x == y:36 return True37 try:38 return os.path.samefile(x, y)39 except (IOError, OSError, AttributeError):40 # Windows has no samefile41 return False42 sys.path[:] = [x for x in sys.path if not _samefile(path, x)]43 sys.path.insert(0, path)444546def iter_suites():47 """Yields all testsuites."""48 for module in find_modules(__name__):49 mod = import_string(module)50 if hasattr(mod, 'suite'):51 yield mod.suite()525354def find_all_tests(suite):55 """Yields all the tests and their names from a given suite."""56 suites = [suite]57 while suites:58 s = suites.pop()59 try:60 suites.extend(s)61 except TypeError:62 yield s, '%s.%s.%s' % (63 s.__class__.__module__,64 s.__class__.__name__,65 s._testMethodName66 )676869@contextmanager70def catch_warnings():71 """Catch warnings in a with block in a list"""72 # make sure deprecation warnings are active in tests73 warnings.simplefilter('default', category=DeprecationWarning)7475 filters = warnings.filters76 warnings.filters = filters[:]77 old_showwarning = warnings.showwarning78 log = []79 def showwarning(message, category, filename, lineno, file=None, line=None):80 log.append(locals())81 try:82 warnings.showwarning = showwarning83 yield log84 finally:85 warnings.filters = filters86 warnings.showwarning = old_showwarning878889@contextmanager90def catch_stderr():91 """Catch stderr in a StringIO"""92 old_stderr = sys.stderr93 sys.stderr = rv = StringIO()94 try:95 yield rv96 finally:97 sys.stderr = old_stderr9899100def emits_module_deprecation_warning(f):101 def new_f(self, *args, **kwargs):102 with catch_warnings() as log:103 f(self, *args, **kwargs)104 self.assert_true(log, 'expected deprecation warning')105 for entry in log:106 self.assert_in('Modules are deprecated', str(entry['message']))107 return update_wrapper(new_f, f)108109110class FlaskTestCase(unittest.TestCase):111 """Baseclass for all the tests that Flask uses. Use these methods112 for testing instead of the camelcased ones in the baseclass for113 consistency.114 """115116 def ensure_clean_request_context(self):117 # make sure we're not leaking a request context since we are118 # testing flask internally in debug mode in a few cases119 leaks = []120 while flask._request_ctx_stack.top is not None:121 leaks.append(flask._request_ctx_stack.pop())122 self.assert_equal(leaks, [])123124 def setup(self):125 pass126127 def teardown(self):128 pass129130 def setUp(self):131 self.setup()132133 def tearDown(self):134 unittest.TestCase.tearDown(self)135 self.ensure_clean_request_context()136 self.teardown()137138 def assert_equal(self, x, y):139 return self.assertEqual(x, y)140141 def assert_raises(self, exc_type, callable=None, *args, **kwargs):142 catcher = _ExceptionCatcher(self, exc_type)143 if callable is None:144 return catcher145 with catcher:146 callable(*args, **kwargs)147148 def assert_true(self, x, msg=None):149 self.assertTrue(x, msg)150151 def assert_false(self, x, msg=None):152 self.assertFalse(x, msg)153154 def assert_in(self, x, y):155 self.assertIn(x, y)156157 def assert_not_in(self, x, y):158 self.assertNotIn(x, y)159160 def assert_isinstance(self, obj, cls):161 self.assertIsInstance(obj, cls)162163 if sys.version_info[:2] == (2, 6):164 def assertIn(self, x, y):165 assert x in y, "%r unexpectedly not in %r" % (x, y)166167 def assertNotIn(self, x, y):168 assert x not in y, "%r unexpectedly in %r" % (x, y)169170 def assertIsInstance(self, x, y):171 assert isinstance(x, y), "not isinstance(%r, %r)" % (x, y)172173174class _ExceptionCatcher(object):175176 def __init__(self, test_case, exc_type):177 self.test_case = test_case178 self.exc_type = exc_type179180 def __enter__(self):181 return self182183 def __exit__(self, exc_type, exc_value, tb):184 exception_name = self.exc_type.__name__185 if exc_type is None:186 self.test_case.fail('Expected exception of type %r' %187 exception_name)188 elif not issubclass(exc_type, self.exc_type):189 reraise(exc_type, exc_value, tb)190 return True191192193class BetterLoader(unittest.TestLoader):194 """A nicer loader that solves two problems. First of all we are setting195 up tests from different sources and we're doing this programmatically196 which breaks the default loading logic so this is required anyways.197 Secondly this loader has a nicer interpolation for test names than the198 default one so you can just do ``run-tests.py ViewTestCase`` and it199 will work.200 """201202 def getRootSuite(self):203 return suite()204205 def loadTestsFromName(self, name, module=None):206 root = self.getRootSuite()207 if name == 'suite':208 return root209210 all_tests = []211 for testcase, testname in find_all_tests(root):212 if testname == name or \213 testname.endswith('.' + name) or \214 ('.' + name + '.') in testname or \215 testname.startswith(name + '.'):216 all_tests.append(testcase)217218 if not all_tests:219 raise LookupError('could not find test case for "%s"' % name)220221 if len(all_tests) == 1:222 return all_tests[0]223 rv = unittest.TestSuite()224 for test in all_tests:225 rv.addTest(test)226 return rv227228229def setup_path():230 add_to_path(os.path.abspath(os.path.join(231 os.path.dirname(__file__), 'test_apps')))232233234def suite():235 """A testsuite that has all the Flask tests. You can use this236 function to integrate the Flask tests into your own testsuite237 in case you want to test that monkeypatches to Flask do not238 break it.239 """240 setup_path()241 suite = unittest.TestSuite()242 for other_suite in iter_suites():243 suite.addTest(other_suite)244 return suite245246247def main():248 """Runs the testsuite as command line application."""249 try:250 unittest.main(testLoader=BetterLoader(), defaultTest='suite')251 except Exception as e:252 print('Error: %s' % e)
deleted:flask/testsuite/appctx.py-118 removed
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.appctx4 ~~~~~~~~~~~~~~~~~~~~~~56 Tests the application context.78 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import flask13import unittest14from flask.testsuite import FlaskTestCase151617class AppContextTestCase(FlaskTestCase):1819 def test_basic_url_generation(self):20 app = flask.Flask(__name__)21 app.config['SERVER_NAME'] = 'localhost'22 app.config['PREFERRED_URL_SCHEME'] = 'https'2324 @app.route('/')25 def index():26 pass2728 with app.app_context():29 rv = flask.url_for('index')30 self.assert_equal(rv, 'https://localhost/')3132 def test_url_generation_requires_server_name(self):33 app = flask.Flask(__name__)34 with app.app_context():35 with self.assert_raises(RuntimeError):36 flask.url_for('index')3738 def test_url_generation_without_context_fails(self):39 with self.assert_raises(RuntimeError):40 flask.url_for('index')4142 def test_request_context_means_app_context(self):43 app = flask.Flask(__name__)44 with app.test_request_context():45 self.assert_equal(flask.current_app._get_current_object(), app)46 self.assert_equal(flask._app_ctx_stack.top, None)4748 def test_app_context_provides_current_app(self):49 app = flask.Flask(__name__)50 with app.app_context():51 self.assert_equal(flask.current_app._get_current_object(), app)52 self.assert_equal(flask._app_ctx_stack.top, None)5354 def test_app_tearing_down(self):55 cleanup_stuff = []56 app = flask.Flask(__name__)57 @app.teardown_appcontext58 def cleanup(exception):59 cleanup_stuff.append(exception)6061 with app.app_context():62 pass6364 self.assert_equal(cleanup_stuff, [None])6566 def test_app_tearing_down_with_previous_exception(self):67 cleanup_stuff = []68 app = flask.Flask(__name__)69 @app.teardown_appcontext70 def cleanup(exception):71 cleanup_stuff.append(exception)7273 try:74 raise Exception('dummy')75 except Exception:76 pass7778 with app.app_context():79 pass8081 self.assert_equal(cleanup_stuff, [None])8283 def test_custom_app_ctx_globals_class(self):84 class CustomRequestGlobals(object):85 def __init__(self):86 self.spam = 'eggs'87 app = flask.Flask(__name__)88 app.app_ctx_globals_class = CustomRequestGlobals89 with app.app_context():90 self.assert_equal(91 flask.render_template_string('{{ g.spam }}'), 'eggs')9293 def test_context_refcounts(self):94 called = []95 app = flask.Flask(__name__)96 @app.teardown_request97 def teardown_req(error=None):98 called.append('request')99 @app.teardown_appcontext100 def teardown_app(error=None):101 called.append('app')102 @app.route('/')103 def index():104 with flask._app_ctx_stack.top:105 with flask._request_ctx_stack.top:106 pass107 self.assert_true(flask._request_ctx_stack.top.request.environ108 ['werkzeug.request'] is not None)109 return u''110 c = app.test_client()111 c.get('/')112 self.assertEqual(called, ['request', 'app'])113114115def suite():116 suite = unittest.TestSuite()117 suite.addTest(unittest.makeSuite(AppContextTestCase))118 return suite
deleted:flask/testsuite/basic.py-1405 removed
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.basic4 ~~~~~~~~~~~~~~~~~~~~~56 The basic functionality.78 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import re13import uuid14import time15import flask16import pickle17import unittest18from datetime import datetime19from threading import Thread20from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning21from flask._compat import text_type22from werkzeug.exceptions import BadRequest, NotFound23from werkzeug.http import parse_date24from werkzeug.routing import BuildError252627class BasicFunctionalityTestCase(FlaskTestCase):2829 def test_options_work(self):30 app = flask.Flask(__name__)31 @app.route('/', methods=['GET', 'POST'])32 def index():33 return 'Hello World'34 rv = app.test_client().open('/', method='OPTIONS')35 self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST'])36 self.assert_equal(rv.data, b'')3738 def test_options_on_multiple_rules(self):39 app = flask.Flask(__name__)40 @app.route('/', methods=['GET', 'POST'])41 def index():42 return 'Hello World'43 @app.route('/', methods=['PUT'])44 def index_put():45 return 'Aha!'46 rv = app.test_client().open('/', method='OPTIONS')47 self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'])4849 def test_options_handling_disabled(self):50 app = flask.Flask(__name__)51 def index():52 return 'Hello World!'53 index.provide_automatic_options = False54 app.route('/')(index)55 rv = app.test_client().open('/', method='OPTIONS')56 self.assert_equal(rv.status_code, 405)5758 app = flask.Flask(__name__)59 def index2():60 return 'Hello World!'61 index2.provide_automatic_options = True62 app.route('/', methods=['OPTIONS'])(index2)63 rv = app.test_client().open('/', method='OPTIONS')64 self.assert_equal(sorted(rv.allow), ['OPTIONS'])6566 def test_request_dispatching(self):67 app = flask.Flask(__name__)68 @app.route('/')69 def index():70 return flask.request.method71 @app.route('/more', methods=['GET', 'POST'])72 def more():73 return flask.request.method7475 c = app.test_client()76 self.assert_equal(c.get('/').data, b'GET')77 rv = c.post('/')78 self.assert_equal(rv.status_code, 405)79 self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS'])80 rv = c.head('/')81 self.assert_equal(rv.status_code, 200)82 self.assert_false(rv.data) # head truncates83 self.assert_equal(c.post('/more').data, b'POST')84 self.assert_equal(c.get('/more').data, b'GET')85 rv = c.delete('/more')86 self.assert_equal(rv.status_code, 405)87 self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST'])8889 def test_disallow_string_for_allowed_methods(self):90 app = flask.Flask(__name__)91 with self.assert_raises(TypeError):92 @app.route('/', methods='GET POST')93 def index():94 return "Hey"9596 def test_url_mapping(self):97 app = flask.Flask(__name__)98 def index():99 return flask.request.method100 def more():101 return flask.request.method102103 app.add_url_rule('/', 'index', index)104 app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])105106 c = app.test_client()107 self.assert_equal(c.get('/').data, b'GET')108 rv = c.post('/')109 self.assert_equal(rv.status_code, 405)110 self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS'])111 rv = c.head('/')112 self.assert_equal(rv.status_code, 200)113 self.assert_false(rv.data) # head truncates114 self.assert_equal(c.post('/more').data, b'POST')115 self.assert_equal(c.get('/more').data, b'GET')116 rv = c.delete('/more')117 self.assert_equal(rv.status_code, 405)118 self.assert_equal(sorted(rv.allow), ['GET', 'HEAD', 'OPTIONS', 'POST'])119120 def test_werkzeug_routing(self):121 from werkzeug.routing import Submount, Rule122 app = flask.Flask(__name__)123 app.url_map.add(Submount('/foo', [124 Rule('/bar', endpoint='bar'),125 Rule('/', endpoint='index')126 ]))127 def bar():128 return 'bar'129 def index():130 return 'index'131 app.view_functions['bar'] = bar132 app.view_functions['index'] = index133134 c = app.test_client()135 self.assert_equal(c.get('/foo/').data, b'index')136 self.assert_equal(c.get('/foo/bar').data, b'bar')137138 def test_endpoint_decorator(self):139 from werkzeug.routing import Submount, Rule140 app = flask.Flask(__name__)141 app.url_map.add(Submount('/foo', [142 Rule('/bar', endpoint='bar'),143 Rule('/', endpoint='index')144 ]))145146 @app.endpoint('bar')147 def bar():148 return 'bar'149150 @app.endpoint('index')151 def index():152 return 'index'153154 c = app.test_client()155 self.assert_equal(c.get('/foo/').data, b'index')156 self.assert_equal(c.get('/foo/bar').data, b'bar')157158 def test_session(self):159 app = flask.Flask(__name__)160 app.secret_key = 'testkey'161 @app.route('/set', methods=['POST'])162 def set():163 flask.session['value'] = flask.request.form['value']164 return 'value set'165 @app.route('/get')166 def get():167 return flask.session['value']168169 c = app.test_client()170 self.assert_equal(c.post('/set', data={'value': '42'}).data, b'value set')171 self.assert_equal(c.get('/get').data, b'42')172173 def test_session_using_server_name(self):174 app = flask.Flask(__name__)175 app.config.update(176 SECRET_KEY='foo',177 SERVER_NAME='example.com'178 )179 @app.route('/')180 def index():181 flask.session['testing'] = 42182 return 'Hello World'183 rv = app.test_client().get('/', 'http://example.com/')184 self.assert_in('domain=.example.com', rv.headers['set-cookie'].lower())185 self.assert_in('httponly', rv.headers['set-cookie'].lower())186187 def test_session_using_server_name_and_port(self):188 app = flask.Flask(__name__)189 app.config.update(190 SECRET_KEY='foo',191 SERVER_NAME='example.com:8080'192 )193 @app.route('/')194 def index():195 flask.session['testing'] = 42196 return 'Hello World'197 rv = app.test_client().get('/', 'http://example.com:8080/')198 self.assert_in('domain=.example.com', rv.headers['set-cookie'].lower())199 self.assert_in('httponly', rv.headers['set-cookie'].lower())200201 def test_session_using_server_name_port_and_path(self):202 app = flask.Flask(__name__)203 app.config.update(204 SECRET_KEY='foo',205 SERVER_NAME='example.com:8080',206 APPLICATION_ROOT='/foo'207 )208 @app.route('/')209 def index():210 flask.session['testing'] = 42211 return 'Hello World'212 rv = app.test_client().get('/', 'http://example.com:8080/foo')213 self.assert_in('domain=example.com', rv.headers['set-cookie'].lower())214 self.assert_in('path=/foo', rv.headers['set-cookie'].lower())215 self.assert_in('httponly', rv.headers['set-cookie'].lower())216217 def test_session_using_application_root(self):218 class PrefixPathMiddleware(object):219 def __init__(self, app, prefix):220 self.app = app221 self.prefix = prefix222 def __call__(self, environ, start_response):223 environ['SCRIPT_NAME'] = self.prefix224 return self.app(environ, start_response)225226 app = flask.Flask(__name__)227 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar')228 app.config.update(229 SECRET_KEY='foo',230 APPLICATION_ROOT='/bar'231 )232 @app.route('/')233 def index():234 flask.session['testing'] = 42235 return 'Hello World'236 rv = app.test_client().get('/', 'http://example.com:8080/')237 self.assert_in('path=/bar', rv.headers['set-cookie'].lower())238239 def test_session_using_session_settings(self):240 app = flask.Flask(__name__)241 app.config.update(242 SECRET_KEY='foo',243 SERVER_NAME='www.example.com:8080',244 APPLICATION_ROOT='/test',245 SESSION_COOKIE_DOMAIN='.example.com',246 SESSION_COOKIE_HTTPONLY=False,247 SESSION_COOKIE_SECURE=True,248 SESSION_COOKIE_PATH='/'249 )250 @app.route('/')251 def index():252 flask.session['testing'] = 42253 return 'Hello World'254 rv = app.test_client().get('/', 'http://www.example.com:8080/test/')255 cookie = rv.headers['set-cookie'].lower()256 self.assert_in('domain=.example.com', cookie)257 self.assert_in('path=/', cookie)258 self.assert_in('secure', cookie)259 self.assert_not_in('httponly', cookie)260261 def test_missing_session(self):262 app = flask.Flask(__name__)263 def expect_exception(f, *args, **kwargs):264 try:265 f(*args, **kwargs)266 except RuntimeError as e:267 self.assert_true(e.args and 'session is unavailable' in e.args[0])268 else:269 self.assert_true(False, 'expected exception')270 with app.test_request_context():271 self.assert_true(flask.session.get('missing_key') is None)272 expect_exception(flask.session.__setitem__, 'foo', 42)273 expect_exception(flask.session.pop, 'foo')274275 def test_session_expiration(self):276 permanent = True277 app = flask.Flask(__name__)278 app.secret_key = 'testkey'279 @app.route('/')280 def index():281 flask.session['test'] = 42282 flask.session.permanent = permanent283 return ''284285 @app.route('/test')286 def test():287 return text_type(flask.session.permanent)288289 client = app.test_client()290 rv = client.get('/')291 self.assert_in('set-cookie', rv.headers)292 match = re.search(r'\bexpires=([^;]+)(?i)', rv.headers['set-cookie'])293 expires = parse_date(match.group())294 expected = datetime.utcnow() + app.permanent_session_lifetime295 self.assert_equal(expires.year, expected.year)296 self.assert_equal(expires.month, expected.month)297 self.assert_equal(expires.day, expected.day)298299 rv = client.get('/test')300 self.assert_equal(rv.data, b'True')301302 permanent = False303 rv = app.test_client().get('/')304 self.assert_in('set-cookie', rv.headers)305 match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])306 self.assert_true(match is None)307308 def test_session_stored_last(self):309 app = flask.Flask(__name__)310 app.secret_key = 'development-key'311 app.testing = True312313 @app.after_request314 def modify_session(response):315 flask.session['foo'] = 42316 return response317 @app.route('/')318 def dump_session_contents():319 return repr(flask.session.get('foo'))320321 c = app.test_client()322 self.assert_equal(c.get('/').data, b'None')323 self.assert_equal(c.get('/').data, b'42')324325 def test_session_special_types(self):326 app = flask.Flask(__name__)327 app.secret_key = 'development-key'328 app.testing = True329 now = datetime.utcnow().replace(microsecond=0)330 the_uuid = uuid.uuid4()331332 @app.after_request333 def modify_session(response):334 flask.session['m'] = flask.Markup('Hello!')335 flask.session['u'] = the_uuid336 flask.session['dt'] = now337 flask.session['b'] = b'\xff'338 flask.session['t'] = (1, 2, 3)339 return response340341 @app.route('/')342 def dump_session_contents():343 return pickle.dumps(dict(flask.session))344345 c = app.test_client()346 c.get('/')347 rv = pickle.loads(c.get('/').data)348 self.assert_equal(rv['m'], flask.Markup('Hello!'))349 self.assert_equal(type(rv['m']), flask.Markup)350 self.assert_equal(rv['dt'], now)351 self.assert_equal(rv['u'], the_uuid)352 self.assert_equal(rv['b'], b'\xff')353 self.assert_equal(type(rv['b']), bytes)354 self.assert_equal(rv['t'], (1, 2, 3))355356 def test_session_cookie_setting(self):357 app = flask.Flask(__name__)358 app.testing = True359 app.secret_key = 'dev key'360 is_permanent = True361362 @app.route('/bump')363 def bump():364 rv = flask.session['foo'] = flask.session.get('foo', 0) + 1365 flask.session.permanent = is_permanent366 return str(rv)367368 @app.route('/read')369 def read():370 return str(flask.session.get('foo', 0))371372 def run_test(expect_header):373 with app.test_client() as c:374 self.assert_equal(c.get('/bump').data, b'1')375 self.assert_equal(c.get('/bump').data, b'2')376 self.assert_equal(c.get('/bump').data, b'3')377378 rv = c.get('/read')379 set_cookie = rv.headers.get('set-cookie')380 self.assert_equal(set_cookie is not None, expect_header)381 self.assert_equal(rv.data, b'3')382383 is_permanent = True384 app.config['SESSION_REFRESH_EACH_REQUEST'] = True385 run_test(expect_header=True)386387 is_permanent = True388 app.config['SESSION_REFRESH_EACH_REQUEST'] = False389 run_test(expect_header=False)390391 is_permanent = False392 app.config['SESSION_REFRESH_EACH_REQUEST'] = True393 run_test(expect_header=False)394395 is_permanent = False396 app.config['SESSION_REFRESH_EACH_REQUEST'] = False397 run_test(expect_header=False)398399 def test_session_vary_cookie(self):400401 app = flask.Flask(__name__)402 app.secret_key = 'testkey'403404 @app.route('/set-session')405 def set_session():406407 flask.session['test'] = 'test'408 return ''409410 @app.route('/get-session')411 def get_session():412413 s = flask.session.get('test')414 return ''415416 @app.route('/get-session-with-dictionary')417 def get_session_with_dictionary():418419 s = flask.session['test']420 return ''421422 @app.route('/no-vary-header')423 def no_vary_header():424425 return ''426427 c = app.test_client()428429 rv = c.get('/set-session')430431 self.assert_in('Vary', rv.headers)432 self.assert_equal('Cookie', rv.headers['Vary'])433434 rv = c.get('/get-session')435436 self.assert_in('Vary', rv.headers)437 self.assert_equal('Cookie', rv.headers['Vary'])438439 rv = c.get('/get-session-with-dictionary')440441 self.assert_in('Vary', rv.headers)442 self.assert_equal('Cookie', rv.headers['Vary'])443444 rv = c.get('/no-vary-header')445446 self.assert_not_in('Vary', rv.headers)447448449 def test_flashes(self):450 app = flask.Flask(__name__)451 app.secret_key = 'testkey'452453 with app.test_request_context():454 self.assert_false(flask.session.modified)455 flask.flash('Zap')456 flask.session.modified = False457 flask.flash('Zip')458 self.assert_true(flask.session.modified)459 self.assert_equal(list(flask.get_flashed_messages()), ['Zap', 'Zip'])460461 def test_extended_flashing(self):462 # Be sure app.testing=True below, else tests can fail silently.463 #464 # Specifically, if app.testing is not set to True, the AssertionErrors465 # in the view functions will cause a 500 response to the test client466 # instead of propagating exceptions.467468 app = flask.Flask(__name__)469 app.secret_key = 'testkey'470 app.testing = True471472 @app.route('/')473 def index():474 flask.flash(u'Hello World')475 flask.flash(u'Hello World', 'error')476 flask.flash(flask.Markup(u'<em>Testing</em>'), 'warning')477 return ''478479 @app.route('/test/')480 def test():481 messages = flask.get_flashed_messages()482 self.assert_equal(len(messages), 3)483 self.assert_equal(messages[0], u'Hello World')484 self.assert_equal(messages[1], u'Hello World')485 self.assert_equal(messages[2], flask.Markup(u'<em>Testing</em>'))486 return ''487488 @app.route('/test_with_categories/')489 def test_with_categories():490 messages = flask.get_flashed_messages(with_categories=True)491 self.assert_equal(len(messages), 3)492 self.assert_equal(messages[0], ('message', u'Hello World'))493 self.assert_equal(messages[1], ('error', u'Hello World'))494 self.assert_equal(messages[2], ('warning', flask.Markup(u'<em>Testing</em>')))495 return ''496497 @app.route('/test_filter/')498 def test_filter():499 messages = flask.get_flashed_messages(category_filter=['message'], with_categories=True)500 self.assert_equal(len(messages), 1)501 self.assert_equal(messages[0], ('message', u'Hello World'))502 return ''503504 @app.route('/test_filters/')505 def test_filters():506 messages = flask.get_flashed_messages(category_filter=['message', 'warning'], with_categories=True)507 self.assert_equal(len(messages), 2)508 self.assert_equal(messages[0], ('message', u'Hello World'))509 self.assert_equal(messages[1], ('warning', flask.Markup(u'<em>Testing</em>')))510 return ''511512 @app.route('/test_filters_without_returning_categories/')513 def test_filters2():514 messages = flask.get_flashed_messages(category_filter=['message', 'warning'])515 self.assert_equal(len(messages), 2)516 self.assert_equal(messages[0], u'Hello World')517 self.assert_equal(messages[1], flask.Markup(u'<em>Testing</em>'))518 return ''519520 # Create new test client on each test to clean flashed messages.521522 c = app.test_client()523 c.get('/')524 c.get('/test/')525526 c = app.test_client()527 c.get('/')528 c.get('/test_with_categories/')529530 c = app.test_client()531 c.get('/')532 c.get('/test_filter/')533534 c = app.test_client()535 c.get('/')536 c.get('/test_filters/')537538 c = app.test_client()539 c.get('/')540 c.get('/test_filters_without_returning_categories/')541542 def test_request_processing(self):543 app = flask.Flask(__name__)544 evts = []545 @app.before_request546 def before_request():547 evts.append('before')548 @app.after_request549 def after_request(response):550 response.data += b'|after'551 evts.append('after')552 return response553 @app.route('/')554 def index():555 self.assert_in('before', evts)556 self.assert_not_in('after', evts)557 return 'request'558 self.assert_not_in('after', evts)559 rv = app.test_client().get('/').data560 self.assert_in('after', evts)561 self.assert_equal(rv, b'request|after')562563 def test_after_request_processing(self):564 app = flask.Flask(__name__)565 app.testing = True566 @app.route('/')567 def index():568 @flask.after_this_request569 def foo(response):570 response.headers['X-Foo'] = 'a header'571 return response572 return 'Test'573 c = app.test_client()574 resp = c.get('/')575 self.assertEqual(resp.status_code, 200)576 self.assertEqual(resp.headers['X-Foo'], 'a header')577578 def test_teardown_request_handler(self):579 called = []580 app = flask.Flask(__name__)581 @app.teardown_request582 def teardown_request(exc):583 called.append(True)584 return "Ignored"585 @app.route('/')586 def root():587 return "Response"588 rv = app.test_client().get('/')589 self.assert_equal(rv.status_code, 200)590 self.assert_in(b'Response', rv.data)591 self.assert_equal(len(called), 1)592593 def test_teardown_request_handler_debug_mode(self):594 called = []595 app = flask.Flask(__name__)596 app.testing = True597 @app.teardown_request598 def teardown_request(exc):599 called.append(True)600 return "Ignored"601 @app.route('/')602 def root():603 return "Response"604 rv = app.test_client().get('/')605 self.assert_equal(rv.status_code, 200)606 self.assert_in(b'Response', rv.data)607 self.assert_equal(len(called), 1)608609 def test_teardown_request_handler_error(self):610 called = []611 app = flask.Flask(__name__)612 @app.teardown_request613 def teardown_request1(exc):614 self.assert_equal(type(exc), ZeroDivisionError)615 called.append(True)616 # This raises a new error and blows away sys.exc_info(), so we can617 # test that all teardown_requests get passed the same original618 # exception.619 try:620 raise TypeError()621 except:622 pass623 @app.teardown_request624 def teardown_request2(exc):625 self.assert_equal(type(exc), ZeroDivisionError)626 called.append(True)627 # This raises a new error and blows away sys.exc_info(), so we can628 # test that all teardown_requests get passed the same original629 # exception.630 try:631 raise TypeError()632 except:633 pass634 @app.route('/')635 def fails():636 1 // 0637 rv = app.test_client().get('/')638 self.assert_equal(rv.status_code, 500)639 self.assert_in(b'Internal Server Error', rv.data)640 self.assert_equal(len(called), 2)641642 def test_before_after_request_order(self):643 called = []644 app = flask.Flask(__name__)645 @app.before_request646 def before1():647 called.append(1)648 @app.before_request649 def before2():650 called.append(2)651 @app.after_request652 def after1(response):653 called.append(4)654 return response655 @app.after_request656 def after2(response):657 called.append(3)658 return response659 @app.teardown_request660 def finish1(exc):661 called.append(6)662 @app.teardown_request663 def finish2(exc):664 called.append(5)665 @app.route('/')666 def index():667 return '42'668 rv = app.test_client().get('/')669 self.assert_equal(rv.data, b'42')670 self.assert_equal(called, [1, 2, 3, 4, 5, 6])671672 def test_error_handling(self):673 app = flask.Flask(__name__)674 @app.errorhandler(404)675 def not_found(e):676 return 'not found', 404677 @app.errorhandler(500)678 def internal_server_error(e):679 return 'internal server error', 500680 @app.route('/')681 def index():682 flask.abort(404)683 @app.route('/error')684 def error():685 1 // 0686 c = app.test_client()687 rv = c.get('/')688 self.assert_equal(rv.status_code, 404)689 self.assert_equal(rv.data, b'not found')690 rv = c.get('/error')691 self.assert_equal(rv.status_code, 500)692 self.assert_equal(b'internal server error', rv.data)693694 def test_before_request_and_routing_errors(self):695 app = flask.Flask(__name__)696 @app.before_request697 def attach_something():698 flask.g.something = 'value'699 @app.errorhandler(404)700 def return_something(error):701 return flask.g.something, 404702 rv = app.test_client().get('/')703 self.assert_equal(rv.status_code, 404)704 self.assert_equal(rv.data, b'value')705706 def test_user_error_handling(self):707 class MyException(Exception):708 pass709710 app = flask.Flask(__name__)711 @app.errorhandler(MyException)712 def handle_my_exception(e):713 self.assert_true(isinstance(e, MyException))714 return '42'715 @app.route('/')716 def index():717 raise MyException()718719 c = app.test_client()720 self.assert_equal(c.get('/').data, b'42')721722 def test_trapping_of_bad_request_key_errors(self):723 app = flask.Flask(__name__)724 app.testing = True725 @app.route('/fail')726 def fail():727 flask.request.form['missing_key']728 c = app.test_client()729 self.assert_equal(c.get('/fail').status_code, 400)730731 app.config['TRAP_BAD_REQUEST_ERRORS'] = True732 c = app.test_client()733 try:734 c.get('/fail')735 except KeyError as e:736 self.assert_true(isinstance(e, BadRequest))737 else:738 self.fail('Expected exception')739740 def test_trapping_of_all_http_exceptions(self):741 app = flask.Flask(__name__)742 app.testing = True743 app.config['TRAP_HTTP_EXCEPTIONS'] = True744 @app.route('/fail')745 def fail():746 flask.abort(404)747748 c = app.test_client()749 try:750 c.get('/fail')751 except NotFound as e:752 pass753 else:754 self.fail('Expected exception')755756 def test_enctype_debug_helper(self):757 from flask.debughelpers import DebugFilesKeyError758 app = flask.Flask(__name__)759 app.debug = True760 @app.route('/fail', methods=['POST'])761 def index():762 return flask.request.files['foo'].filename763764 # with statement is important because we leave an exception on the765 # stack otherwise and we want to ensure that this is not the case766 # to not negatively affect other tests.767 with app.test_client() as c:768 try:769 c.post('/fail', data={'foo': 'index.txt'})770 except DebugFilesKeyError as e:771 self.assert_in('no file contents were transmitted', str(e))772 self.assert_in('This was submitted: "index.txt"', str(e))773 else:774 self.fail('Expected exception')775776 def test_response_creation(self):777 app = flask.Flask(__name__)778 @app.route('/unicode')779 def from_unicode():780 return u'Hällo Wörld'781 @app.route('/string')782 def from_string():783 return u'Hällo Wörld'.encode('utf-8')784 @app.route('/args')785 def from_tuple():786 return 'Meh', 400, {787 'X-Foo': 'Testing',788 'Content-Type': 'text/plain; charset=utf-8'789 } 790 @app.route('/two_args')791 def from_two_args_tuple():792 return 'Hello', {793 'X-Foo': 'Test',794 'Content-Type': 'text/plain; charset=utf-8'795 }796 @app.route('/args_status')797 def from_status_tuple():798 return 'Hi, status!', 400799 @app.route('/args_header')800 def from_response_instance_status_tuple():801 return flask.Response('Hello world', 404), {802 "X-Foo": "Bar",803 "X-Bar": "Foo"804 }805806 c = app.test_client()807 self.assert_equal(c.get('/unicode').data, u'Hällo Wörld'.encode('utf-8'))808 self.assert_equal(c.get('/string').data, u'Hällo Wörld'.encode('utf-8'))809 rv = c.get('/args')810 self.assert_equal(rv.data, b'Meh')811 self.assert_equal(rv.headers['X-Foo'], 'Testing')812 self.assert_equal(rv.status_code, 400)813 self.assert_equal(rv.mimetype, 'text/plain')814 rv2 = c.get('/two_args')815 self.assert_equal(rv2.data, b'Hello')816 self.assert_equal(rv2.headers['X-Foo'], 'Test')817 self.assert_equal(rv2.status_code, 200)818 self.assert_equal(rv2.mimetype, 'text/plain')819 rv3 = c.get('/args_status')820 self.assert_equal(rv3.data, b'Hi, status!')821 self.assert_equal(rv3.status_code, 400)822 self.assert_equal(rv3.mimetype, 'text/html')823 rv4 = c.get('/args_header')824 self.assert_equal(rv4.data, b'Hello world')825 self.assert_equal(rv4.headers['X-Foo'], 'Bar')826 self.assert_equal(rv4.headers['X-Bar'], 'Foo')827 self.assert_equal(rv4.status_code, 404)828829 def test_make_response(self):830 app = flask.Flask(__name__)831 with app.test_request_context():832 rv = flask.make_response()833 self.assert_equal(rv.status_code, 200)834 self.assert_equal(rv.data, b'')835 self.assert_equal(rv.mimetype, 'text/html')836837 rv = flask.make_response('Awesome')838 self.assert_equal(rv.status_code, 200)839 self.assert_equal(rv.data, b'Awesome')840 self.assert_equal(rv.mimetype, 'text/html')841842 rv = flask.make_response('W00t', 404)843 self.assert_equal(rv.status_code, 404)844 self.assert_equal(rv.data, b'W00t')845 self.assert_equal(rv.mimetype, 'text/html')846847 def test_make_response_with_response_instance(self):848 app = flask.Flask(__name__)849 with app.test_request_context():850 rv = flask.make_response(851 flask.jsonify({'msg': 'W00t'}), 400)852 self.assertEqual(rv.status_code, 400)853 self.assertEqual(rv.data, b'{\n "msg": "W00t"\n}')854 self.assertEqual(rv.mimetype, 'application/json')855856 rv = flask.make_response(857 flask.Response(''), 400)858 self.assertEqual(rv.status_code, 400)859 self.assertEqual(rv.data, b'')860 self.assertEqual(rv.mimetype, 'text/html')861862 rv = flask.make_response(863 flask.Response('', headers={'Content-Type': 'text/html'}),864 400, [('X-Foo', 'bar')])865 self.assertEqual(rv.status_code, 400)866 self.assertEqual(rv.headers['Content-Type'], 'text/html')867 self.assertEqual(rv.headers['X-Foo'], 'bar')868869 def test_url_generation(self):870 app = flask.Flask(__name__)871 @app.route('/hello/<name>', methods=['POST'])872 def hello():873 pass874 with app.test_request_context():875 self.assert_equal(flask.url_for('hello', name='test x'), '/hello/test%20x')876 self.assert_equal(flask.url_for('hello', name='test x', _external=True),877 'http://localhost/hello/test%20x')878879 def test_build_error_handler(self):880 app = flask.Flask(__name__)881882 # Test base case, a URL which results in a BuildError.883 with app.test_request_context():884 self.assertRaises(BuildError, flask.url_for, 'spam')885886 # Verify the error is re-raised if not the current exception.887 try:888 with app.test_request_context():889 flask.url_for('spam')890 except BuildError as err:891 error = err892 try:893 raise RuntimeError('Test case where BuildError is not current.')894 except RuntimeError:895 self.assertRaises(BuildError, app.handle_url_build_error, error, 'spam', {})896897 # Test a custom handler.898 def handler(error, endpoint, values):899 # Just a test.900 return '/test_handler/'901 app.url_build_error_handlers.append(handler)902 with app.test_request_context():903 self.assert_equal(flask.url_for('spam'), '/test_handler/')904905 def test_custom_converters(self):906 from werkzeug.routing import BaseConverter907 class ListConverter(BaseConverter):908 def to_python(self, value):909 return value.split(',')910 def to_url(self, value):911 base_to_url = super(ListConverter, self).to_url912 return ','.join(base_to_url(x) for x in value)913 app = flask.Flask(__name__)914 app.url_map.converters['list'] = ListConverter915 @app.route('/<list:args>')916 def index(args):917 return '|'.join(args)918 c = app.test_client()919 self.assert_equal(c.get('/1,2,3').data, b'1|2|3')920921 def test_static_files(self):922 app = flask.Flask(__name__)923 app.testing = True924 rv = app.test_client().get('/static/index.html')925 self.assert_equal(rv.status_code, 200)926 self.assert_equal(rv.data.strip(), b'<h1>Hello World!</h1>')927 with app.test_request_context():928 self.assert_equal(flask.url_for('static', filename='index.html'),929 '/static/index.html')930 rv.close()931932 def test_none_response(self):933 app = flask.Flask(__name__)934 @app.route('/')935 def test():936 return None937 try:938 app.test_client().get('/')939 except ValueError as e:940 self.assert_equal(str(e), 'View function did not return a response')941 pass942 else:943 self.assert_true("Expected ValueError")944945 def test_request_locals(self):946 self.assert_equal(repr(flask.g), '<LocalProxy unbound>')947 self.assertFalse(flask.g)948949 def test_test_app_proper_environ(self):950 app = flask.Flask(__name__)951 app.config.update(952 SERVER_NAME='localhost.localdomain:5000'953 )954 @app.route('/')955 def index():956 return 'Foo'957958 @app.route('/', subdomain='foo')959 def subdomain():960 return 'Foo SubDomain'961962 rv = app.test_client().get('/')963 self.assert_equal(rv.data, b'Foo')964965 rv = app.test_client().get('/', 'http://localhost.localdomain:5000')966 self.assert_equal(rv.data, b'Foo')967968 rv = app.test_client().get('/', 'https://localhost.localdomain:5000')969 self.assert_equal(rv.data, b'Foo')970971 app.config.update(SERVER_NAME='localhost.localdomain')972 rv = app.test_client().get('/', 'https://localhost.localdomain')973 self.assert_equal(rv.data, b'Foo')974975 try:976 app.config.update(SERVER_NAME='localhost.localdomain:443')977 rv = app.test_client().get('/', 'https://localhost.localdomain')978 # Werkzeug 0.8979 self.assert_equal(rv.status_code, 404)980 except ValueError as e:981 # Werkzeug 0.7982 self.assert_equal(str(e), "the server name provided " +983 "('localhost.localdomain:443') does not match the " + \984 "server name from the WSGI environment ('localhost.localdomain')")985986 try:987 app.config.update(SERVER_NAME='localhost.localdomain')988 rv = app.test_client().get('/', 'http://foo.localhost')989 # Werkzeug 0.8990 self.assert_equal(rv.status_code, 404)991 except ValueError as e:992 # Werkzeug 0.7993 self.assert_equal(str(e), "the server name provided " + \994 "('localhost.localdomain') does not match the " + \995 "server name from the WSGI environment ('foo.localhost')")996997 rv = app.test_client().get('/', 'http://foo.localhost.localdomain')998 self.assert_equal(rv.data, b'Foo SubDomain')9991000 def test_exception_propagation(self):1001 def apprunner(configkey):1002 app = flask.Flask(__name__)1003 @app.route('/')1004 def index():1005 1 // 01006 c = app.test_client()1007 if config_key is not None:1008 app.config[config_key] = True1009 try:1010 resp = c.get('/')1011 except Exception:1012 pass1013 else:1014 self.fail('expected exception')1015 else:1016 self.assert_equal(c.get('/').status_code, 500)10171018 # we have to run this test in an isolated thread because if the1019 # debug flag is set to true and an exception happens the context is1020 # not torn down. This causes other tests that run after this fail1021 # when they expect no exception on the stack.1022 for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None:1023 t = Thread(target=apprunner, args=(config_key,))1024 t.start()1025 t.join()10261027 def test_max_content_length(self):1028 app = flask.Flask(__name__)1029 app.config['MAX_CONTENT_LENGTH'] = 641030 @app.before_request1031 def always_first():1032 flask.request.form['myfile']1033 self.assert_true(False)1034 @app.route('/accept', methods=['POST'])1035 def accept_file():1036 flask.request.form['myfile']1037 self.assert_true(False)1038 @app.errorhandler(413)1039 def catcher(error):1040 return '42'10411042 c = app.test_client()1043 rv = c.post('/accept', data={'myfile': 'foo' * 100})1044 self.assert_equal(rv.data, b'42')10451046 def test_url_processors(self):1047 app = flask.Flask(__name__)10481049 @app.url_defaults1050 def add_language_code(endpoint, values):1051 if flask.g.lang_code is not None and \1052 app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1053 values.setdefault('lang_code', flask.g.lang_code)10541055 @app.url_value_preprocessor1056 def pull_lang_code(endpoint, values):1057 flask.g.lang_code = values.pop('lang_code', None)10581059 @app.route('/<lang_code>/')1060 def index():1061 return flask.url_for('about')10621063 @app.route('/<lang_code>/about')1064 def about():1065 return flask.url_for('something_else')10661067 @app.route('/foo')1068 def something_else():1069 return flask.url_for('about', lang_code='en')10701071 c = app.test_client()10721073 self.assert_equal(c.get('/de/').data, b'/de/about')1074 self.assert_equal(c.get('/de/about').data, b'/foo')1075 self.assert_equal(c.get('/foo').data, b'/en/about')10761077 def test_inject_blueprint_url_defaults(self):1078 app = flask.Flask(__name__)1079 bp = flask.Blueprint('foo.bar.baz', __name__,1080 template_folder='template')10811082 @bp.url_defaults1083 def bp_defaults(endpoint, values):1084 values['page'] = 'login'1085 @bp.route('/<page>')1086 def view(page): pass10871088 app.register_blueprint(bp)10891090 values = dict()1091 app.inject_url_defaults('foo.bar.baz.view', values)1092 expected = dict(page='login')1093 self.assert_equal(values, expected)10941095 with app.test_request_context('/somepage'):1096 url = flask.url_for('foo.bar.baz.view')1097 expected = '/login'1098 self.assert_equal(url, expected)10991100 def test_nonascii_pathinfo(self):1101 app = flask.Flask(__name__)1102 app.testing = True11031104 @app.route(u'/киртест')1105 def index():1106 return 'Hello World!'11071108 c = app.test_client()1109 rv = c.get(u'/киртест')1110 self.assert_equal(rv.data, b'Hello World!')11111112 def test_debug_mode_complains_after_first_request(self):1113 app = flask.Flask(__name__)1114 app.debug = True1115 @app.route('/')1116 def index():1117 return 'Awesome'1118 self.assert_false(app.got_first_request)1119 self.assert_equal(app.test_client().get('/').data, b'Awesome')1120 try:1121 @app.route('/foo')1122 def broken():1123 return 'Meh'1124 except AssertionError as e:1125 self.assert_in('A setup function was called', str(e))1126 else:1127 self.fail('Expected exception')11281129 app.debug = False1130 @app.route('/foo')1131 def working():1132 return 'Meh'1133 self.assert_equal(app.test_client().get('/foo').data, b'Meh')1134 self.assert_true(app.got_first_request)11351136 def test_before_first_request_functions(self):1137 got = []1138 app = flask.Flask(__name__)1139 @app.before_first_request1140 def foo():1141 got.append(42)1142 c = app.test_client()1143 c.get('/')1144 self.assert_equal(got, [42])1145 c.get('/')1146 self.assert_equal(got, [42])1147 self.assert_true(app.got_first_request)11481149 def test_before_first_request_functions_concurrent(self):1150 got = []1151 app = flask.Flask(__name__)11521153 @app.before_first_request1154 def foo():1155 time.sleep(0.2)1156 got.append(42)11571158 c = app.test_client()1159 def get_and_assert():1160 c.get("/")1161 self.assert_equal(got, [42])11621163 t = Thread(target=get_and_assert)1164 t.start()1165 get_and_assert()1166 t.join()1167 self.assert_true(app.got_first_request)11681169 def test_routing_redirect_debugging(self):1170 app = flask.Flask(__name__)1171 app.debug = True1172 @app.route('/foo/', methods=['GET', 'POST'])1173 def foo():1174 return 'success'1175 with app.test_client() as c:1176 try:1177 c.post('/foo', data={})1178 except AssertionError as e:1179 self.assert_in('http://localhost/foo/', str(e))1180 self.assert_in('Make sure to directly send your POST-request '1181 'to this URL', str(e))1182 else:1183 self.fail('Expected exception')11841185 rv = c.get('/foo', data={}, follow_redirects=True)1186 self.assert_equal(rv.data, b'success')11871188 app.debug = False1189 with app.test_client() as c:1190 rv = c.post('/foo', data={}, follow_redirects=True)1191 self.assert_equal(rv.data, b'success')11921193 def test_route_decorator_custom_endpoint(self):1194 app = flask.Flask(__name__)1195 app.debug = True11961197 @app.route('/foo/')1198 def foo():1199 return flask.request.endpoint12001201 @app.route('/bar/', endpoint='bar')1202 def for_bar():1203 return flask.request.endpoint12041205 @app.route('/bar/123', endpoint='123')1206 def for_bar_foo():1207 return flask.request.endpoint12081209 with app.test_request_context():1210 assert flask.url_for('foo') == '/foo/'1211 assert flask.url_for('bar') == '/bar/'1212 assert flask.url_for('123') == '/bar/123'12131214 c = app.test_client()1215 self.assertEqual(c.get('/foo/').data, b'foo')1216 self.assertEqual(c.get('/bar/').data, b'bar')1217 self.assertEqual(c.get('/bar/123').data, b'123')12181219 def test_preserve_only_once(self):1220 app = flask.Flask(__name__)1221 app.debug = True12221223 @app.route('/fail')1224 def fail_func():1225 1 // 012261227 c = app.test_client()1228 for x in range(3):1229 with self.assert_raises(ZeroDivisionError):1230 c.get('/fail')12311232 self.assert_true(flask._request_ctx_stack.top is not None)1233 self.assert_true(flask._app_ctx_stack.top is not None)1234 # implicit appctx disappears too1235 flask._request_ctx_stack.top.pop()1236 self.assert_true(flask._request_ctx_stack.top is None)1237 self.assert_true(flask._app_ctx_stack.top is None)12381239 def test_preserve_remembers_exception(self):1240 app = flask.Flask(__name__)1241 app.debug = True1242 errors = []12431244 @app.route('/fail')1245 def fail_func():1246 1 // 012471248 @app.route('/success')1249 def success_func():1250 return 'Okay'12511252 @app.teardown_request1253 def teardown_handler(exc):1254 errors.append(exc)12551256 c = app.test_client()12571258 # After this failure we did not yet call the teardown handler1259 with self.assert_raises(ZeroDivisionError):1260 c.get('/fail')1261 self.assert_equal(errors, [])12621263 # But this request triggers it, and it's an error1264 c.get('/success')1265 self.assert_equal(len(errors), 2)1266 self.assert_true(isinstance(errors[0], ZeroDivisionError))12671268 # At this point another request does nothing.1269 c.get('/success')1270 self.assert_equal(len(errors), 3)1271 self.assert_equal(errors[1], None)12721273 def test_get_method_on_g(self):1274 app = flask.Flask(__name__)1275 app.testing = True12761277 with app.app_context():1278 self.assert_equal(flask.g.get('x'), None)1279 self.assert_equal(flask.g.get('x', 11), 11)1280 flask.g.x = 421281 self.assert_equal(flask.g.get('x'), 42)1282 self.assert_equal(flask.g.x, 42)12831284 def test_g_iteration_protocol(self):1285 app = flask.Flask(__name__)1286 app.testing = True12871288 with app.app_context():1289 flask.g.foo = 231290 flask.g.bar = 421291 self.assert_equal('foo' in flask.g, True)1292 self.assert_equal('foos' in flask.g, False)1293 self.assert_equal(sorted(flask.g), ['bar', 'foo'])129412951296class SubdomainTestCase(FlaskTestCase):12971298 def test_basic_support(self):1299 app = flask.Flask(__name__)1300 app.config['SERVER_NAME'] = 'localhost'1301 @app.route('/')1302 def normal_index():1303 return 'normal index'1304 @app.route('/', subdomain='test')1305 def test_index():1306 return 'test index'13071308 c = app.test_client()1309 rv = c.get('/', 'http://localhost/')1310 self.assert_equal(rv.data, b'normal index')13111312 rv = c.get('/', 'http://test.localhost/')1313 self.assert_equal(rv.data, b'test index')13141315 @emits_module_deprecation_warning1316 def test_module_static_path_subdomain(self):1317 app = flask.Flask(__name__)1318 app.config['SERVER_NAME'] = 'example.com'1319 from subdomaintestmodule import mod1320 app.register_module(mod)1321 c = app.test_client()1322 rv = c.get('/static/hello.txt', 'http://foo.example.com/')1323 rv.direct_passthrough = False1324 self.assert_equal(rv.data.strip(), b'Hello Subdomain')1325 rv.close()13261327 def test_subdomain_matching(self):1328 app = flask.Flask(__name__)1329 app.config['SERVER_NAME'] = 'localhost'1330 @app.route('/', subdomain='<user>')1331 def index(user):1332 return 'index for %s' % user13331334 c = app.test_client()1335 rv = c.get('/', 'http://mitsuhiko.localhost/')1336 self.assert_equal(rv.data, b'index for mitsuhiko')13371338 def test_subdomain_matching_with_ports(self):1339 app = flask.Flask(__name__)1340 app.config['SERVER_NAME'] = 'localhost:3000'1341 @app.route('/', subdomain='<user>')1342 def index(user):1343 return 'index for %s' % user13441345 c = app.test_client()1346 rv = c.get('/', 'http://mitsuhiko.localhost:3000/')1347 self.assert_equal(rv.data, b'index for mitsuhiko')13481349 @emits_module_deprecation_warning1350 def test_module_subdomain_support(self):1351 app = flask.Flask(__name__)1352 mod = flask.Module(__name__, 'test', subdomain='testing')1353 app.config['SERVER_NAME'] = 'localhost'13541355 @mod.route('/test')1356 def test():1357 return 'Test'13581359 @mod.route('/outside', subdomain='xtesting')1360 def bar():1361 return 'Outside'13621363 app.register_module(mod)13641365 c = app.test_client()1366 rv = c.get('/test', 'http://testing.localhost/')1367 self.assert_equal(rv.data, b'Test')1368 rv = c.get('/outside', 'http://xtesting.localhost/')1369 self.assert_equal(rv.data, b'Outside')13701371 def test_multi_route_rules(self):1372 app = flask.Flask(__name__)13731374 @app.route('/')1375 @app.route('/<test>/')1376 def index(test='a'):1377 return test13781379 rv = app.test_client().open('/')1380 self.assert_equal(rv.data, b'a')1381 rv = app.test_client().open('/b/')1382 self.assert_equal(rv.data, b'b')13831384 def test_multi_route_class_views(self):1385 class View(object):1386 def __init__(self, app):1387 app.add_url_rule('/', 'index', self.index)1388 app.add_url_rule('/<test>/', 'index', self.index)13891390 def index(self, test='a'):1391 return test13921393 app = flask.Flask(__name__)1394 _ = View(app)1395 rv = app.test_client().open('/')1396 self.assert_equal(rv.data, b'a')1397 rv = app.test_client().open('/b/')1398 self.assert_equal(rv.data, b'b')139914001401def suite():1402 suite = unittest.TestSuite()1403 suite.addTest(unittest.makeSuite(BasicFunctionalityTestCase))1404 suite.addTest(unittest.makeSuite(SubdomainTestCase))1405 return suite
deleted:flask/testsuite/blueprints.py-823 removed
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.blueprints4 ~~~~~~~~~~~~~~~~~~~~~~~~~~56 Blueprints (and currently modules)78 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import flask13import unittest14import warnings15from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning16from flask._compat import text_type17from werkzeug.exceptions import NotFound18from werkzeug.http import parse_cache_control_header19from jinja2 import TemplateNotFound202122# import moduleapp here because it uses deprecated features and we don't23# want to see the warnings24warnings.simplefilter('ignore', DeprecationWarning)25from moduleapp import app as moduleapp26warnings.simplefilter('default', DeprecationWarning)272829class ModuleTestCase(FlaskTestCase):3031 @emits_module_deprecation_warning32 def test_basic_module(self):33 app = flask.Flask(__name__)34 admin = flask.Module(__name__, 'admin', url_prefix='/admin')35 @admin.route('/')36 def admin_index():37 return 'admin index'38 @admin.route('/login')39 def admin_login():40 return 'admin login'41 @admin.route('/logout')42 def admin_logout():43 return 'admin logout'44 @app.route('/')45 def index():46 return 'the index'47 app.register_module(admin)48 c = app.test_client()49 self.assert_equal(c.get('/').data, b'the index')50 self.assert_equal(c.get('/admin/').data, b'admin index')51 self.assert_equal(c.get('/admin/login').data, b'admin login')52 self.assert_equal(c.get('/admin/logout').data, b'admin logout')5354 @emits_module_deprecation_warning55 def test_default_endpoint_name(self):56 app = flask.Flask(__name__)57 mod = flask.Module(__name__, 'frontend')58 def index():59 return 'Awesome'60 mod.add_url_rule('/', view_func=index)61 app.register_module(mod)62 rv = app.test_client().get('/')63 self.assert_equal(rv.data, b'Awesome')64 with app.test_request_context():65 self.assert_equal(flask.url_for('frontend.index'), '/')6667 @emits_module_deprecation_warning68 def test_request_processing(self):69 catched = []70 app = flask.Flask(__name__)71 admin = flask.Module(__name__, 'admin', url_prefix='/admin')72 @admin.before_request73 def before_admin_request():74 catched.append('before-admin')75 @admin.after_request76 def after_admin_request(response):77 catched.append('after-admin')78 return response79 @admin.route('/')80 def admin_index():81 return 'the admin'82 @app.before_request83 def before_request():84 catched.append('before-app')85 @app.after_request86 def after_request(response):87 catched.append('after-app')88 return response89 @app.route('/')90 def index():91 return 'the index'92 app.register_module(admin)93 c = app.test_client()9495 self.assert_equal(c.get('/').data, b'the index')96 self.assert_equal(catched, ['before-app', 'after-app'])97 del catched[:]9899 self.assert_equal(c.get('/admin/').data, b'the admin')100 self.assert_equal(catched, ['before-app', 'before-admin',101 'after-admin', 'after-app'])102103 @emits_module_deprecation_warning104 def test_context_processors(self):105 app = flask.Flask(__name__)106 admin = flask.Module(__name__, 'admin', url_prefix='/admin')107 @app.context_processor108 def inject_all_regular():109 return {'a': 1}110 @admin.context_processor111 def inject_admin():112 return {'b': 2}113 @admin.app_context_processor114 def inject_all_module():115 return {'c': 3}116 @app.route('/')117 def index():118 return flask.render_template_string('{{ a }}{{ b }}{{ c }}')119 @admin.route('/')120 def admin_index():121 return flask.render_template_string('{{ a }}{{ b }}{{ c }}')122 app.register_module(admin)123 c = app.test_client()124 self.assert_equal(c.get('/').data, b'13')125 self.assert_equal(c.get('/admin/').data, b'123')126127 @emits_module_deprecation_warning128 def test_late_binding(self):129 app = flask.Flask(__name__)130 admin = flask.Module(__name__, 'admin')131 @admin.route('/')132 def index():133 return '42'134 app.register_module(admin, url_prefix='/admin')135 self.assert_equal(app.test_client().get('/admin/').data, b'42')136137 @emits_module_deprecation_warning138 def test_error_handling(self):139 app = flask.Flask(__name__)140 admin = flask.Module(__name__, 'admin')141 @admin.app_errorhandler(404)142 def not_found(e):143 return 'not found', 404144 @admin.app_errorhandler(500)145 def internal_server_error(e):146 return 'internal server error', 500147 @admin.route('/')148 def index():149 flask.abort(404)150 @admin.route('/error')151 def error():152 1 // 0153 app.register_module(admin)154 c = app.test_client()155 rv = c.get('/')156 self.assert_equal(rv.status_code, 404)157 self.assert_equal(rv.data, b'not found')158 rv = c.get('/error')159 self.assert_equal(rv.status_code, 500)160 self.assert_equal(b'internal server error', rv.data)161162 def test_templates_and_static(self):163 app = moduleapp164 app.testing = True165 c = app.test_client()166167 rv = c.get('/')168 self.assert_equal(rv.data, b'Hello from the Frontend')169 rv = c.get('/admin/')170 self.assert_equal(rv.data, b'Hello from the Admin')171 rv = c.get('/admin/index2')172 self.assert_equal(rv.data, b'Hello from the Admin')173 rv = c.get('/admin/static/test.txt')174 self.assert_equal(rv.data.strip(), b'Admin File')175 rv.close()176 rv = c.get('/admin/static/css/test.css')177 self.assert_equal(rv.data.strip(), b'/* nested file */')178 rv.close()179180 with app.test_request_context():181 self.assert_equal(flask.url_for('admin.static', filename='test.txt'),182 '/admin/static/test.txt')183184 with app.test_request_context():185 try:186 flask.render_template('missing.html')187 except TemplateNotFound as e:188 self.assert_equal(e.name, 'missing.html')189 else:190 self.assert_true(0, 'expected exception')191192 with flask.Flask(__name__).test_request_context():193 self.assert_equal(flask.render_template('nested/nested.txt'), 'I\'m nested')194195 def test_safe_access(self):196 app = moduleapp197198 with app.test_request_context():199 f = app.view_functions['admin.static']200201 try:202 f('/etc/passwd')203 except NotFound:204 pass205 else:206 self.assert_true(0, 'expected exception')207 try:208 f('../__init__.py')209 except NotFound:210 pass211 else:212 self.assert_true(0, 'expected exception')213214 # testcase for a security issue that may exist on windows systems215 import os216 import ntpath217 old_path = os.path218 os.path = ntpath219 try:220 try:221 f('..\\__init__.py')222 except NotFound:223 pass224 else:225 self.assert_true(0, 'expected exception')226 finally:227 os.path = old_path228229 @emits_module_deprecation_warning230 def test_endpoint_decorator(self):231 from werkzeug.routing import Submount, Rule232 from flask import Module233234 app = flask.Flask(__name__)235 app.testing = True236 app.url_map.add(Submount('/foo', [237 Rule('/bar', endpoint='bar'),238 Rule('/', endpoint='index')239 ]))240 module = Module(__name__, __name__)241242 @module.endpoint('bar')243 def bar():244 return 'bar'245246 @module.endpoint('index')247 def index():248 return 'index'249250 app.register_module(module)251252 c = app.test_client()253 self.assert_equal(c.get('/foo/').data, b'index')254 self.assert_equal(c.get('/foo/bar').data, b'bar')255256257class BlueprintTestCase(FlaskTestCase):258259 def test_blueprint_specific_error_handling(self):260 frontend = flask.Blueprint('frontend', __name__)261 backend = flask.Blueprint('backend', __name__)262 sideend = flask.Blueprint('sideend', __name__)263264 @frontend.errorhandler(403)265 def frontend_forbidden(e):266 return 'frontend says no', 403267268 @frontend.route('/frontend-no')269 def frontend_no():270 flask.abort(403)271272 @backend.errorhandler(403)273 def backend_forbidden(e):274 return 'backend says no', 403275276 @backend.route('/backend-no')277 def backend_no():278 flask.abort(403)279280 @sideend.route('/what-is-a-sideend')281 def sideend_no():282 flask.abort(403)283284 app = flask.Flask(__name__)285 app.register_blueprint(frontend)286 app.register_blueprint(backend)287 app.register_blueprint(sideend)288289 @app.errorhandler(403)290 def app_forbidden(e):291 return 'application itself says no', 403292293 c = app.test_client()294295 self.assert_equal(c.get('/frontend-no').data, b'frontend says no')296 self.assert_equal(c.get('/backend-no').data, b'backend says no')297 self.assert_equal(c.get('/what-is-a-sideend').data, b'application itself says no')298299 def test_blueprint_specific_user_error_handling(self):300 class MyDecoratorException(Exception):301 pass302 class MyFunctionException(Exception):303 pass304305 blue = flask.Blueprint('blue', __name__)306307 @blue.errorhandler(MyDecoratorException)308 def my_decorator_exception_handler(e):309 self.assert_true(isinstance(e, MyDecoratorException))310 return 'boom'311312 def my_function_exception_handler(e):313 self.assert_true(isinstance(e, MyFunctionException))314 return 'bam'315 blue.register_error_handler(MyFunctionException, my_function_exception_handler)316317 @blue.route('/decorator')318 def blue_deco_test():319 raise MyDecoratorException()320 @blue.route('/function')321 def blue_func_test():322 raise MyFunctionException()323324 app = flask.Flask(__name__)325 app.register_blueprint(blue)326327 c = app.test_client()328329 self.assert_equal(c.get('/decorator').data, b'boom')330 self.assert_equal(c.get('/function').data, b'bam')331332 def test_blueprint_url_definitions(self):333 bp = flask.Blueprint('test', __name__)334335 @bp.route('/foo', defaults={'baz': 42})336 def foo(bar, baz):337 return '%s/%d' % (bar, baz)338339 @bp.route('/bar')340 def bar(bar):341 return text_type(bar)342343 app = flask.Flask(__name__)344 app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23})345 app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19})346347 c = app.test_client()348 self.assert_equal(c.get('/1/foo').data, b'23/42')349 self.assert_equal(c.get('/2/foo').data, b'19/42')350 self.assert_equal(c.get('/1/bar').data, b'23')351 self.assert_equal(c.get('/2/bar').data, b'19')352353 def test_blueprint_url_processors(self):354 bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')355356 @bp.url_defaults357 def add_language_code(endpoint, values):358 values.setdefault('lang_code', flask.g.lang_code)359360 @bp.url_value_preprocessor361 def pull_lang_code(endpoint, values):362 flask.g.lang_code = values.pop('lang_code')363364 @bp.route('/')365 def index():366 return flask.url_for('.about')367368 @bp.route('/about')369 def about():370 return flask.url_for('.index')371372 app = flask.Flask(__name__)373 app.register_blueprint(bp)374375 c = app.test_client()376377 self.assert_equal(c.get('/de/').data, b'/de/about')378 self.assert_equal(c.get('/de/about').data, b'/de/')379380 def test_templates_and_static(self):381 from blueprintapp import app382 c = app.test_client()383384 rv = c.get('/')385 self.assert_equal(rv.data, b'Hello from the Frontend')386 rv = c.get('/admin/')387 self.assert_equal(rv.data, b'Hello from the Admin')388 rv = c.get('/admin/index2')389 self.assert_equal(rv.data, b'Hello from the Admin')390 rv = c.get('/admin/static/test.txt')391 self.assert_equal(rv.data.strip(), b'Admin File')392 rv.close()393 rv = c.get('/admin/static/css/test.css')394 self.assert_equal(rv.data.strip(), b'/* nested file */')395 rv.close()396397 # try/finally, in case other tests use this app for Blueprint tests.398 max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT']399 try:400 expected_max_age = 3600401 if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == expected_max_age:402 expected_max_age = 7200403 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age404 rv = c.get('/admin/static/css/test.css')405 cc = parse_cache_control_header(rv.headers['Cache-Control'])406 self.assert_equal(cc.max_age, expected_max_age)407 rv.close()408 finally:409 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default410411 with app.test_request_context():412 self.assert_equal(flask.url_for('admin.static', filename='test.txt'),413 '/admin/static/test.txt')414415 with app.test_request_context():416 try:417 flask.render_template('missing.html')418 except TemplateNotFound as e:419 self.assert_equal(e.name, 'missing.html')420 else:421 self.assert_true(0, 'expected exception')422423 with flask.Flask(__name__).test_request_context():424 self.assert_equal(flask.render_template('nested/nested.txt'), 'I\'m nested')425426 def test_default_static_cache_timeout(self):427 app = flask.Flask(__name__)428 class MyBlueprint(flask.Blueprint):429 def get_send_file_max_age(self, filename):430 return 100431432 blueprint = MyBlueprint('blueprint', __name__, static_folder='static')433 app.register_blueprint(blueprint)434435 # try/finally, in case other tests use this app for Blueprint tests.436 max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT']437 try:438 with app.test_request_context():439 unexpected_max_age = 3600440 if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == unexpected_max_age:441 unexpected_max_age = 7200442 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = unexpected_max_age443 rv = blueprint.send_static_file('index.html')444 cc = parse_cache_control_header(rv.headers['Cache-Control'])445 self.assert_equal(cc.max_age, 100)446 rv.close()447 finally:448 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default449450 def test_templates_list(self):451 from blueprintapp import app452 templates = sorted(app.jinja_env.list_templates())453 self.assert_equal(templates, ['admin/index.html',454 'frontend/index.html'])455456 def test_dotted_names(self):457 frontend = flask.Blueprint('myapp.frontend', __name__)458 backend = flask.Blueprint('myapp.backend', __name__)459460 @frontend.route('/fe')461 def frontend_index():462 return flask.url_for('myapp.backend.backend_index')463464 @frontend.route('/fe2')465 def frontend_page2():466 return flask.url_for('.frontend_index')467468 @backend.route('/be')469 def backend_index():470 return flask.url_for('myapp.frontend.frontend_index')471472 app = flask.Flask(__name__)473 app.register_blueprint(frontend)474 app.register_blueprint(backend)475476 c = app.test_client()477 self.assert_equal(c.get('/fe').data.strip(), b'/be')478 self.assert_equal(c.get('/fe2').data.strip(), b'/fe')479 self.assert_equal(c.get('/be').data.strip(), b'/fe')480481 def test_dotted_names_from_app(self):482 app = flask.Flask(__name__)483 app.testing = True484 test = flask.Blueprint('test', __name__)485486 @app.route('/')487 def app_index():488 return flask.url_for('test.index')489490 @test.route('/test/')491 def index():492 return flask.url_for('app_index')493494 app.register_blueprint(test)495496 with app.test_client() as c:497 rv = c.get('/')498 self.assert_equal(rv.data, b'/test/')499500 def test_empty_url_defaults(self):501 bp = flask.Blueprint('bp', __name__)502503 @bp.route('/', defaults={'page': 1})504 @bp.route('/page/<int:page>')505 def something(page):506 return str(page)507508 app = flask.Flask(__name__)509 app.register_blueprint(bp)510511 c = app.test_client()512 self.assert_equal(c.get('/').data, b'1')513 self.assert_equal(c.get('/page/2').data, b'2')514515 def test_route_decorator_custom_endpoint(self):516517 bp = flask.Blueprint('bp', __name__)518519 @bp.route('/foo')520 def foo():521 return flask.request.endpoint522523 @bp.route('/bar', endpoint='bar')524 def foo_bar():525 return flask.request.endpoint526527 @bp.route('/bar/123', endpoint='123')528 def foo_bar_foo():529 return flask.request.endpoint530531 @bp.route('/bar/foo')532 def bar_foo():533 return flask.request.endpoint534535 app = flask.Flask(__name__)536 app.register_blueprint(bp, url_prefix='/py')537538 @app.route('/')539 def index():540 return flask.request.endpoint541542 c = app.test_client()543 self.assertEqual(c.get('/').data, b'index')544 self.assertEqual(c.get('/py/foo').data, b'bp.foo')545 self.assertEqual(c.get('/py/bar').data, b'bp.bar')546 self.assertEqual(c.get('/py/bar/123').data, b'bp.123')547 self.assertEqual(c.get('/py/bar/foo').data, b'bp.bar_foo')548549 def test_route_decorator_custom_endpoint_with_dots(self):550 bp = flask.Blueprint('bp', __name__)551552 @bp.route('/foo')553 def foo():554 return flask.request.endpoint555556 try:557 @bp.route('/bar', endpoint='bar.bar')558 def foo_bar():559 return flask.request.endpoint560 except AssertionError:561 pass562 else:563 raise AssertionError('expected AssertionError not raised')564565 try:566 @bp.route('/bar/123', endpoint='bar.123')567 def foo_bar_foo():568 return flask.request.endpoint569 except AssertionError:570 pass571 else:572 raise AssertionError('expected AssertionError not raised')573574 def foo_foo_foo():575 pass576577 self.assertRaises(578 AssertionError,579 lambda: bp.add_url_rule(580 '/bar/123', endpoint='bar.123', view_func=foo_foo_foo581 )582 )583584 self.assertRaises(585 AssertionError,586 bp.route('/bar/123', endpoint='bar.123'),587 lambda: None588 )589590 app = flask.Flask(__name__)591 app.register_blueprint(bp, url_prefix='/py')592593 c = app.test_client()594 self.assertEqual(c.get('/py/foo').data, b'bp.foo')595 # The rule's didn't actually made it through596 rv = c.get('/py/bar')597 assert rv.status_code == 404598 rv = c.get('/py/bar/123')599 assert rv.status_code == 404600601 def test_template_filter(self):602 bp = flask.Blueprint('bp', __name__)603 @bp.app_template_filter()604 def my_reverse(s):605 return s[::-1]606 app = flask.Flask(__name__)607 app.register_blueprint(bp, url_prefix='/py')608 self.assert_in('my_reverse', app.jinja_env.filters.keys())609 self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)610 self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba')611612 def test_add_template_filter(self):613 bp = flask.Blueprint('bp', __name__)614 def my_reverse(s):615 return s[::-1]616 bp.add_app_template_filter(my_reverse)617 app = flask.Flask(__name__)618 app.register_blueprint(bp, url_prefix='/py')619 self.assert_in('my_reverse', app.jinja_env.filters.keys())620 self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)621 self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba')622623 def test_template_filter_with_name(self):624 bp = flask.Blueprint('bp', __name__)625 @bp.app_template_filter('strrev')626 def my_reverse(s):627 return s[::-1]628 app = flask.Flask(__name__)629 app.register_blueprint(bp, url_prefix='/py')630 self.assert_in('strrev', app.jinja_env.filters.keys())631 self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)632 self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba')633634 def test_add_template_filter_with_name(self):635 bp = flask.Blueprint('bp', __name__)636 def my_reverse(s):637 return s[::-1]638 bp.add_app_template_filter(my_reverse, 'strrev')639 app = flask.Flask(__name__)640 app.register_blueprint(bp, url_prefix='/py')641 self.assert_in('strrev', app.jinja_env.filters.keys())642 self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)643 self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba')644645 def test_template_filter_with_template(self):646 bp = flask.Blueprint('bp', __name__)647 @bp.app_template_filter()648 def super_reverse(s):649 return s[::-1]650 app = flask.Flask(__name__)651 app.register_blueprint(bp, url_prefix='/py')652 @app.route('/')653 def index():654 return flask.render_template('template_filter.html', value='abcd')655 rv = app.test_client().get('/')656 self.assert_equal(rv.data, b'dcba')657658 def test_template_filter_after_route_with_template(self):659 app = flask.Flask(__name__)660 @app.route('/')661 def index():662 return flask.render_template('template_filter.html', value='abcd')663 bp = flask.Blueprint('bp', __name__)664 @bp.app_template_filter()665 def super_reverse(s):666 return s[::-1]667 app.register_blueprint(bp, url_prefix='/py')668 rv = app.test_client().get('/')669 self.assert_equal(rv.data, b'dcba')670671 def test_add_template_filter_with_template(self):672 bp = flask.Blueprint('bp', __name__)673 def super_reverse(s):674 return s[::-1]675 bp.add_app_template_filter(super_reverse)676 app = flask.Flask(__name__)677 app.register_blueprint(bp, url_prefix='/py')678 @app.route('/')679 def index():680 return flask.render_template('template_filter.html', value='abcd')681 rv = app.test_client().get('/')682 self.assert_equal(rv.data, b'dcba')683684 def test_template_filter_with_name_and_template(self):685 bp = flask.Blueprint('bp', __name__)686 @bp.app_template_filter('super_reverse')687 def my_reverse(s):688 return s[::-1]689 app = flask.Flask(__name__)690 app.register_blueprint(bp, url_prefix='/py')691 @app.route('/')692 def index():693 return flask.render_template('template_filter.html', value='abcd')694 rv = app.test_client().get('/')695 self.assert_equal(rv.data, b'dcba')696697 def test_add_template_filter_with_name_and_template(self):698 bp = flask.Blueprint('bp', __name__)699 def my_reverse(s):700 return s[::-1]701 bp.add_app_template_filter(my_reverse, 'super_reverse')702 app = flask.Flask(__name__)703 app.register_blueprint(bp, url_prefix='/py')704 @app.route('/')705 def index():706 return flask.render_template('template_filter.html', value='abcd')707 rv = app.test_client().get('/')708 self.assert_equal(rv.data, b'dcba')709710 def test_template_test(self):711 bp = flask.Blueprint('bp', __name__)712 @bp.app_template_test()713 def is_boolean(value):714 return isinstance(value, bool)715 app = flask.Flask(__name__)716 app.register_blueprint(bp, url_prefix='/py')717 self.assert_in('is_boolean', app.jinja_env.tests.keys())718 self.assert_equal(app.jinja_env.tests['is_boolean'], is_boolean)719 self.assert_true(app.jinja_env.tests['is_boolean'](False))720721 def test_add_template_test(self):722 bp = flask.Blueprint('bp', __name__)723 def is_boolean(value):724 return isinstance(value, bool)725 bp.add_app_template_test(is_boolean)726 app = flask.Flask(__name__)727 app.register_blueprint(bp, url_prefix='/py')728 self.assert_in('is_boolean', app.jinja_env.tests.keys())729 self.assert_equal(app.jinja_env.tests['is_boolean'], is_boolean)730 self.assert_true(app.jinja_env.tests['is_boolean'](False))731732 def test_template_test_with_name(self):733 bp = flask.Blueprint('bp', __name__)734 @bp.app_template_test('boolean')735 def is_boolean(value):736 return isinstance(value, bool)737 app = flask.Flask(__name__)738 app.register_blueprint(bp, url_prefix='/py')739 self.assert_in('boolean', app.jinja_env.tests.keys())740 self.assert_equal(app.jinja_env.tests['boolean'], is_boolean)741 self.assert_true(app.jinja_env.tests['boolean'](False))742743 def test_add_template_test_with_name(self):744 bp = flask.Blueprint('bp', __name__)745 def is_boolean(value):746 return isinstance(value, bool)747 bp.add_app_template_test(is_boolean, 'boolean')748 app = flask.Flask(__name__)749 app.register_blueprint(bp, url_prefix='/py')750 self.assert_in('boolean', app.jinja_env.tests.keys())751 self.assert_equal(app.jinja_env.tests['boolean'], is_boolean)752 self.assert_true(app.jinja_env.tests['boolean'](False))753754 def test_template_test_with_template(self):755 bp = flask.Blueprint('bp', __name__)756 @bp.app_template_test()757 def boolean(value):758 return isinstance(value, bool)759 app = flask.Flask(__name__)760 app.register_blueprint(bp, url_prefix='/py')761 @app.route('/')762 def index():763 return flask.render_template('template_test.html', value=False)764 rv = app.test_client().get('/')765 self.assert_in(b'Success!', rv.data)766767 def test_template_test_after_route_with_template(self):768 app = flask.Flask(__name__)769 @app.route('/')770 def index():771 return flask.render_template('template_test.html', value=False)772 bp = flask.Blueprint('bp', __name__)773 @bp.app_template_test()774 def boolean(value):775 return isinstance(value, bool)776 app.register_blueprint(bp, url_prefix='/py')777 rv = app.test_client().get('/')778 self.assert_in(b'Success!', rv.data)779780 def test_add_template_test_with_template(self):781 bp = flask.Blueprint('bp', __name__)782 def boolean(value):783 return isinstance(value, bool)784 bp.add_app_template_test(boolean)785 app = flask.Flask(__name__)786 app.register_blueprint(bp, url_prefix='/py')787 @app.route('/')788 def index():789 return flask.render_template('template_test.html', value=False)790 rv = app.test_client().get('/')791 self.assert_in(b'Success!', rv.data)792793 def test_template_test_with_name_and_template(self):794 bp = flask.Blueprint('bp', __name__)795 @bp.app_template_test('boolean')796 def is_boolean(value):797 return isinstance(value, bool)798 app = flask.Flask(__name__)799 app.register_blueprint(bp, url_prefix='/py')800 @app.route('/')801 def index():802 return flask.render_template('template_test.html', value=False)803 rv = app.test_client().get('/')804 self.assert_in(b'Success!', rv.data)805806 def test_add_template_test_with_name_and_template(self):807 bp = flask.Blueprint('bp', __name__)808 def is_boolean(value):809 return isinstance(value, bool)810 bp.add_app_template_test(is_boolean, 'boolean')811 app = flask.Flask(__name__)812 app.register_blueprint(bp, url_prefix='/py')813 @app.route('/')814 def index():815 return flask.render_template('template_test.html', value=False)816 rv = app.test_client().get('/')817 self.assert_in(b'Success!', rv.data)818819def suite():820 suite = unittest.TestSuite()821 suite.addTest(unittest.makeSuite(BlueprintTestCase))822 suite.addTest(unittest.makeSuite(ModuleTestCase))823 return suite
deleted:flask/testsuite/config.py-356 removed
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.config4 ~~~~~~~~~~~~~~~~~~~~~~56 Configuration and instances.78 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import os13import sys14import flask15import pkgutil16import unittest17from contextlib import contextmanager18from flask.testsuite import FlaskTestCase19from flask._compat import PY2202122# config keys used for the ConfigTestCase23TEST_KEY = 'foo'24SECRET_KEY = 'devkey'252627class ConfigTestCase(FlaskTestCase):2829 def common_object_test(self, app):30 self.assert_equal(app.secret_key, 'devkey')31 self.assert_equal(app.config['TEST_KEY'], 'foo')32 self.assert_not_in('ConfigTestCase', app.config)3334 def test_config_from_file(self):35 app = flask.Flask(__name__)36 app.config.from_pyfile(__file__.rsplit('.', 1)[0] + '.py')37 self.common_object_test(app)3839 def test_config_from_object(self):40 app = flask.Flask(__name__)41 app.config.from_object(__name__)42 self.common_object_test(app)4344 def test_config_from_json(self):45 app = flask.Flask(__name__)46 current_dir = os.path.dirname(os.path.abspath(__file__))47 app.config.from_json(os.path.join(current_dir, 'static', 'config.json'))48 self.common_object_test(app)4950 def test_config_from_class(self):51 class Base(object):52 TEST_KEY = 'foo'53 class Test(Base):54 SECRET_KEY = 'devkey'55 app = flask.Flask(__name__)56 app.config.from_object(Test)57 self.common_object_test(app)5859 def test_config_from_envvar(self):60 env = os.environ61 try:62 os.environ = {}63 app = flask.Flask(__name__)64 try:65 app.config.from_envvar('FOO_SETTINGS')66 except RuntimeError as e:67 self.assert_true("'FOO_SETTINGS' is not set" in str(e))68 else:69 self.assert_true(0, 'expected exception')70 self.assert_false(app.config.from_envvar('FOO_SETTINGS', silent=True))7172 os.environ = {'FOO_SETTINGS': __file__.rsplit('.', 1)[0] + '.py'}73 self.assert_true(app.config.from_envvar('FOO_SETTINGS'))74 self.common_object_test(app)75 finally:76 os.environ = env7778 def test_config_from_envvar_missing(self):79 env = os.environ80 try:81 os.environ = {'FOO_SETTINGS': 'missing.cfg'}82 try:83 app = flask.Flask(__name__)84 app.config.from_envvar('FOO_SETTINGS')85 except IOError as e:86 msg = str(e)87 self.assert_true(msg.startswith('[Errno 2] Unable to load configuration '88 'file (No such file or directory):'))89 self.assert_true(msg.endswith("missing.cfg'"))90 else:91 self.fail('expected IOError')92 self.assertFalse(app.config.from_envvar('FOO_SETTINGS', silent=True))93 finally:94 os.environ = env9596 def test_config_missing(self):97 app = flask.Flask(__name__)98 try:99 app.config.from_pyfile('missing.cfg')100 except IOError as e:101 msg = str(e)102 self.assert_true(msg.startswith('[Errno 2] Unable to load configuration '103 'file (No such file or directory):'))104 self.assert_true(msg.endswith("missing.cfg'"))105 else:106 self.assert_true(0, 'expected config')107 self.assert_false(app.config.from_pyfile('missing.cfg', silent=True))108109 def test_config_missing_json(self):110 app = flask.Flask(__name__)111 try:112 app.config.from_json('missing.json')113 except IOError as e:114 msg = str(e)115 self.assert_true(msg.startswith('[Errno 2] Unable to load configuration '116 'file (No such file or directory):'))117 self.assert_true(msg.endswith("missing.json'"))118 else:119 self.assert_true(0, 'expected config')120 self.assert_false(app.config.from_json('missing.json', silent=True))121122 def test_custom_config_class(self):123 class Config(flask.Config):124 pass125 class Flask(flask.Flask):126 config_class = Config127 app = Flask(__name__)128 self.assert_isinstance(app.config, Config)129 app.config.from_object(__name__)130 self.common_object_test(app)131132 def test_session_lifetime(self):133 app = flask.Flask(__name__)134 app.config['PERMANENT_SESSION_LIFETIME'] = 42135 self.assert_equal(app.permanent_session_lifetime.seconds, 42)136137 def test_get_namespace(self):138 app = flask.Flask(__name__)139 app.config['FOO_OPTION_1'] = 'foo option 1'140 app.config['FOO_OPTION_2'] = 'foo option 2'141 app.config['BAR_STUFF_1'] = 'bar stuff 1'142 app.config['BAR_STUFF_2'] = 'bar stuff 2'143 foo_options = app.config.get_namespace('FOO_')144 self.assert_equal(2, len(foo_options))145 self.assert_equal('foo option 1', foo_options['option_1'])146 self.assert_equal('foo option 2', foo_options['option_2'])147 bar_options = app.config.get_namespace('BAR_', lowercase=False)148 self.assert_equal(2, len(bar_options))149 self.assert_equal('bar stuff 1', bar_options['STUFF_1'])150 self.assert_equal('bar stuff 2', bar_options['STUFF_2'])151152153class LimitedLoaderMockWrapper(object):154 def __init__(self, loader):155 self.loader = loader156157 def __getattr__(self, name):158 if name in ('archive', 'get_filename'):159 msg = 'Mocking a loader which does not have `%s.`' % name160 raise AttributeError(msg)161 return getattr(self.loader, name)162163164@contextmanager165def patch_pkgutil_get_loader(wrapper_class=LimitedLoaderMockWrapper):166 """Patch pkgutil.get_loader to give loader without get_filename or archive.167168 This provides for tests where a system has custom loaders, e.g. Google App169 Engine's HardenedModulesHook, which have neither the `get_filename` method170 nor the `archive` attribute.171 """172 old_get_loader = pkgutil.get_loader173 def get_loader(*args, **kwargs):174 return wrapper_class(old_get_loader(*args, **kwargs))175 try:176 pkgutil.get_loader = get_loader177 yield178 finally:179 pkgutil.get_loader = old_get_loader180181182class InstanceTestCase(FlaskTestCase):183184 def test_explicit_instance_paths(self):185 here = os.path.abspath(os.path.dirname(__file__))186 try:187 flask.Flask(__name__, instance_path='instance')188 except ValueError as e:189 self.assert_in('must be absolute', str(e))190 else:191 self.fail('Expected value error')192193 app = flask.Flask(__name__, instance_path=here)194 self.assert_equal(app.instance_path, here)195196 def test_main_module_paths(self):197 # Test an app with '__main__' as the import name, uses cwd.198 from main_app import app199 here = os.path.abspath(os.getcwd())200 self.assert_equal(app.instance_path, os.path.join(here, 'instance'))201 if 'main_app' in sys.modules:202 del sys.modules['main_app']203204 def test_uninstalled_module_paths(self):205 from config_module_app import app206 here = os.path.abspath(os.path.dirname(__file__))207 self.assert_equal(app.instance_path, os.path.join(here, 'test_apps', 'instance'))208209 def test_uninstalled_package_paths(self):210 from config_package_app import app211 here = os.path.abspath(os.path.dirname(__file__))212 self.assert_equal(app.instance_path, os.path.join(here, 'test_apps', 'instance'))213214 def test_installed_module_paths(self):215 here = os.path.abspath(os.path.dirname(__file__))216 expected_prefix = os.path.join(here, 'test_apps')217 real_prefix, sys.prefix = sys.prefix, expected_prefix218 site_packages = os.path.join(expected_prefix, 'lib', 'python2.5', 'site-packages')219 sys.path.append(site_packages)220 try:221 import site_app222 self.assert_equal(site_app.app.instance_path,223 os.path.join(expected_prefix, 'var',224 'site_app-instance'))225 finally:226 sys.prefix = real_prefix227 sys.path.remove(site_packages)228 if 'site_app' in sys.modules:229 del sys.modules['site_app']230231 def test_installed_module_paths_with_limited_loader(self):232 here = os.path.abspath(os.path.dirname(__file__))233 expected_prefix = os.path.join(here, 'test_apps')234 real_prefix, sys.prefix = sys.prefix, expected_prefix235 site_packages = os.path.join(expected_prefix, 'lib', 'python2.5', 'site-packages')236 sys.path.append(site_packages)237 with patch_pkgutil_get_loader():238 try:239 import site_app240 self.assert_equal(site_app.app.instance_path,241 os.path.join(expected_prefix, 'var',242 'site_app-instance'))243 finally:244 sys.prefix = real_prefix245 sys.path.remove(site_packages)246 if 'site_app' in sys.modules:247 del sys.modules['site_app']248249 def test_installed_package_paths(self):250 here = os.path.abspath(os.path.dirname(__file__))251 expected_prefix = os.path.join(here, 'test_apps')252 real_prefix, sys.prefix = sys.prefix, expected_prefix253 installed_path = os.path.join(expected_prefix, 'path')254 sys.path.append(installed_path)255 try:256 import installed_package257 self.assert_equal(installed_package.app.instance_path,258 os.path.join(expected_prefix, 'var',259 'installed_package-instance'))260 finally:261 sys.prefix = real_prefix262 sys.path.remove(installed_path)263 if 'installed_package' in sys.modules:264 del sys.modules['installed_package']265266 def test_installed_package_paths_with_limited_loader(self):267 here = os.path.abspath(os.path.dirname(__file__))268 expected_prefix = os.path.join(here, 'test_apps')269 real_prefix, sys.prefix = sys.prefix, expected_prefix270 installed_path = os.path.join(expected_prefix, 'path')271 sys.path.append(installed_path)272 with patch_pkgutil_get_loader():273 try:274 import installed_package275 self.assert_equal(installed_package.app.instance_path,276 os.path.join(expected_prefix, 'var',277 'installed_package-instance'))278 finally:279 sys.prefix = real_prefix280 sys.path.remove(installed_path)281 if 'installed_package' in sys.modules:282 del sys.modules['installed_package']283284 def test_prefix_package_paths(self):285 here = os.path.abspath(os.path.dirname(__file__))286 expected_prefix = os.path.join(here, 'test_apps')287 real_prefix, sys.prefix = sys.prefix, expected_prefix288 site_packages = os.path.join(expected_prefix, 'lib', 'python2.5', 'site-packages')289 sys.path.append(site_packages)290 try:291 import site_package292 self.assert_equal(site_package.app.instance_path,293 os.path.join(expected_prefix, 'var',294 'site_package-instance'))295 finally:296 sys.prefix = real_prefix297 sys.path.remove(site_packages)298 if 'site_package' in sys.modules:299 del sys.modules['site_package']300301 def test_prefix_package_paths_with_limited_loader(self):302 here = os.path.abspath(os.path.dirname(__file__))303 expected_prefix = os.path.join(here, 'test_apps')304 real_prefix, sys.prefix = sys.prefix, expected_prefix305 site_packages = os.path.join(expected_prefix, 'lib', 'python2.5', 'site-packages')306 sys.path.append(site_packages)307 with patch_pkgutil_get_loader():308 try:309 import site_package310 self.assert_equal(site_package.app.instance_path,311 os.path.join(expected_prefix, 'var',312 'site_package-instance'))313 finally:314 sys.prefix = real_prefix315 sys.path.remove(site_packages)316 if 'site_package' in sys.modules:317 del sys.modules['site_package']318319 def test_egg_installed_paths(self):320 here = os.path.abspath(os.path.dirname(__file__))321 expected_prefix = os.path.join(here, 'test_apps')322 real_prefix, sys.prefix = sys.prefix, expected_prefix323 site_packages = os.path.join(expected_prefix, 'lib', 'python2.5', 'site-packages')324 egg_path = os.path.join(site_packages, 'SiteEgg.egg')325 sys.path.append(site_packages)326 sys.path.append(egg_path)327 try:328 import site_egg # in SiteEgg.egg329 self.assert_equal(site_egg.app.instance_path,330 os.path.join(expected_prefix, 'var',331 'site_egg-instance'))332 finally:333 sys.prefix = real_prefix334 sys.path.remove(site_packages)335 sys.path.remove(egg_path)336 if 'site_egg' in sys.modules:337 del sys.modules['site_egg']338339 if PY2:340 def test_meta_path_loader_without_is_package(self):341 class Loader(object):342 def find_module(self, name):343 return self344 sys.meta_path.append(Loader())345 try:346 with self.assert_raises(AttributeError):347 flask.Flask(__name__)348 finally:349 sys.meta_path.pop()350351352def suite():353 suite = unittest.TestSuite()354 suite.addTest(unittest.makeSuite(ConfigTestCase))355 suite.addTest(unittest.makeSuite(InstanceTestCase))356 return suite
deleted:flask/testsuite/deprecations.py-24 removed
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.deprecations4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~56 Tests deprecation support.78 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import flask13import unittest14from flask.testsuite import FlaskTestCase, catch_warnings151617class DeprecationsTestCase(FlaskTestCase):18 """not used currently"""192021def suite():22 suite = unittest.TestSuite()23 suite.addTest(unittest.makeSuite(DeprecationsTestCase))24 return suite
deleted:flask/testsuite/examples.py-38 removed
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.examples4 ~~~~~~~~~~~~~~~~~~~~~~~~56 Tests the examples.78 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import os12import unittest13from flask.testsuite import add_to_path141516def setup_path():17 example_path = os.path.join(os.path.dirname(__file__),18 os.pardir, os.pardir, 'examples')19 add_to_path(os.path.join(example_path, 'flaskr'))20 add_to_path(os.path.join(example_path, 'minitwit'))212223def suite():24 setup_path()25 suite = unittest.TestSuite()26 try:27 from minitwit_tests import MiniTwitTestCase28 except ImportError:29 pass30 else:31 suite.addTest(unittest.makeSuite(MiniTwitTestCase))32 try:33 from flaskr_tests import FlaskrTestCase34 except ImportError:35 pass36 else:37 suite.addTest(unittest.makeSuite(FlaskrTestCase))38 return suite
deleted:flask/testsuite/ext.py-136 removed
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.ext4 ~~~~~~~~~~~~~~~~~~~56 Tests the extension import thing.78 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import sys13import unittest14try:15 from imp import reload as reload_module16except ImportError:17 reload_module = reload18from flask.testsuite import FlaskTestCase19from flask._compat import PY22021class ExtImportHookTestCase(FlaskTestCase):2223 def setup(self):24 # we clear this out for various reasons. The most important one is25 # that a real flaskext could be in there which would disable our26 # fake package. Secondly we want to make sure that the flaskext27 # import hook does not break on reloading.28 for entry, value in list(sys.modules.items()):29 if (entry.startswith('flask.ext.') or30 entry.startswith('flask_') or31 entry.startswith('flaskext.') or32 entry == 'flaskext') and value is not None:33 sys.modules.pop(entry, None)34 from flask import ext35 reload_module(ext)3637 # reloading must not add more hooks38 import_hooks = 039 for item in sys.meta_path:40 cls = type(item)41 if cls.__module__ == 'flask.exthook' and \42 cls.__name__ == 'ExtensionImporter':43 import_hooks += 144 self.assert_equal(import_hooks, 1)4546 def teardown(self):47 from flask import ext48 for key in ext.__dict__:49 self.assert_not_in('.', key)5051 def test_flaskext_new_simple_import_normal(self):52 from flask.ext.newext_simple import ext_id53 self.assert_equal(ext_id, 'newext_simple')5455 def test_flaskext_new_simple_import_module(self):56 from flask.ext import newext_simple57 self.assert_equal(newext_simple.ext_id, 'newext_simple')58 self.assert_equal(newext_simple.__name__, 'flask_newext_simple')5960 def test_flaskext_new_package_import_normal(self):61 from flask.ext.newext_package import ext_id62 self.assert_equal(ext_id, 'newext_package')6364 def test_flaskext_new_package_import_module(self):65 from flask.ext import newext_package66 self.assert_equal(newext_package.ext_id, 'newext_package')67 self.assert_equal(newext_package.__name__, 'flask_newext_package')6869 def test_flaskext_new_package_import_submodule_function(self):70 from flask.ext.newext_package.submodule import test_function71 self.assert_equal(test_function(), 42)7273 def test_flaskext_new_package_import_submodule(self):74 from flask.ext.newext_package import submodule75 self.assert_equal(submodule.__name__, 'flask_newext_package.submodule')76 self.assert_equal(submodule.test_function(), 42)7778 def test_flaskext_old_simple_import_normal(self):79 from flask.ext.oldext_simple import ext_id80 self.assert_equal(ext_id, 'oldext_simple')8182 def test_flaskext_old_simple_import_module(self):83 from flask.ext import oldext_simple84 self.assert_equal(oldext_simple.ext_id, 'oldext_simple')85 self.assert_equal(oldext_simple.__name__, 'flaskext.oldext_simple')8687 def test_flaskext_old_package_import_normal(self):88 from flask.ext.oldext_package import ext_id89 self.assert_equal(ext_id, 'oldext_package')9091 def test_flaskext_old_package_import_module(self):92 from flask.ext import oldext_package93 self.assert_equal(oldext_package.ext_id, 'oldext_package')94 self.assert_equal(oldext_package.__name__, 'flaskext.oldext_package')9596 def test_flaskext_old_package_import_submodule(self):97 from flask.ext.oldext_package import submodule98 self.assert_equal(submodule.__name__, 'flaskext.oldext_package.submodule')99 self.assert_equal(submodule.test_function(), 42)100101 def test_flaskext_old_package_import_submodule_function(self):102 from flask.ext.oldext_package.submodule import test_function103 self.assert_equal(test_function(), 42)104105 def test_flaskext_broken_package_no_module_caching(self):106 for x in range(2):107 with self.assert_raises(ImportError):108 import flask.ext.broken109110 def test_no_error_swallowing(self):111 try:112 import flask.ext.broken113 except ImportError:114 exc_type, exc_value, tb = sys.exc_info()115 self.assert_true(exc_type is ImportError)116 if PY2:117 message = 'No module named missing_module'118 else:119 message = 'No module named \'missing_module\''120 self.assert_equal(str(exc_value), message)121 self.assert_true(tb.tb_frame.f_globals is globals())122123 # reraise() adds a second frame so we need to skip that one too.124 # On PY3 we even have another one :(125 next = tb.tb_next.tb_next126 if not PY2:127 next = next.tb_next128 129 import os.path130 self.assert_in(os.path.join('flask_broken', '__init__.py'), next.tb_frame.f_code.co_filename)131132133def suite():134 suite = unittest.TestSuite()135 suite.addTest(unittest.makeSuite(ExtImportHookTestCase))136 return suite
deleted:flask/testsuite/helpers.py-658 removed
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.helpers4 ~~~~~~~~~~~~~~~~~~~~~~~56 Various helpers.78 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import os13import flask14import unittest15from logging import StreamHandler16from flask.testsuite import FlaskTestCase, catch_warnings, catch_stderr17from werkzeug.http import parse_cache_control_header, parse_options_header18from flask._compat import StringIO, text_type192021def has_encoding(name):22 try:23 import codecs24 codecs.lookup(name)25 return True26 except LookupError:27 return False282930class JSONTestCase(FlaskTestCase):3132 def test_json_bad_requests(self):33 app = flask.Flask(__name__)34 @app.route('/json', methods=['POST'])35 def return_json():36 return flask.jsonify(foo=text_type(flask.request.get_json()))37 c = app.test_client()38 rv = c.post('/json', data='malformed', content_type='application/json')39 self.assert_equal(rv.status_code, 400)4041 def test_json_custom_mimetypes(self):42 app = flask.Flask(__name__)43 @app.route('/json', methods=['POST'])44 def return_json():45 return flask.request.get_json()46 c = app.test_client()47 rv = c.post('/json', data='"foo"', content_type='application/x+json')48 self.assert_equal(rv.data, b'foo')4950 def test_json_body_encoding(self):51 app = flask.Flask(__name__)52 app.testing = True53 @app.route('/')54 def index():55 return flask.request.get_json()5657 c = app.test_client()58 resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),59 content_type='application/json; charset=iso-8859-15')60 self.assert_equal(resp.data, u'Hällo Wörld'.encode('utf-8'))6162 def test_jsonify(self):63 d = dict(a=23, b=42, c=[1, 2, 3])64 app = flask.Flask(__name__)65 @app.route('/kw')66 def return_kwargs():67 return flask.jsonify(**d)68 @app.route('/dict')69 def return_dict():70 return flask.jsonify(d)71 c = app.test_client()72 for url in '/kw', '/dict':73 rv = c.get(url)74 self.assert_equal(rv.mimetype, 'application/json')75 self.assert_equal(flask.json.loads(rv.data), d)7677 def test_json_as_unicode(self):78 app = flask.Flask(__name__)7980 app.config['JSON_AS_ASCII'] = True81 with app.app_context():82 rv = flask.json.dumps(u'\N{SNOWMAN}')83 self.assert_equal(rv, '"\\u2603"')8485 app.config['JSON_AS_ASCII'] = False86 with app.app_context():87 rv = flask.json.dumps(u'\N{SNOWMAN}')88 self.assert_equal(rv, u'"\u2603"')8990 def test_json_attr(self):91 app = flask.Flask(__name__)92 @app.route('/add', methods=['POST'])93 def add():94 json = flask.request.get_json()95 return text_type(json['a'] + json['b'])96 c = app.test_client()97 rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),98 content_type='application/json')99 self.assert_equal(rv.data, b'3')100101 def test_template_escaping(self):102 app = flask.Flask(__name__)103 render = flask.render_template_string104 with app.test_request_context():105 rv = flask.json.htmlsafe_dumps('</script>')106 self.assert_equal(rv, u'"\\u003c/script\\u003e"')107 self.assert_equal(type(rv), text_type)108 rv = render('{{ "</script>"|tojson }}')109 self.assert_equal(rv, '"\\u003c/script\\u003e"')110 rv = render('{{ "<\0/script>"|tojson }}')111 self.assert_equal(rv, '"\\u003c\\u0000/script\\u003e"')112 rv = render('{{ "<!--<script>"|tojson }}')113 self.assert_equal(rv, '"\\u003c!--\\u003cscript\\u003e"')114 rv = render('{{ "&"|tojson }}')115 self.assert_equal(rv, '"\\u0026"')116 rv = render('{{ "\'"|tojson }}')117 self.assert_equal(rv, '"\\u0027"')118 rv = render("<a ng-data='{{ data|tojson }}'></a>",119 data={'x': ["foo", "bar", "baz'"]})120 self.assert_equal(rv,121 '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>')122123 def test_json_customization(self):124 class X(object):125 def __init__(self, val):126 self.val = val127 class MyEncoder(flask.json.JSONEncoder):128 def default(self, o):129 if isinstance(o, X):130 return '<%d>' % o.val131 return flask.json.JSONEncoder.default(self, o)132 class MyDecoder(flask.json.JSONDecoder):133 def __init__(self, *args, **kwargs):134 kwargs.setdefault('object_hook', self.object_hook)135 flask.json.JSONDecoder.__init__(self, *args, **kwargs)136 def object_hook(self, obj):137 if len(obj) == 1 and '_foo' in obj:138 return X(obj['_foo'])139 return obj140 app = flask.Flask(__name__)141 app.testing = True142 app.json_encoder = MyEncoder143 app.json_decoder = MyDecoder144 @app.route('/', methods=['POST'])145 def index():146 return flask.json.dumps(flask.request.get_json()['x'])147 c = app.test_client()148 rv = c.post('/', data=flask.json.dumps({149 'x': {'_foo': 42}150 }), content_type='application/json')151 self.assertEqual(rv.data, b'"<42>"')152153 def test_modified_url_encoding(self):154 class ModifiedRequest(flask.Request):155 url_charset = 'euc-kr'156 app = flask.Flask(__name__)157 app.testing = True158 app.request_class = ModifiedRequest159 app.url_map.charset = 'euc-kr'160161 @app.route('/')162 def index():163 return flask.request.args['foo']164165 rv = app.test_client().get(u'/?foo=정상처리'.encode('euc-kr'))166 self.assert_equal(rv.status_code, 200)167 self.assert_equal(rv.data, u'정상처리'.encode('utf-8'))168169 if not has_encoding('euc-kr'):170 test_modified_url_encoding = None171172 def test_json_key_sorting(self):173 app = flask.Flask(__name__)174 app.testing = True175 self.assert_equal(app.config['JSON_SORT_KEYS'], True)176 d = dict.fromkeys(range(20), 'foo')177178 @app.route('/')179 def index():180 return flask.jsonify(values=d)181182 c = app.test_client()183 rv = c.get('/')184 lines = [x.strip() for x in rv.data.strip().decode('utf-8').splitlines()]185 sorted_by_str = [186 '{',187 '"values": {',188 '"0": "foo",',189 '"1": "foo",',190 '"10": "foo",',191 '"11": "foo",',192 '"12": "foo",',193 '"13": "foo",',194 '"14": "foo",',195 '"15": "foo",',196 '"16": "foo",',197 '"17": "foo",',198 '"18": "foo",',199 '"19": "foo",',200 '"2": "foo",',201 '"3": "foo",',202 '"4": "foo",',203 '"5": "foo",',204 '"6": "foo",',205 '"7": "foo",',206 '"8": "foo",',207 '"9": "foo"',208 '}',209 '}'210 ]211 sorted_by_int = [212 '{',213 '"values": {',214 '"0": "foo",',215 '"1": "foo",',216 '"2": "foo",',217 '"3": "foo",',218 '"4": "foo",',219 '"5": "foo",',220 '"6": "foo",',221 '"7": "foo",',222 '"8": "foo",',223 '"9": "foo",',224 '"10": "foo",',225 '"11": "foo",',226 '"12": "foo",',227 '"13": "foo",',228 '"14": "foo",',229 '"15": "foo",',230 '"16": "foo",',231 '"17": "foo",',232 '"18": "foo",',233 '"19": "foo"',234 '}',235 '}'236 ]237238 try:239 self.assert_equal(lines, sorted_by_int)240 except AssertionError:241 self.assert_equal(lines, sorted_by_str)242243class SendfileTestCase(FlaskTestCase):244245 def test_send_file_regular(self):246 app = flask.Flask(__name__)247 with app.test_request_context():248 rv = flask.send_file('static/index.html')249 self.assert_true(rv.direct_passthrough)250 self.assert_equal(rv.mimetype, 'text/html')251 with app.open_resource('static/index.html') as f:252 rv.direct_passthrough = False253 self.assert_equal(rv.data, f.read())254 rv.close()255256 def test_send_file_xsendfile(self):257 app = flask.Flask(__name__)258 app.use_x_sendfile = True259 with app.test_request_context():260 rv = flask.send_file('static/index.html')261 self.assert_true(rv.direct_passthrough)262 self.assert_in('x-sendfile', rv.headers)263 self.assert_equal(rv.headers['x-sendfile'],264 os.path.join(app.root_path, 'static/index.html'))265 self.assert_equal(rv.mimetype, 'text/html')266 rv.close()267268 def test_send_file_object(self):269 app = flask.Flask(__name__)270 with catch_warnings() as captured:271 with app.test_request_context():272 f = open(os.path.join(app.root_path, 'static/index.html'), mode='rb')273 rv = flask.send_file(f)274 rv.direct_passthrough = False275 with app.open_resource('static/index.html') as f:276 self.assert_equal(rv.data, f.read())277 self.assert_equal(rv.mimetype, 'text/html')278 rv.close()279 # mimetypes + etag280 self.assert_equal(len(captured), 2)281282 app.use_x_sendfile = True283 with catch_warnings() as captured:284 with app.test_request_context():285 f = open(os.path.join(app.root_path, 'static/index.html'))286 rv = flask.send_file(f)287 self.assert_equal(rv.mimetype, 'text/html')288 self.assert_in('x-sendfile', rv.headers)289 self.assert_equal(rv.headers['x-sendfile'],290 os.path.join(app.root_path, 'static/index.html'))291 rv.close()292 # mimetypes + etag293 self.assert_equal(len(captured), 2)294295 app.use_x_sendfile = False296 with app.test_request_context():297 with catch_warnings() as captured:298 f = StringIO('Test')299 rv = flask.send_file(f)300 rv.direct_passthrough = False301 self.assert_equal(rv.data, b'Test')302 self.assert_equal(rv.mimetype, 'application/octet-stream')303 rv.close()304 # etags305 self.assert_equal(len(captured), 1)306 with catch_warnings() as captured:307 class PyStringIO(object):308 def __init__(self, *args, **kwargs):309 self._io = StringIO(*args, **kwargs)310 def __getattr__(self, name):311 return getattr(self._io, name)312 f = PyStringIO('Test')313 f.name = 'test.txt'314 rv = flask.send_file(f)315 rv.direct_passthrough = False316 self.assert_equal(rv.data, b'Test')317 self.assert_equal(rv.mimetype, 'text/plain')318 rv.close()319 # attachment_filename and etags320 self.assert_equal(len(captured), 3)321 with catch_warnings() as captured:322 f = StringIO('Test')323 rv = flask.send_file(f, mimetype='text/plain')324 rv.direct_passthrough = False325 self.assert_equal(rv.data, b'Test')326 self.assert_equal(rv.mimetype, 'text/plain')327 rv.close()328 # etags329 self.assert_equal(len(captured), 1)330331 app.use_x_sendfile = True332 with catch_warnings() as captured:333 with app.test_request_context():334 f = StringIO('Test')335 rv = flask.send_file(f)336 self.assert_not_in('x-sendfile', rv.headers)337 rv.close()338 # etags339 self.assert_equal(len(captured), 1)340341 def test_attachment(self):342 app = flask.Flask(__name__)343 with catch_warnings() as captured:344 with app.test_request_context():345 f = open(os.path.join(app.root_path, 'static/index.html'))346 rv = flask.send_file(f, as_attachment=True)347 value, options = parse_options_header(rv.headers['Content-Disposition'])348 self.assert_equal(value, 'attachment')349 rv.close()350 # mimetypes + etag351 self.assert_equal(len(captured), 2)352353 with app.test_request_context():354 self.assert_equal(options['filename'], 'index.html')355 rv = flask.send_file('static/index.html', as_attachment=True)356 value, options = parse_options_header(rv.headers['Content-Disposition'])357 self.assert_equal(value, 'attachment')358 self.assert_equal(options['filename'], 'index.html')359 rv.close()360361 with app.test_request_context():362 rv = flask.send_file(StringIO('Test'), as_attachment=True,363 attachment_filename='index.txt',364 add_etags=False)365 self.assert_equal(rv.mimetype, 'text/plain')366 value, options = parse_options_header(rv.headers['Content-Disposition'])367 self.assert_equal(value, 'attachment')368 self.assert_equal(options['filename'], 'index.txt')369 rv.close()370371 def test_static_file(self):372 app = flask.Flask(__name__)373 # default cache timeout is 12 hours374 with app.test_request_context():375 # Test with static file handler.376 rv = app.send_static_file('index.html')377 cc = parse_cache_control_header(rv.headers['Cache-Control'])378 self.assert_equal(cc.max_age, 12 * 60 * 60)379 rv.close()380 # Test again with direct use of send_file utility.381 rv = flask.send_file('static/index.html')382 cc = parse_cache_control_header(rv.headers['Cache-Control'])383 self.assert_equal(cc.max_age, 12 * 60 * 60)384 rv.close()385 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600386 with app.test_request_context():387 # Test with static file handler.388 rv = app.send_static_file('index.html')389 cc = parse_cache_control_header(rv.headers['Cache-Control'])390 self.assert_equal(cc.max_age, 3600)391 rv.close()392 # Test again with direct use of send_file utility.393 rv = flask.send_file('static/index.html')394 cc = parse_cache_control_header(rv.headers['Cache-Control'])395 self.assert_equal(cc.max_age, 3600)396 rv.close()397 class StaticFileApp(flask.Flask):398 def get_send_file_max_age(self, filename):399 return 10400 app = StaticFileApp(__name__)401 with app.test_request_context():402 # Test with static file handler.403 rv = app.send_static_file('index.html')404 cc = parse_cache_control_header(rv.headers['Cache-Control'])405 self.assert_equal(cc.max_age, 10)406 rv.close()407 # Test again with direct use of send_file utility.408 rv = flask.send_file('static/index.html')409 cc = parse_cache_control_header(rv.headers['Cache-Control'])410 self.assert_equal(cc.max_age, 10)411 rv.close()412413 def test_send_from_directory(self):414 app = flask.Flask(__name__)415 app.testing = True416 app.root_path = os.path.join(os.path.dirname(__file__),417 'test_apps', 'subdomaintestmodule')418 with app.test_request_context():419 rv = flask.send_from_directory('static', 'hello.txt')420 rv.direct_passthrough = False421 self.assert_equal(rv.data.strip(), b'Hello Subdomain')422 rv.close()423424425class LoggingTestCase(FlaskTestCase):426427 def test_logger_cache(self):428 app = flask.Flask(__name__)429 logger1 = app.logger430 self.assert_true(app.logger is logger1)431 self.assert_equal(logger1.name, __name__)432 app.logger_name = __name__ + '/test_logger_cache'433 self.assert_true(app.logger is not logger1)434435 def test_debug_log(self):436 app = flask.Flask(__name__)437 app.debug = True438439 @app.route('/')440 def index():441 app.logger.warning('the standard library is dead')442 app.logger.debug('this is a debug statement')443 return ''444445 @app.route('/exc')446 def exc():447 1 // 0448449 with app.test_client() as c:450 with catch_stderr() as err:451 c.get('/')452 out = err.getvalue()453 self.assert_in('WARNING in helpers [', out)454 self.assert_in(os.path.basename(__file__.rsplit('.', 1)[0] + '.py'), out)455 self.assert_in('the standard library is dead', out)456 self.assert_in('this is a debug statement', out)457458 with catch_stderr() as err:459 try:460 c.get('/exc')461 except ZeroDivisionError:462 pass463 else:464 self.assert_true(False, 'debug log ate the exception')465466 def test_debug_log_override(self):467 app = flask.Flask(__name__)468 app.debug = True469 app.logger_name = 'flask_tests/test_debug_log_override'470 app.logger.level = 10471 self.assert_equal(app.logger.level, 10)472473 def test_exception_logging(self):474 out = StringIO()475 app = flask.Flask(__name__)476 app.logger_name = 'flask_tests/test_exception_logging'477 app.logger.addHandler(StreamHandler(out))478479 @app.route('/')480 def index():481 1 // 0482483 rv = app.test_client().get('/')484 self.assert_equal(rv.status_code, 500)485 self.assert_in(b'Internal Server Error', rv.data)486487 err = out.getvalue()488 self.assert_in('Exception on / [GET]', err)489 self.assert_in('Traceback (most recent call last):', err)490 self.assert_in('1 // 0', err)491 self.assert_in('ZeroDivisionError:', err)492493 def test_processor_exceptions(self):494 app = flask.Flask(__name__)495 @app.before_request496 def before_request():497 if trigger == 'before':498 1 // 0499 @app.after_request500 def after_request(response):501 if trigger == 'after':502 1 // 0503 return response504 @app.route('/')505 def index():506 return 'Foo'507 @app.errorhandler(500)508 def internal_server_error(e):509 return 'Hello Server Error', 500510 for trigger in 'before', 'after':511 rv = app.test_client().get('/')512 self.assert_equal(rv.status_code, 500)513 self.assert_equal(rv.data, b'Hello Server Error')514515 def test_url_for_with_anchor(self):516 app = flask.Flask(__name__)517 @app.route('/')518 def index():519 return '42'520 with app.test_request_context():521 self.assert_equal(flask.url_for('index', _anchor='x y'),522 '/#x%20y')523524 def test_url_for_with_scheme(self):525 app = flask.Flask(__name__)526 @app.route('/')527 def index():528 return '42'529 with app.test_request_context():530 self.assert_equal(flask.url_for('index',531 _external=True,532 _scheme='https'),533 'https://localhost/')534535 def test_url_for_with_scheme_not_external(self):536 app = flask.Flask(__name__)537 @app.route('/')538 def index():539 return '42'540 with app.test_request_context():541 self.assert_raises(ValueError,542 flask.url_for,543 'index',544 _scheme='https')545546 def test_url_with_method(self):547 from flask.views import MethodView548 app = flask.Flask(__name__)549 class MyView(MethodView):550 def get(self, id=None):551 if id is None:552 return 'List'553 return 'Get %d' % id554 def post(self):555 return 'Create'556 myview = MyView.as_view('myview')557 app.add_url_rule('/myview/', methods=['GET'],558 view_func=myview)559 app.add_url_rule('/myview/<int:id>', methods=['GET'],560 view_func=myview)561 app.add_url_rule('/myview/create', methods=['POST'],562 view_func=myview)563564 with app.test_request_context():565 self.assert_equal(flask.url_for('myview', _method='GET'),566 '/myview/')567 self.assert_equal(flask.url_for('myview', id=42, _method='GET'),568 '/myview/42')569 self.assert_equal(flask.url_for('myview', _method='POST'),570 '/myview/create')571572573class NoImportsTestCase(FlaskTestCase):574 """Test Flasks are created without import.575576 Avoiding ``__import__`` helps create Flask instances where there are errors577 at import time. Those runtime errors will be apparent to the user soon578 enough, but tools which build Flask instances meta-programmatically benefit579 from a Flask which does not ``__import__``. Instead of importing to580 retrieve file paths or metadata on a module or package, use the pkgutil and581 imp modules in the Python standard library.582 """583584 def test_name_with_import_error(self):585 try:586 flask.Flask('importerror')587 except NotImplementedError:588 self.fail('Flask(import_name) is importing import_name.')589590591class StreamingTestCase(FlaskTestCase):592593 def test_streaming_with_context(self):594 app = flask.Flask(__name__)595 app.testing = True596 @app.route('/')597 def index():598 def generate():599 yield 'Hello '600 yield flask.request.args['name']601 yield '!'602 return flask.Response(flask.stream_with_context(generate()))603 c = app.test_client()604 rv = c.get('/?name=World')605 self.assertEqual(rv.data, b'Hello World!')606607 def test_streaming_with_context_as_decorator(self):608 app = flask.Flask(__name__)609 app.testing = True610 @app.route('/')611 def index():612 @flask.stream_with_context613 def generate():614 yield 'Hello '615 yield flask.request.args['name']616 yield '!'617 return flask.Response(generate())618 c = app.test_client()619 rv = c.get('/?name=World')620 self.assertEqual(rv.data, b'Hello World!')621622 def test_streaming_with_context_and_custom_close(self):623 app = flask.Flask(__name__)624 app.testing = True625 called = []626 class Wrapper(object):627 def __init__(self, gen):628 self._gen = gen629 def __iter__(self):630 return self631 def close(self):632 called.append(42)633 def __next__(self):634 return next(self._gen)635 next = __next__636 @app.route('/')637 def index():638 def generate():639 yield 'Hello '640 yield flask.request.args['name']641 yield '!'642 return flask.Response(flask.stream_with_context(643 Wrapper(generate())))644 c = app.test_client()645 rv = c.get('/?name=World')646 self.assertEqual(rv.data, b'Hello World!')647 self.assertEqual(called, [42])648649650def suite():651 suite = unittest.TestSuite()652 if flask.json_available:653 suite.addTest(unittest.makeSuite(JSONTestCase))654 suite.addTest(unittest.makeSuite(SendfileTestCase))655 suite.addTest(unittest.makeSuite(LoggingTestCase))656 suite.addTest(unittest.makeSuite(NoImportsTestCase))657 suite.addTest(unittest.makeSuite(StreamingTestCase))658 return suite
deleted:flask/testsuite/regression.py-116 removed
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.regression4 ~~~~~~~~~~~~~~~~~~~~~~~~~~56 Tests regressions.78 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import os13import gc14import sys15import flask16import threading17import unittest18from werkzeug.exceptions import NotFound19from flask.testsuite import FlaskTestCase202122_gc_lock = threading.Lock()232425class _NoLeakAsserter(object):2627 def __init__(self, testcase):28 self.testcase = testcase2930 def __enter__(self):31 gc.disable()32 _gc_lock.acquire()33 loc = flask._request_ctx_stack._local3435 # Force Python to track this dictionary at all times.36 # This is necessary since Python only starts tracking37 # dicts if they contain mutable objects. It's a horrible,38 # horrible hack but makes this kinda testable.39 loc.__storage__['FOOO'] = [1, 2, 3]4041 gc.collect()42 self.old_objects = len(gc.get_objects())4344 def __exit__(self, exc_type, exc_value, tb):45 if not hasattr(sys, 'getrefcount'):46 gc.collect()47 new_objects = len(gc.get_objects())48 if new_objects > self.old_objects:49 self.testcase.fail('Example code leaked')50 _gc_lock.release()51 gc.enable()525354class MemoryTestCase(FlaskTestCase):5556 def assert_no_leak(self):57 return _NoLeakAsserter(self)5859 def test_memory_consumption(self):60 app = flask.Flask(__name__)61 @app.route('/')62 def index():63 return flask.render_template('simple_template.html', whiskey=42)6465 def fire():66 with app.test_client() as c:67 rv = c.get('/')68 self.assert_equal(rv.status_code, 200)69 self.assert_equal(rv.data, b'<h1>42</h1>')7071 # Trigger caches72 fire()7374 # This test only works on CPython 2.7.75 if sys.version_info >= (2, 7) and \76 not hasattr(sys, 'pypy_translation_info'):77 with self.assert_no_leak():78 for x in range(10):79 fire()8081 def test_safe_join_toplevel_pardir(self):82 from flask.helpers import safe_join83 with self.assert_raises(NotFound):84 safe_join('/foo', '..')858687class ExceptionTestCase(FlaskTestCase):8889 def test_aborting(self):90 class Foo(Exception):91 whatever = 4292 app = flask.Flask(__name__)93 app.testing = True94 @app.errorhandler(Foo)95 def handle_foo(e):96 return str(e.whatever)97 @app.route('/')98 def index():99 raise flask.abort(flask.redirect(flask.url_for('test')))100 @app.route('/test')101 def test():102 raise Foo()103104 with app.test_client() as c:105 rv = c.get('/')106 self.assertEqual(rv.headers['Location'], 'http://localhost/test')107 rv = c.get('/test')108 self.assertEqual(rv.data, b'42')109110111def suite():112 suite = unittest.TestSuite()113 if os.environ.get('RUN_FLASK_MEMORY_TESTS') == '1':114 suite.addTest(unittest.makeSuite(MemoryTestCase))115 suite.addTest(unittest.makeSuite(ExceptionTestCase))116 return suite
deleted:flask/testsuite/reqctx.py-201 removed
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.reqctx4 ~~~~~~~~~~~~~~~~~~~~~~56 Tests the request context.78 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import flask13import unittest14try:15 from greenlet import greenlet16except ImportError:17 greenlet = None18from flask.testsuite import FlaskTestCase192021class RequestContextTestCase(FlaskTestCase):2223 def test_teardown_on_pop(self):24 buffer = []25 app = flask.Flask(__name__)26 @app.teardown_request27 def end_of_request(exception):28 buffer.append(exception)2930 ctx = app.test_request_context()31 ctx.push()32 self.assert_equal(buffer, [])33 ctx.pop()34 self.assert_equal(buffer, [None])3536 def test_teardown_with_previous_exception(self):37 buffer = []38 app = flask.Flask(__name__)39 @app.teardown_request40 def end_of_request(exception):41 buffer.append(exception)4243 try:44 raise Exception('dummy')45 except Exception:46 pass4748 with app.test_request_context():49 self.assert_equal(buffer, [])50 self.assert_equal(buffer, [None])5152 def test_proper_test_request_context(self):53 app = flask.Flask(__name__)54 app.config.update(55 SERVER_NAME='localhost.localdomain:5000'56 )5758 @app.route('/')59 def index():60 return None6162 @app.route('/', subdomain='foo')63 def sub():64 return None6566 with app.test_request_context('/'):67 self.assert_equal(flask.url_for('index', _external=True), 'http://localhost.localdomain:5000/')6869 with app.test_request_context('/'):70 self.assert_equal(flask.url_for('sub', _external=True), 'http://foo.localhost.localdomain:5000/')7172 try:73 with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}):74 pass75 except Exception as e:76 self.assert_true(isinstance(e, ValueError))77 self.assert_equal(str(e), "the server name provided " +78 "('localhost.localdomain:5000') does not match the " + \79 "server name from the WSGI environment ('localhost')")8081 try:82 app.config.update(SERVER_NAME='localhost')83 with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}):84 pass85 except ValueError as e:86 raise ValueError(87 "No ValueError exception should have been raised \"%s\"" % e88 )8990 try:91 app.config.update(SERVER_NAME='localhost:80')92 with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}):93 pass94 except ValueError as e:95 raise ValueError(96 "No ValueError exception should have been raised \"%s\"" % e97 )9899 def test_context_binding(self):100 app = flask.Flask(__name__)101 @app.route('/')102 def index():103 return 'Hello %s!' % flask.request.args['name']104 @app.route('/meh')105 def meh():106 return flask.request.url107108 with app.test_request_context('/?name=World'):109 self.assert_equal(index(), 'Hello World!')110 with app.test_request_context('/meh'):111 self.assert_equal(meh(), 'http://localhost/meh')112 self.assert_true(flask._request_ctx_stack.top is None)113114 def test_context_test(self):115 app = flask.Flask(__name__)116 self.assert_false(flask.request)117 self.assert_false(flask.has_request_context())118 ctx = app.test_request_context()119 ctx.push()120 try:121 self.assert_true(flask.request)122 self.assert_true(flask.has_request_context())123 finally:124 ctx.pop()125126 def test_manual_context_binding(self):127 app = flask.Flask(__name__)128 @app.route('/')129 def index():130 return 'Hello %s!' % flask.request.args['name']131132 ctx = app.test_request_context('/?name=World')133 ctx.push()134 self.assert_equal(index(), 'Hello World!')135 ctx.pop()136 try:137 index()138 except RuntimeError:139 pass140 else:141 self.assert_true(0, 'expected runtime error')142143 def test_greenlet_context_copying(self):144 app = flask.Flask(__name__)145 greenlets = []146147 @app.route('/')148 def index():149 reqctx = flask._request_ctx_stack.top.copy()150 def g():151 self.assert_false(flask.request)152 self.assert_false(flask.current_app)153 with reqctx:154 self.assert_true(flask.request)155 self.assert_equal(flask.current_app, app)156 self.assert_equal(flask.request.path, '/')157 self.assert_equal(flask.request.args['foo'], 'bar')158 self.assert_false(flask.request)159 return 42160 greenlets.append(greenlet(g))161 return 'Hello World!'162163 rv = app.test_client().get('/?foo=bar')164 self.assert_equal(rv.data, b'Hello World!')165166 result = greenlets[0].run()167 self.assert_equal(result, 42)168169 def test_greenlet_context_copying_api(self):170 app = flask.Flask(__name__)171 greenlets = []172173 @app.route('/')174 def index():175 reqctx = flask._request_ctx_stack.top.copy()176 @flask.copy_current_request_context177 def g():178 self.assert_true(flask.request)179 self.assert_equal(flask.current_app, app)180 self.assert_equal(flask.request.path, '/')181 self.assert_equal(flask.request.args['foo'], 'bar')182 return 42183 greenlets.append(greenlet(g))184 return 'Hello World!'185186 rv = app.test_client().get('/?foo=bar')187 self.assert_equal(rv.data, b'Hello World!')188189 result = greenlets[0].run()190 self.assert_equal(result, 42)191192 # Disable test if we don't have greenlets available193 if greenlet is None:194 test_greenlet_context_copying = None195 test_greenlet_context_copying_api = None196197198def suite():199 suite = unittest.TestSuite()200 suite.addTest(unittest.makeSuite(RequestContextTestCase))201 return suite
deleted:flask/testsuite/signals.py-153 removed
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.signals4 ~~~~~~~~~~~~~~~~~~~~~~~56 Signalling.78 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import flask13import unittest14from flask.testsuite import FlaskTestCase151617class SignalsTestCase(FlaskTestCase):1819 def test_template_rendered(self):20 app = flask.Flask(__name__)2122 @app.route('/')23 def index():24 return flask.render_template('simple_template.html', whiskey=42)2526 recorded = []27 def record(sender, template, context):28 recorded.append((template, context))2930 flask.template_rendered.connect(record, app)31 try:32 app.test_client().get('/')33 self.assert_equal(len(recorded), 1)34 template, context = recorded[0]35 self.assert_equal(template.name, 'simple_template.html')36 self.assert_equal(context['whiskey'], 42)37 finally:38 flask.template_rendered.disconnect(record, app)3940 def test_request_signals(self):41 app = flask.Flask(__name__)42 calls = []4344 def before_request_signal(sender):45 calls.append('before-signal')4647 def after_request_signal(sender, response):48 self.assert_equal(response.data, b'stuff')49 calls.append('after-signal')5051 @app.before_request52 def before_request_handler():53 calls.append('before-handler')5455 @app.after_request56 def after_request_handler(response):57 calls.append('after-handler')58 response.data = 'stuff'59 return response6061 @app.route('/')62 def index():63 calls.append('handler')64 return 'ignored anyway'6566 flask.request_started.connect(before_request_signal, app)67 flask.request_finished.connect(after_request_signal, app)6869 try:70 rv = app.test_client().get('/')71 self.assert_equal(rv.data, b'stuff')7273 self.assert_equal(calls, ['before-signal', 'before-handler',74 'handler', 'after-handler',75 'after-signal'])76 finally:77 flask.request_started.disconnect(before_request_signal, app)78 flask.request_finished.disconnect(after_request_signal, app)7980 def test_request_exception_signal(self):81 app = flask.Flask(__name__)82 recorded = []8384 @app.route('/')85 def index():86 1 // 08788 def record(sender, exception):89 recorded.append(exception)9091 flask.got_request_exception.connect(record, app)92 try:93 self.assert_equal(app.test_client().get('/').status_code, 500)94 self.assert_equal(len(recorded), 1)95 self.assert_true(isinstance(recorded[0], ZeroDivisionError))96 finally:97 flask.got_request_exception.disconnect(record, app)9899 def test_appcontext_signals(self):100 app = flask.Flask(__name__)101 recorded = []102 def record_push(sender, **kwargs):103 recorded.append('push')104 def record_pop(sender, **kwargs):105 recorded.append('pop')106107 @app.route('/')108 def index():109 return 'Hello'110111 flask.appcontext_pushed.connect(record_push, app)112 flask.appcontext_popped.connect(record_pop, app)113 try:114 with app.test_client() as c:115 rv = c.get('/')116 self.assert_equal(rv.data, b'Hello')117 self.assert_equal(recorded, ['push'])118 self.assert_equal(recorded, ['push', 'pop'])119 finally:120 flask.appcontext_pushed.disconnect(record_push, app)121 flask.appcontext_popped.disconnect(record_pop, app)122123 def test_flash_signal(self):124 app = flask.Flask(__name__)125 app.config['SECRET_KEY'] = 'secret'126127 @app.route('/')128 def index():129 flask.flash('This is a flash message', category='notice')130 return flask.redirect('/other')131132 recorded = []133 def record(sender, message, category):134 recorded.append((message, category))135136 flask.message_flashed.connect(record, app)137 try:138 client = app.test_client()139 with client.session_transaction():140 client.get('/')141 self.assert_equal(len(recorded), 1)142 message, category = recorded[0]143 self.assert_equal(message, 'This is a flash message')144 self.assert_equal(category, 'notice')145 finally:146 flask.message_flashed.disconnect(record, app)147148149def suite():150 suite = unittest.TestSuite()151 if flask.signals_available:152 suite.addTest(unittest.makeSuite(SignalsTestCase))153 return suite
deleted:flask/testsuite/subclassing.py-46 removed
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.subclassing4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~56 Test that certain behavior of flask can be customized by7 subclasses.89 :copyright: (c) 2014 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""12import flask13import unittest14from logging import StreamHandler15from flask.testsuite import FlaskTestCase16from flask._compat import StringIO171819class FlaskSubclassingTestCase(FlaskTestCase):2021 def test_suppressed_exception_logging(self):22 class SuppressedFlask(flask.Flask):23 def log_exception(self, exc_info):24 pass2526 out = StringIO()27 app = SuppressedFlask(__name__)28 app.logger_name = 'flask_tests/test_suppressed_exception_logging'29 app.logger.addHandler(StreamHandler(out))3031 @app.route('/')32 def index():33 1 // 03435 rv = app.test_client().get('/')36 self.assert_equal(rv.status_code, 500)37 self.assert_in(b'Internal Server Error', rv.data)3839 err = out.getvalue()40 self.assert_equal(err, '')414243def suite():44 suite = unittest.TestSuite()45 suite.addTest(unittest.makeSuite(FlaskSubclassingTestCase))46 return suite
deleted:flask/testsuite/templating.py-310 removed
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.templating4 ~~~~~~~~~~~~~~~~~~~~~~~~~~56 Template functionality78 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import flask13import unittest14from flask.testsuite import FlaskTestCase151617class TemplatingTestCase(FlaskTestCase):1819 def test_context_processing(self):20 app = flask.Flask(__name__)21 @app.context_processor22 def context_processor():23 return {'injected_value': 42}24 @app.route('/')25 def index():26 return flask.render_template('context_template.html', value=23)27 rv = app.test_client().get('/')28 self.assert_equal(rv.data, b'<p>23|42')2930 def test_original_win(self):31 app = flask.Flask(__name__)32 @app.route('/')33 def index():34 return flask.render_template_string('{{ config }}', config=42)35 rv = app.test_client().get('/')36 self.assert_equal(rv.data, b'42')3738 def test_request_less_rendering(self):39 app = flask.Flask(__name__)40 app.config['WORLD_NAME'] = 'Special World'41 @app.context_processor42 def context_processor():43 return dict(foo=42)4445 with app.app_context():46 rv = flask.render_template_string('Hello {{ config.WORLD_NAME }} '47 '{{ foo }}')48 self.assert_equal(rv, 'Hello Special World 42')4950 def test_standard_context(self):51 app = flask.Flask(__name__)52 app.secret_key = 'development key'53 @app.route('/')54 def index():55 flask.g.foo = 2356 flask.session['test'] = 'aha'57 return flask.render_template_string('''58 {{ request.args.foo }}59 {{ g.foo }}60 {{ config.DEBUG }}61 {{ session.test }}62 ''')63 rv = app.test_client().get('/?foo=42')64 self.assert_equal(rv.data.split(), [b'42', b'23', b'False', b'aha'])6566 def test_escaping(self):67 text = '<p>Hello World!'68 app = flask.Flask(__name__)69 @app.route('/')70 def index():71 return flask.render_template('escaping_template.html', text=text,72 html=flask.Markup(text))73 lines = app.test_client().get('/').data.splitlines()74 self.assert_equal(lines, [75 b'&lt;p&gt;Hello World!',76 b'<p>Hello World!',77 b'<p>Hello World!',78 b'<p>Hello World!',79 b'&lt;p&gt;Hello World!',80 b'<p>Hello World!'81 ])8283 def test_no_escaping(self):84 app = flask.Flask(__name__)85 with app.test_request_context():86 self.assert_equal(flask.render_template_string('{{ foo }}',87 foo='<test>'), '<test>')88 self.assert_equal(flask.render_template('mail.txt', foo='<test>'),89 '<test> Mail')9091 def test_macros(self):92 app = flask.Flask(__name__)93 with app.test_request_context():94 macro = flask.get_template_attribute('_macro.html', 'hello')95 self.assert_equal(macro('World'), 'Hello World!')9697 def test_template_filter(self):98 app = flask.Flask(__name__)99 @app.template_filter()100 def my_reverse(s):101 return s[::-1]102 self.assert_in('my_reverse', app.jinja_env.filters.keys())103 self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)104 self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba')105106 def test_add_template_filter(self):107 app = flask.Flask(__name__)108 def my_reverse(s):109 return s[::-1]110 app.add_template_filter(my_reverse)111 self.assert_in('my_reverse', app.jinja_env.filters.keys())112 self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)113 self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba')114115 def test_template_filter_with_name(self):116 app = flask.Flask(__name__)117 @app.template_filter('strrev')118 def my_reverse(s):119 return s[::-1]120 self.assert_in('strrev', app.jinja_env.filters.keys())121 self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)122 self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba')123124 def test_add_template_filter_with_name(self):125 app = flask.Flask(__name__)126 def my_reverse(s):127 return s[::-1]128 app.add_template_filter(my_reverse, 'strrev')129 self.assert_in('strrev', app.jinja_env.filters.keys())130 self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)131 self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba')132133 def test_template_filter_with_template(self):134 app = flask.Flask(__name__)135 @app.template_filter()136 def super_reverse(s):137 return s[::-1]138 @app.route('/')139 def index():140 return flask.render_template('template_filter.html', value='abcd')141 rv = app.test_client().get('/')142 self.assert_equal(rv.data, b'dcba')143144 def test_add_template_filter_with_template(self):145 app = flask.Flask(__name__)146 def super_reverse(s):147 return s[::-1]148 app.add_template_filter(super_reverse)149 @app.route('/')150 def index():151 return flask.render_template('template_filter.html', value='abcd')152 rv = app.test_client().get('/')153 self.assert_equal(rv.data, b'dcba')154155 def test_template_filter_with_name_and_template(self):156 app = flask.Flask(__name__)157 @app.template_filter('super_reverse')158 def my_reverse(s):159 return s[::-1]160 @app.route('/')161 def index():162 return flask.render_template('template_filter.html', value='abcd')163 rv = app.test_client().get('/')164 self.assert_equal(rv.data, b'dcba')165166 def test_add_template_filter_with_name_and_template(self):167 app = flask.Flask(__name__)168 def my_reverse(s):169 return s[::-1]170 app.add_template_filter(my_reverse, 'super_reverse')171 @app.route('/')172 def index():173 return flask.render_template('template_filter.html', value='abcd')174 rv = app.test_client().get('/')175 self.assert_equal(rv.data, b'dcba')176177 def test_template_test(self):178 app = flask.Flask(__name__)179 @app.template_test()180 def boolean(value):181 return isinstance(value, bool)182 self.assert_in('boolean', app.jinja_env.tests.keys())183 self.assert_equal(app.jinja_env.tests['boolean'], boolean)184 self.assert_true(app.jinja_env.tests['boolean'](False))185186 def test_add_template_test(self):187 app = flask.Flask(__name__)188 def boolean(value):189 return isinstance(value, bool)190 app.add_template_test(boolean)191 self.assert_in('boolean', app.jinja_env.tests.keys())192 self.assert_equal(app.jinja_env.tests['boolean'], boolean)193 self.assert_true(app.jinja_env.tests['boolean'](False))194195 def test_template_test_with_name(self):196 app = flask.Flask(__name__)197 @app.template_test('boolean')198 def is_boolean(value):199 return isinstance(value, bool)200 self.assert_in('boolean', app.jinja_env.tests.keys())201 self.assert_equal(app.jinja_env.tests['boolean'], is_boolean)202 self.assert_true(app.jinja_env.tests['boolean'](False))203204 def test_add_template_test_with_name(self):205 app = flask.Flask(__name__)206 def is_boolean(value):207 return isinstance(value, bool)208 app.add_template_test(is_boolean, 'boolean')209 self.assert_in('boolean', app.jinja_env.tests.keys())210 self.assert_equal(app.jinja_env.tests['boolean'], is_boolean)211 self.assert_true(app.jinja_env.tests['boolean'](False))212213 def test_template_test_with_template(self):214 app = flask.Flask(__name__)215 @app.template_test()216 def boolean(value):217 return isinstance(value, bool)218 @app.route('/')219 def index():220 return flask.render_template('template_test.html', value=False)221 rv = app.test_client().get('/')222 self.assert_in(b'Success!', rv.data)223224 def test_add_template_test_with_template(self):225 app = flask.Flask(__name__)226 def boolean(value):227 return isinstance(value, bool)228 app.add_template_test(boolean)229 @app.route('/')230 def index():231 return flask.render_template('template_test.html', value=False)232 rv = app.test_client().get('/')233 self.assert_in(b'Success!', rv.data)234235 def test_template_test_with_name_and_template(self):236 app = flask.Flask(__name__)237 @app.template_test('boolean')238 def is_boolean(value):239 return isinstance(value, bool)240 @app.route('/')241 def index():242 return flask.render_template('template_test.html', value=False)243 rv = app.test_client().get('/')244 self.assert_in(b'Success!', rv.data)245246 def test_add_template_test_with_name_and_template(self):247 app = flask.Flask(__name__)248 def is_boolean(value):249 return isinstance(value, bool)250 app.add_template_test(is_boolean, 'boolean')251 @app.route('/')252 def index():253 return flask.render_template('template_test.html', value=False)254 rv = app.test_client().get('/')255 self.assert_in(b'Success!', rv.data)256257 def test_add_template_global(self):258 app = flask.Flask(__name__)259 @app.template_global()260 def get_stuff():261 return 42262 self.assert_in('get_stuff', app.jinja_env.globals.keys())263 self.assert_equal(app.jinja_env.globals['get_stuff'], get_stuff)264 self.assert_true(app.jinja_env.globals['get_stuff'](), 42)265 with app.app_context():266 rv = flask.render_template_string('{{ get_stuff() }}')267 self.assert_equal(rv, '42')268269 def test_custom_template_loader(self):270 class MyFlask(flask.Flask):271 def create_global_jinja_loader(self):272 from jinja2 import DictLoader273 return DictLoader({'index.html': 'Hello Custom World!'})274 app = MyFlask(__name__)275 @app.route('/')276 def index():277 return flask.render_template('index.html')278 c = app.test_client()279 rv = c.get('/')280 self.assert_equal(rv.data, b'Hello Custom World!')281282 def test_iterable_loader(self):283 app = flask.Flask(__name__)284 @app.context_processor285 def context_processor():286 return {'whiskey': 'Jameson'}287 @app.route('/')288 def index():289 return flask.render_template(290 ['no_template.xml', # should skip this one291 'simple_template.html', # should render this292 'context_template.html'],293 value=23)294295 rv = app.test_client().get('/')296 self.assert_equal(rv.data, b'<h1>Jameson</h1>')297298 def test_templates_auto_reload(self):299 app = flask.Flask(__name__)300 self.assert_true(app.config['TEMPLATES_AUTO_RELOAD'])301 self.assert_true(app.jinja_env.auto_reload)302 app = flask.Flask(__name__)303 app.config['TEMPLATES_AUTO_RELOAD'] = False304 self.assert_false(app.jinja_env.auto_reload)305306307def suite():308 suite = unittest.TestSuite()309 suite.addTest(unittest.makeSuite(TemplatingTestCase))310 return suite
deleted:flask/testsuite/testing.py-256 removed
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.testing4 ~~~~~~~~~~~~~~~~~~~~~~~56 Test client and more.78 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import flask13import unittest14from flask.testsuite import FlaskTestCase15from flask._compat import text_type161718class TestToolsTestCase(FlaskTestCase):1920 def test_environ_defaults_from_config(self):21 app = flask.Flask(__name__)22 app.testing = True23 app.config['SERVER_NAME'] = 'example.com:1234'24 app.config['APPLICATION_ROOT'] = '/foo'25 @app.route('/')26 def index():27 return flask.request.url2829 ctx = app.test_request_context()30 self.assert_equal(ctx.request.url, 'http://example.com:1234/foo/')31 with app.test_client() as c:32 rv = c.get('/')33 self.assert_equal(rv.data, b'http://example.com:1234/foo/')3435 def test_environ_defaults(self):36 app = flask.Flask(__name__)37 app.testing = True38 @app.route('/')39 def index():40 return flask.request.url4142 ctx = app.test_request_context()43 self.assert_equal(ctx.request.url, 'http://localhost/')44 with app.test_client() as c:45 rv = c.get('/')46 self.assert_equal(rv.data, b'http://localhost/')4748 def test_redirect_keep_session(self):49 app = flask.Flask(__name__)50 app.secret_key = 'testing'5152 @app.route('/', methods=['GET', 'POST'])53 def index():54 if flask.request.method == 'POST':55 return flask.redirect('/getsession')56 flask.session['data'] = 'foo'57 return 'index'5859 @app.route('/getsession')60 def get_session():61 return flask.session.get('data', '<missing>')6263 with app.test_client() as c:64 rv = c.get('/getsession')65 assert rv.data == b'<missing>'6667 rv = c.get('/')68 assert rv.data == b'index'69 assert flask.session.get('data') == 'foo'70 rv = c.post('/', data={}, follow_redirects=True)71 assert rv.data == b'foo'7273 # This support requires a new Werkzeug version74 if not hasattr(c, 'redirect_client'):75 assert flask.session.get('data') == 'foo'7677 rv = c.get('/getsession')78 assert rv.data == b'foo'7980 def test_session_transactions(self):81 app = flask.Flask(__name__)82 app.testing = True83 app.secret_key = 'testing'8485 @app.route('/')86 def index():87 return text_type(flask.session['foo'])8889 with app.test_client() as c:90 with c.session_transaction() as sess:91 self.assert_equal(len(sess), 0)92 sess['foo'] = [42]93 self.assert_equal(len(sess), 1)94 rv = c.get('/')95 self.assert_equal(rv.data, b'[42]')96 with c.session_transaction() as sess:97 self.assert_equal(len(sess), 1)98 self.assert_equal(sess['foo'], [42])99100 def test_session_transactions_no_null_sessions(self):101 app = flask.Flask(__name__)102 app.testing = True103104 with app.test_client() as c:105 try:106 with c.session_transaction() as sess:107 pass108 except RuntimeError as e:109 self.assert_in('Session backend did not open a session', str(e))110 else:111 self.fail('Expected runtime error')112113 def test_session_transactions_keep_context(self):114 app = flask.Flask(__name__)115 app.testing = True116 app.secret_key = 'testing'117118 with app.test_client() as c:119 rv = c.get('/')120 req = flask.request._get_current_object()121 self.assert_true(req is not None)122 with c.session_transaction():123 self.assert_true(req is flask.request._get_current_object())124125 def test_session_transaction_needs_cookies(self):126 app = flask.Flask(__name__)127 app.testing = True128 c = app.test_client(use_cookies=False)129 try:130 with c.session_transaction() as s:131 pass132 except RuntimeError as e:133 self.assert_in('cookies', str(e))134 else:135 self.fail('Expected runtime error')136137 def test_test_client_context_binding(self):138 app = flask.Flask(__name__)139 @app.route('/')140 def index():141 flask.g.value = 42142 return 'Hello World!'143144 @app.route('/other')145 def other():146 1 // 0147148 with app.test_client() as c:149 resp = c.get('/')150 self.assert_equal(flask.g.value, 42)151 self.assert_equal(resp.data, b'Hello World!')152 self.assert_equal(resp.status_code, 200)153154 resp = c.get('/other')155 self.assert_false(hasattr(flask.g, 'value'))156 self.assert_in(b'Internal Server Error', resp.data)157 self.assert_equal(resp.status_code, 500)158 flask.g.value = 23159160 try:161 flask.g.value162 except (AttributeError, RuntimeError):163 pass164 else:165 raise AssertionError('some kind of exception expected')166167 def test_reuse_client(self):168 app = flask.Flask(__name__)169 c = app.test_client()170171 with c:172 self.assert_equal(c.get('/').status_code, 404)173174 with c:175 self.assert_equal(c.get('/').status_code, 404)176177 def test_test_client_calls_teardown_handlers(self):178 app = flask.Flask(__name__)179 called = []180 @app.teardown_request181 def remember(error):182 called.append(error)183184 with app.test_client() as c:185 self.assert_equal(called, [])186 c.get('/')187 self.assert_equal(called, [])188 self.assert_equal(called, [None])189190 del called[:]191 with app.test_client() as c:192 self.assert_equal(called, [])193 c.get('/')194 self.assert_equal(called, [])195 c.get('/')196 self.assert_equal(called, [None])197 self.assert_equal(called, [None, None])198199 def test_full_url_request(self):200 app = flask.Flask(__name__)201 app.testing = True202203 @app.route('/action', methods=['POST'])204 def action():205 return 'x'206207 with app.test_client() as c:208 rv = c.post('http://domain.com/action?vodka=42', data={'gin': 43})209 self.assert_equal(rv.status_code, 200)210 self.assert_true('gin' in flask.request.form)211 self.assert_true('vodka' in flask.request.args)212213214class SubdomainTestCase(FlaskTestCase):215216 def setUp(self):217 self.app = flask.Flask(__name__)218 self.app.config['SERVER_NAME'] = 'example.com'219 self.client = self.app.test_client()220221 self._ctx = self.app.test_request_context()222 self._ctx.push()223224 def tearDown(self):225 if self._ctx is not None:226 self._ctx.pop()227228 def test_subdomain(self):229 @self.app.route('/', subdomain='<company_id>')230 def view(company_id):231 return company_id232233 url = flask.url_for('view', company_id='xxx')234 response = self.client.get(url)235236 self.assert_equal(200, response.status_code)237 self.assert_equal(b'xxx', response.data)238239240 def test_nosubdomain(self):241 @self.app.route('/<company_id>')242 def view(company_id):243 return company_id244245 url = flask.url_for('view', company_id='xxx')246 response = self.client.get(url)247248 self.assert_equal(200, response.status_code)249 self.assert_equal(b'xxx', response.data)250251252def suite():253 suite = unittest.TestSuite()254 suite.addTest(unittest.makeSuite(TestToolsTestCase))255 suite.addTest(unittest.makeSuite(SubdomainTestCase))256 return suite
deleted:flask/testsuite/views.py-169 removed
1# -*- coding: utf-8 -*-2"""3 flask.testsuite.views4 ~~~~~~~~~~~~~~~~~~~~~56 Pluggable views.78 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import flask13import flask.views14import unittest15from flask.testsuite import FlaskTestCase16from werkzeug.http import parse_set_header1718class ViewTestCase(FlaskTestCase):1920 def common_test(self, app):21 c = app.test_client()2223 self.assert_equal(c.get('/').data, b'GET')24 self.assert_equal(c.post('/').data, b'POST')25 self.assert_equal(c.put('/').status_code, 405)26 meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])27 self.assert_equal(sorted(meths), ['GET', 'HEAD', 'OPTIONS', 'POST'])2829 def test_basic_view(self):30 app = flask.Flask(__name__)3132 class Index(flask.views.View):33 methods = ['GET', 'POST']34 def dispatch_request(self):35 return flask.request.method3637 app.add_url_rule('/', view_func=Index.as_view('index'))38 self.common_test(app)3940 def test_method_based_view(self):41 app = flask.Flask(__name__)4243 class Index(flask.views.MethodView):44 def get(self):45 return 'GET'46 def post(self):47 return 'POST'4849 app.add_url_rule('/', view_func=Index.as_view('index'))5051 self.common_test(app)5253 def test_view_patching(self):54 app = flask.Flask(__name__)5556 class Index(flask.views.MethodView):57 def get(self):58 1 // 059 def post(self):60 1 // 06162 class Other(Index):63 def get(self):64 return 'GET'65 def post(self):66 return 'POST'6768 view = Index.as_view('index')69 view.view_class = Other70 app.add_url_rule('/', view_func=view)71 self.common_test(app)7273 def test_view_inheritance(self):74 app = flask.Flask(__name__)7576 class Index(flask.views.MethodView):77 def get(self):78 return 'GET'79 def post(self):80 return 'POST'8182 class BetterIndex(Index):83 def delete(self):84 return 'DELETE'8586 app.add_url_rule('/', view_func=BetterIndex.as_view('index'))87 c = app.test_client()8889 meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])90 self.assert_equal(sorted(meths), ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST'])9192 def test_view_decorators(self):93 app = flask.Flask(__name__)9495 def add_x_parachute(f):96 def new_function(*args, **kwargs):97 resp = flask.make_response(f(*args, **kwargs))98 resp.headers['X-Parachute'] = 'awesome'99 return resp100 return new_function101102 class Index(flask.views.View):103 decorators = [add_x_parachute]104 def dispatch_request(self):105 return 'Awesome'106107 app.add_url_rule('/', view_func=Index.as_view('index'))108 c = app.test_client()109 rv = c.get('/')110 self.assert_equal(rv.headers['X-Parachute'], 'awesome')111 self.assert_equal(rv.data, b'Awesome')112113 def test_implicit_head(self):114 app = flask.Flask(__name__)115116 class Index(flask.views.MethodView):117 def get(self):118 return flask.Response('Blub', headers={119 'X-Method': flask.request.method120 })121122 app.add_url_rule('/', view_func=Index.as_view('index'))123 c = app.test_client()124 rv = c.get('/')125 self.assert_equal(rv.data, b'Blub')126 self.assert_equal(rv.headers['X-Method'], 'GET')127 rv = c.head('/')128 self.assert_equal(rv.data, b'')129 self.assert_equal(rv.headers['X-Method'], 'HEAD')130131 def test_explicit_head(self):132 app = flask.Flask(__name__)133134 class Index(flask.views.MethodView):135 def get(self):136 return 'GET'137 def head(self):138 return flask.Response('', headers={'X-Method': 'HEAD'})139140 app.add_url_rule('/', view_func=Index.as_view('index'))141 c = app.test_client()142 rv = c.get('/')143 self.assert_equal(rv.data, b'GET')144 rv = c.head('/')145 self.assert_equal(rv.data, b'')146 self.assert_equal(rv.headers['X-Method'], 'HEAD')147148 def test_endpoint_override(self):149 app = flask.Flask(__name__)150 app.debug = True151152 class Index(flask.views.View):153 methods = ['GET', 'POST']154 def dispatch_request(self):155 return flask.request.method156157 app.add_url_rule('/', view_func=Index.as_view('index'))158159 with self.assert_raises(AssertionError):160 app.add_url_rule('/', view_func=Index.as_view('index'))161162 # But these tests should still pass. We just log a warning.163 self.common_test(app)164165166def suite():167 suite = unittest.TestSuite()168 suite.addTest(unittest.makeSuite(ViewTestCase))169 return suite
modified:flask/__init__.py+6 added-7 removed
4 unmodified lines
56 A microframework based on Werkzeug. It's extensively documented7 and follows best practice patterns.89 :copyright: (c) 2014 by Armin Ronacher.9 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213__version__ = '0.11-dev'13__version__ = '0.13-dev'1415# utilities we import from Werkzeug and Jinja2 that are unused16# in the module but are exported as public interface.17from werkzeug.exceptions import abort
2 unmodified lines
2021from .app import Flask, Request, Response22from .config import Config23from .helpers import url_for, flash, send_file, send_from_directory, \24 get_flashed_messages, get_template_attribute, make_response, safe_join, \25 stream_with_context24 get_flashed_messages, get_template_attribute, make_response, safe_join, \25 stream_with_context26from .globals import current_app, g, request, session, _request_ctx_stack, \27 _app_ctx_stack28from .ctx import has_request_context, has_app_context, \29 after_this_request, copy_current_request_context30from .module import Module30from .blueprints import Blueprint31from .templating import render_template, render_template_string3233# 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, \38 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 json4244# 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
added:flask/__main__.py+15 added
1# -*- coding: utf-8 -*-2"""3 flask.__main__4 ~~~~~~~~~~~~~~56 Alias for flask.run for the command line.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""111213if __name__ == '__main__':14 from .cli import main15 main(as_module=True)
modified:flask/_compat.py+19 added-20 removed
5 unmodified lines
6 Some py2/py3 compatibility support based on a stripped down7 version of six so we don't have to depend on a specific version8 of it.910 :copyright: (c) 2014 by Armin Ronacher.10 :copyright: (c) 2015 by Armin Ronacher.11 :license: BSD, see LICENSE for more details.12"""13import sys14
3 unmodified lines
1819if not PY2:20 text_type = str21 string_types = (str,)22 integer_types = (int, )22 integer_types = (int,)2324 iterkeys = lambda d: iter(d.keys())25 itervalues = lambda d: iter(d.values())26 iteritems = lambda d: iter(d.items())
26 unmodified lines
53 return cls545556def with_metaclass(meta, *bases):57 """Create a base class with a metaclass."""58 # This requires a bit of explanation: the basic idea is to make a59 # 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__60 # itself with the actual metaclass.61 class metaclass(type):62 def __new__(cls, name, this_bases, d):70 if this_bases is None:71 return type.__new__(cls, name, (), d)63 return meta(name, bases, d)73 return metaclass('temporary_class', None, {})64 return type.__new__(metaclass, 'temporary_class', (), {})656667# 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# happend until the next bytecode instruction?68# breaks the __exit__ function in a very peculiar way. The second level of69# exception blocks is necessary because pypy seems to forget to check if an70# exception happened until the next bytecode instruction?71#72# Relevant PyPy bugfix commit:73# https://bitbucket.org/pypy/pypy/commits/77ecf91c635a287e88e60d8ddb0f4e9df400330174# According to ronan on #pypy IRC, it is released in PyPy2 2.3 and later75# versions.76#77# Ubuntu 14.04 has PyPy 2.2.1, which does exhibit this bug.78BROKEN_PYPY_CTXMGR_EXIT = False79if hasattr(sys, 'pypy_version_info'):80 class _Mgr(object):81 def __enter__(self):82 return self83 def __exit__(self, *args):84 if hasattr(sys, 'exc_clear'):85 # Python 3 (PyPy3) doesn't have exc_clear87 sys.exc_clear()86 sys.exc_clear()87 try:88 try:89 with _Mgr():90 raise AssertionError()
6 unmodified lines
modified:flask/app.py+475 added-274 removed
3 unmodified lines
4 ~~~~~~~~~56 This module implements the central WSGI application object.78 :copyright: (c) 2014 by Armin Ronacher.8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1111import os12import sys14from threading import Lock13from datetime import timedelta16from itertools import chain14from functools import update_wrapper15from itertools import chain16from threading import Lock1719from werkzeug.datastructures import ImmutableDict20from werkzeug.routing import Map, Rule, RequestRedirect, BuildError21from werkzeug.exceptions import HTTPException, InternalServerError, \22 MethodNotAllowed, BadRequest18from 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 json27from .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 .module import blueprint_is_module32from .signals import appcontext_tearing_down, got_request_exception, \33 request_finished, request_started, request_tearing_down34from .templating import DispatchingJinjaLoader, Environment, \34 _default_template_ctx_processor35from .signals import request_started, request_finished, got_request_exception, \36 request_tearing_down, appcontext_tearing_down37from ._compat import reraise, string_types, text_type, integer_types35 _default_template_ctx_processor36from .wrappers import Request, Response3738# a lock used for logger initialization39_logger_lock = Lock()4041# a singleton sentinel value for parameter defaults42_sentinel = object()434445def _make_timedelta(value):46 if not isinstance(value, timedelta):47 return timedelta(seconds=value)48 return value
24 unmodified lines
7374 The name of the package is used to resolve resources from inside the75 package or the folder the module is contained in depending on if the76 package parameter resolves to an actual python package (a folder with75 an `__init__.py` file inside) or a standard module (just a `.py` file).77 an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).7879 For more information about resource loading, see :func:`open_resource`.8081 Usually you create a :class:`Flask` instance in your main module or80 in the `__init__.py` file of your package like this::82 in the :file:`__init__.py` file of your package like this::8384 from flask import Flask85 app = Flask(__name__)8687 .. admonition:: About the First Parameter8887 The idea of the first parameter is to give Flask an idea what89 The idea of the first parameter is to give Flask an idea of what90 belongs to your application. This name is used to find resources89 on the file system, can be used by extensions to improve debugging91 on the filesystem, can be used by extensions to improve debugging92 information and a lot more.9394 So it's important what you provide there. If you are using a single95 module, `__name__` is always the correct value. If you however are96 using a package, it's usually recommended to hardcode the name of97 your package there.9897 For example if your application is defined in `yourapplication/app.py`99 For example if your application is defined in :file:`yourapplication/app.py`100 you should create it with one of the two versions below::101102 app = Flask('yourapplication')103 app = Flask(__name__.split('.')[0])
15 unmodified lines
119 .. versionadded:: 0.8120 The `instance_path` and `instance_relative_config` parameters were121 added.122121 .. 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 folder in the root path of the application. Defaults137 to None.138 :param host_matching: sets the app's ``url_map.host_matching`` to the given139 given value. Defaults to False.140 :param static_host: the host to use when adding the static route. Defaults141 to None. Required when using ``host_matching=True``142 with a ``static_folder`` configured.143 :param template_folder: the folder that contains the templates that should144 be used by the application. Defaults to145 ``'templates'`` folder in the root path of the146 application.147 :param instance_path: An alternative instance path for the application.148 By default the folder ``'instance'`` next to the149 package or module is assumed to be the instance150 path.139 :param instance_relative_config: if set to `True` relative filenames151 :param instance_relative_config: if set to ``True`` relative filenames152 for loading the config are assumed to153 be relative to the instance path instead154 of the application root.155 :param root_path: Flask by default will automatically calculate the path
10 unmodified lines
166 #: The class that is used for response objects. See167 #: :class:`~flask.Response` for more information.168 response_class = Response169170 #: The class that is used for the Jinja environment.171 #:172 #: .. versionadded:: 0.11173 jinja_environment = Environment174175 #: The class that is used for the :data:`~flask.g` instance.176 #:177 #: Example use cases for a custom class:178 #:179 #: 1. Store arbitrary attributes on flask.g.180 #: 2. Add a property for lazy per-request database connectors.164 #: 3. Return None instead of AttributeError on expected attributes.181 #: 3. Return None instead of AttributeError on unexpected attributes.182 #: 4. Raise exception if an unexpected attr is set, a "controlled" flask.g.183 #:184 #: In Flask 0.9 this property was called `request_globals_class` but it185 #: was changed in 0.10 to :attr:`app_ctx_globals_class` because the169 #: flask.g object is not application context scoped.186 #: flask.g object is now application context scoped.187 #:188 #: .. versionadded:: 0.10189 app_ctx_globals_class = _AppCtxGlobals190
16 unmodified lines
207 #:208 #: 1. Default values for certain config options.209 #: 2. Access to config values through attributes in addition to keys.210 #:194 #: .. versionadded:: 1.0211 #: .. versionadded:: 0.11212 config_class = Config213197 #: The debug flag. Set this to `True` to enable debugging of the214 #: The debug flag. Set this to ``True`` to enable debugging of the215 #: application. In debug mode the debugger will kick in when an unhandled216 #: exception occurs and the integrated server will automatically reload217 #: the application if changes in the code are detected.218 #:202 #: This attribute can also be configured from the config with the `DEBUG`203 #: configuration key. Defaults to `False`.219 #: This attribute can also be configured from the config with the ``DEBUG``220 #: configuration key. Defaults to ``False``.221 debug = ConfigAttribute('DEBUG')222206 #: The testing flag. Set this to `True` to enable the test mode of223 #: The testing flag. Set this to ``True`` to enable the test mode of224 #: Flask extensions (and in the future probably also Flask itself).225 #: For example this might activate unittest helpers that have an226 #: additional runtime cost which should not be enabled by default.227 #:228 #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the229 #: default it's implicitly enabled.230 #:231 #: This attribute can also be configured from the config with the215 #: `TESTING` configuration key. Defaults to `False`.232 #: ``TESTING`` configuration key. Defaults to ``False``.233 testing = ConfigAttribute('TESTING')234235 #: If a secret key is set, cryptographic components can use this to236 #: sign cookies and other things. Set this to a complex random value237 #: when you want to use the secure cookie for instance.238 #:239 #: This attribute can also be configured from the config with the223 #: `SECRET_KEY` configuration key. Defaults to `None`.240 #: ``SECRET_KEY`` configuration key. Defaults to ``None``.241 secret_key = ConfigAttribute('SECRET_KEY')242243 #: The secure cookie uses this for the name of the session cookie.244 #:245 #: This attribute can also be configured from the config with the229 #: `SESSION_COOKIE_NAME` configuration key. Defaults to ``'session'``246 #: ``SESSION_COOKIE_NAME`` configuration key. Defaults to ``'session'``247 session_cookie_name = ConfigAttribute('SESSION_COOKIE_NAME')248249 #: A :class:`~datetime.timedelta` which is used to set the expiration250 #: date of a permanent session. The default is 31 days which makes a251 #: permanent session survive for roughly one month.252 #:253 #: This attribute can also be configured from the config with the237 #: `PERMANENT_SESSION_LIFETIME` configuration key. Defaults to254 #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to255 #: ``timedelta(days=31)``256 permanent_session_lifetime = ConfigAttribute('PERMANENT_SESSION_LIFETIME',257 get_converter=_make_timedelta)258259 #: A :class:`~datetime.timedelta` which is used as default cache_timeout260 #: for the :func:`send_file` functions. The default is 12 hours.261 #:262 #: This attribute can also be configured from the config with the263 #: ``SEND_FILE_MAX_AGE_DEFAULT`` configuration key. This configuration264 #: variable can also be set with an integer value used as seconds.265 #: Defaults to ``timedelta(hours=12)``266 send_file_max_age_default = ConfigAttribute('SEND_FILE_MAX_AGE_DEFAULT',267 get_converter=_make_timedelta)268269 #: Enable this if you want to use the X-Sendfile feature. Keep in270 #: mind that the server has to support this. This only affects files271 #: sent with the :func:`send_file` method.272 #:273 #: .. versionadded:: 0.2274 #:275 #: This attribute can also be configured from the config with the249 #: `USE_X_SENDFILE` configuration key. Defaults to `False`.276 #: ``USE_X_SENDFILE`` configuration key. Defaults to ``False``.277 use_x_sendfile = ConfigAttribute('USE_X_SENDFILE')278279 #: The name of the logger to use. By default the logger name is the280 #: package name passed to the constructor.281 #:282 #: .. versionadded:: 0.4283 logger_name = ConfigAttribute('LOGGER_NAME')284258 #: Enable the deprecated module support? This is active by default259 #: in 0.7 but will be changed to False in 0.8. With Flask 1.0 modules260 #: will be removed in favor of Blueprints261 enable_modules = True262263 #: The logging format used for the debug logger. This is only used when264 #: the application is in debug mode, otherwise the attached logging265 #: handler does the formatting.266 #:267 #: .. versionadded:: 0.3268 debug_log_format = (269 '-' * 80 + '\n' +270 '%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n' +271 '%(message)s\n' +272 '-' * 80273 )274285 #: The JSON encoder class to use. Defaults to :class:`~flask.json.JSONEncoder`.286 #:287 #: .. versionadded:: 0.10288 json_encoder = json.JSONEncoder
9 unmodified lines
298 )299300 #: Default configuration parameters.301 default_config = ImmutableDict({292 'DEBUG': False,302 'DEBUG': get_debug_flag(default=False),303 'TESTING': False,304 'PROPAGATE_EXCEPTIONS': None,305 'PRESERVE_CONTEXT_ON_EXCEPTION': None,306 'SECRET_KEY': None,307 'PERMANENT_SESSION_LIFETIME': timedelta(days=31),308 'USE_X_SENDFILE': False,309 'LOGGER_NAME': None,310 'LOGGER_HANDLER_POLICY': 'always',311 'SERVER_NAME': None,312 'APPLICATION_ROOT': None,313 'SESSION_COOKIE_NAME': 'session',314 'SESSION_COOKIE_DOMAIN': None,
1 unmodified line
316 'SESSION_COOKIE_HTTPONLY': True,317 'SESSION_COOKIE_SECURE': False,318 'SESSION_REFRESH_EACH_REQUEST': True,319 'MAX_CONTENT_LENGTH': None,309 'SEND_FILE_MAX_AGE_DEFAULT': 12 * 60 * 60, # 12 hours320 'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12),321 'TRAP_BAD_REQUEST_ERRORS': False,322 'TRAP_HTTP_EXCEPTIONS': False,323 'EXPLAIN_TEMPLATE_LOADING': False,324 'PREFERRED_URL_SCHEME': 'http',325 'JSON_AS_ASCII': True,326 'JSON_SORT_KEYS': True,315 'JSONIFY_PRETTYPRINT_REGULAR': True,316 'TEMPLATES_AUTO_RELOAD': True,327 'JSONIFY_PRETTYPRINT_REGULAR': False,328 'JSONIFY_MIMETYPE': 'application/json',329 'TEMPLATES_AUTO_RELOAD': None,330 })331332 #: The rule object to use for URL rules created. This is used by333 #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.
12 unmodified lines
346 #: .. versionadded:: 0.8347 session_interface = SecureCookieSessionInterface()348349 def __init__(self, import_name, static_path=None, static_url_path=None,337 static_folder='static', template_folder='templates',350 static_folder='static', static_host=None,351 host_matching=False, template_folder='templates',352 instance_path=None, instance_relative_config=False,353 root_path=None):354 _PackageBoundObject.__init__(self, import_name,355 template_folder=template_folder,
37 unmodified lines
393 # support for the now deprecated `error_handlers` attribute. The394 # :attr:`error_handler_spec` shall be used now.395 self._error_handlers = {}396383 #: A dictionary of all registered error handlers. The key is `None`397 #: A dictionary of all registered error handlers. The key is ``None``398 #: for error handlers active on the application, otherwise the key is399 #: the name of the blueprint. Each key points to another dictionary400 #: where the key is the status code of the http exception. The387 #: special key `None` points to a list of tuples where the first item401 #: special key ``None`` points to a list of tuples where the first item402 #: is the class for the instance check and the second the error handler403 #: function.404 #:391 #: To register a error handler, use the :meth:`errorhandler`405 #: To register an error handler, use the :meth:`errorhandler`406 #: decorator.407 self.error_handler_spec = {None: self._error_handlers}408409 #: A list of functions that are called when :meth:`url_for` raises a410 #: :exc:`~werkzeug.routing.BuildError`. Each function registered here411 #: is called with `error`, `endpoint` and `values`. If a function398 #: returns `None` or raises a `BuildError` the next function is412 #: returns ``None`` or raises a :exc:`BuildError` the next function is413 #: tried.414 #:415 #: .. versionadded:: 0.9416 self.url_build_error_handlers = []417404 #: A dictionary with lists of functions that should be called at the405 #: beginning of the request. The key of the dictionary is the name of406 #: the blueprint this function is active for, `None` for all requests.407 #: This can for example be used to open database connections or408 #: getting hold of the currently logged in user. To register a409 #: function here, use the :meth:`before_request` decorator.418 #: A dictionary with lists of functions that will be called at the419 #: beginning of each request. The key of the dictionary is the name of420 #: the blueprint this function is active for, or ``None`` for all421 #: requests. To register a function, use the :meth:`before_request`422 #: decorator.423 self.before_request_funcs = {}424412 #: A lists of functions that should be called at the beginning of the413 #: first request to this instance. To register a function here, use414 #: the :meth:`before_first_request` decorator.425 #: A list of functions that will be called at the beginning of the426 #: first request to this instance. To register a function, use the427 #: :meth:`before_first_request` decorator.428 #:429 #: .. versionadded:: 0.8430 self.before_first_request_funcs = []431432 #: A dictionary with lists of functions that should be called after433 #: each request. The key of the dictionary is the name of the blueprint421 #: this function is active for, `None` for all requests. This can for422 #: example be used to open database connections or getting hold of the423 #: currently logged in user. To register a function here, use the424 #: :meth:`after_request` decorator.434 #: this function is active for, ``None`` for all requests. This can for435 #: example be used to close database connections. To register a function436 #: here, use the :meth:`after_request` decorator.437 self.after_request_funcs = {}438439 #: A dictionary with lists of functions that are called after440 #: each request, even if an exception has occurred. The key of the441 #: dictionary is the name of the blueprint this function is active for,430 #: `None` for all requests. These functions are not allowed to modify442 #: ``None`` for all requests. These functions are not allowed to modify443 #: the request, and their return values are ignored. If an exception444 #: occurred while processing the request, it gets passed to each445 #: teardown_request function. To register a function here, use the446 #: :meth:`teardown_request` decorator.
8 unmodified lines
455 #:456 #: .. versionadded:: 0.9457 self.teardown_appcontext_funcs = []458447 #: A dictionary with lists of functions that can be used as URL448 #: value processor functions. Whenever a URL is built these functions449 #: are called to modify the dictionary of values in place. The key450 #: `None` here is used for application wide451 #: callbacks, otherwise the key is the name of the blueprint.452 #: Each of these functions has the chance to modify the dictionary459 #: A dictionary with lists of functions that are called before the460 #: :attr:`before_request_funcs` functions. The key of the dictionary is461 #: the name of the blueprint this function is active for, or ``None``462 #: for all requests. To register a function, use463 #: :meth:`url_value_preprocessor`.464 #:465 #: .. versionadded:: 0.7466 self.url_value_preprocessors = {}467468 #: A dictionary with lists of functions that can be used as URL value458 #: preprocessors. The key `None` here is used for application wide469 #: preprocessors. The key ``None`` here is used for application wide470 #: callbacks, otherwise the key is the name of the blueprint.471 #: Each of these functions has the chance to modify the dictionary472 #: of URL values before they are used as the keyword arguments of the473 #: view function. For each function registered this one should also
4 unmodified lines
478 self.url_default_functions = {}479480 #: A dictionary with list of functions that are called without argument481 #: to populate the template context. The key of the dictionary is the471 #: name of the blueprint this function is active for, `None` for all482 #: name of the blueprint this function is active for, ``None`` for all483 #: requests. Each returns a dictionary that the template context is484 #: updated with. To register a function here, use the485 #: :meth:`context_processor` decorator.486 self.template_context_processors = {487 None: [_default_template_ctx_processor]488 }489490 #: A list of shell context processor functions that should be run491 #: when a shell context is created.492 #:493 #: .. versionadded:: 0.11494 self.shell_context_processors = []495496 #: all the attached blueprints in a dictionary by name. Blueprints497 #: can be attached multiple times so this dictionary does not tell498 #: you how often they got attached.499 #:500 #: .. versionadded:: 0.7501 self.blueprints = {}502 self._blueprint_order = []503504 #: a place where extensions can store application specific state. For505 #: example this is where an extension could store database engines and506 #: similar things. For backwards compatibility extensions should register
19 unmodified lines
526 #: class ListConverter(BaseConverter):527 #: def to_python(self, value):528 #: return value.split(',')529 #: def to_url(self, values):512 #: return ','.join(BaseConverter.to_url(value)530 #: return ','.join(super(ListConverter, self).to_url(value)531 #: for value in values)532 #:533 #: app = Flask(__name__)534 #: app.url_map.converters['list'] = ListConverter535 self.url_map = Map()536537 self.url_map.host_matching = host_matching538539 # tracks internally if the application already handled at least one540 # request.541 self._got_first_request = False542 self._before_request_lock = Lock()543524 # register the static folder for the application. Do that even525 # if the folder does not exist. First of all it might be created526 # while the server is running (usually happens during development)527 # but also because google appengine stores static files somewhere528 # else when mapped with the .yml file.544 # Add a static route using the provided static_url_path, static_host,545 # and static_folder if there is a configured static_folder.546 # Note we do this without checking if static_folder exists.547 # For one, it might be created while the server is running (e.g. during548 # development). Also, Google App Engine stores static files somewhere549 if self.has_static_folder:550 assert bool(static_host) == host_matching, 'Invalid static_host/host_matching combination'551 self.add_url_rule(self.static_url_path + '/<path:filename>',531 endpoint='static',552 endpoint='static', host=static_host,553 view_func=self.send_static_file)554555 #: The click command line context for this application. Commands556 #: registered here show up in the :command:`flask` command once the557 #: application has been discovered. The default commands are558 #: provided by Flask itself and can be overridden.559 #:560 #: This is an instance of a :class:`click.Group` object.561 self.cli = cli.AppGroup(self.name)562563 def _get_error_handlers(self):564 from warnings import warn565 warn(DeprecationWarning('error_handlers is deprecated, use the '566 'new error_handler_spec attribute instead.'), stacklevel=1)
22 unmodified lines
589 return self.import_name590591 @property592 def propagate_exceptions(self):564 """Returns the value of the `PROPAGATE_EXCEPTIONS` configuration593 """Returns the value of the ``PROPAGATE_EXCEPTIONS`` configuration594 value in case it's set, otherwise a sensible default is returned.595596 .. versionadded:: 0.7597 """
3 unmodified lines
601 return self.testing or self.debug602603 @property604 def preserve_context_on_exception(self):576 """Returns the value of the `PRESERVE_CONTEXT_ON_EXCEPTION`605 """Returns the value of the ``PRESERVE_CONTEXT_ON_EXCEPTION``606 configuration value in case it's set, otherwise a sensible default607 is returned.608609 .. versionadded:: 0.7
31 unmodified lines
641 return self.create_jinja_environment()642643 @property644 def got_first_request(self):616 """This attribute is set to `True` if the application started645 """This attribute is set to ``True`` if the application started646 handling the first request.647648 .. versionadded:: 0.8649 """
44 unmodified lines
694 the Jinja2 globals and filters after initialization. Override695 this function to customize the behavior.696697 .. versionadded:: 0.5669 .. versionchanged:: 1.0698 .. versionchanged:: 0.11699 ``Environment.auto_reload`` set in accordance with700 ``TEMPLATES_AUTO_RELOAD`` configuration option.701 """702 options = dict(self.jinja_options)703 if 'autoescape' not in options:704 options['autoescape'] = self.select_jinja_autoescape705 if 'auto_reload' not in options:677 options['auto_reload'] = self.debug \678 or self.config['TEMPLATES_AUTO_RELOAD']679 rv = Environment(self, **options)706 if self.config['TEMPLATES_AUTO_RELOAD'] is not None:707 options['auto_reload'] = self.config['TEMPLATES_AUTO_RELOAD']708 else:709 options['auto_reload'] = self.debug710 rv = self.jinja_environment(self, **options)711 rv.globals.update(712 url_for=url_for,713 get_flashed_messages=get_flashed_messages,714 config=self.config,
29 unmodified lines
744 :meth:`create_jinja_environment` instead.745 """746747 def select_jinja_autoescape(self, filename):717 """Returns `True` if autoescaping should be active for the given718 template name.748 """Returns ``True`` if autoescaping should be active for the given749 template name. If no template name is given, returns `True`.750751 .. versionadded:: 0.5752 """753 if filename is None:723 return False754 return True755 return filename.endswith(('.html', '.htm', '.xml', '.xhtml'))756757 def update_template_context(self, context):758 """Update the template context with some commonly used variables.
19 unmodified lines
778 # easier add new variables in context processors without breaking779 # existing views.780 context.update(orig_ctx)781782 def make_shell_context(self):783 """Returns the shell context for an interactive shell for this784 application. This runs all the registered shell context785 processors.786787 .. versionadded:: 0.11788 """789 rv = {'app': self, 'g': g}790 for processor in self.shell_context_processors:791 rv.update(processor())792 return rv793794 def run(self, host=None, port=None, debug=None, **options):752 """Runs the application on a local development server. If the753 :attr:`debug` flag is set the server will automatically reload795 """Runs the application on a local development server.796797 Do not use ``run()`` in a production setting. It is not intended to798 meet security and performance requirements for a production server.799 Instead, see :ref:`deployment` for WSGI server recommendations.800801 If the :attr:`debug` flag is set the server will automatically reload802 for code changes and show a debugger in case an exception happened.803804 If you want to run the application in debug mode, but disable the805 code execution on the interactive debugger, you can pass806 ``use_evalex=False`` as parameter. This will keep the debugger's807 traceback screen active, but disable code execution.808809 It is not recommended to use this function for development with810 automatic reloading as this is badly supported. Instead you should811 be using the :command:`flask` command line script's ``run`` support.812813 .. admonition:: Keep in Mind814815 Flask will suppress any server error with a generic error page816 unless it is in debug mode. As such to enable just the817 interactive debugger without the code reloading, you have to818 invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.767 Setting ``use_debugger`` to `True` without being in debug mode819 Setting ``use_debugger`` to ``True`` without being in debug mode820 won't catch any exceptions because there won't be any to821 catch.822823 .. versionchanged:: 0.10824 The default port is now picked from the ``SERVER_NAME`` variable.825826 :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to827 have the server available externally as well. Defaults to776 ``'127.0.0.1'``.828 ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config829 variable if present.830 :param port: the port of the webserver. Defaults to ``5000`` or the831 port defined in the ``SERVER_NAME`` config variable if832 present.833 :param debug: if given, enable or disable debug mode.
2 unmodified lines
836 Werkzeug server. See837 :func:`werkzeug.serving.run_simple` for more838 information.839 """840 # Change this into a no-op if the server is invoked from the841 # command line. Have a look at cli.py for more information.842 if os.environ.get('FLASK_RUN_FROM_CLI_SERVER') == '1':843 from .debughelpers import explain_ignored_app_run844 explain_ignored_app_run()845 return846847 from werkzeug.serving import run_simple788 if host is None:789 host = '127.0.0.1'790 if port is None:791 server_name = self.config['SERVER_NAME']792 if server_name and ':' in server_name:793 port = int(server_name.rsplit(':', 1)[1])794 else:795 port = 5000848 _host = '127.0.0.1'849 _port = 5000850 server_name = self.config.get("SERVER_NAME")851 sn_host, sn_port = None, None852 if server_name:853 sn_host, _, sn_port = server_name.partition(':')854 host = host or sn_host or _host855 port = int(port or sn_port or _port)856 if debug is not None:857 self.debug = bool(debug)858 options.setdefault('use_reloader', self.debug)859 options.setdefault('use_debugger', self.debug)860 try:861 run_simple(host, port, self, **options)862 finally:863 # reset the first request information if the development server804 # resetted normally. This makes it possible to restart the server864 # reset normally. This makes it possible to restart the server865 # without reloader and that stuff from an interactive shell.866 self._got_first_request = False867808 def test_client(self, use_cookies=True):868 def test_client(self, use_cookies=True, **kwargs):869 """Creates a test client for this application. For information870 about unit testing head over to :ref:`testing`.871872 Note that if you are testing for assertions or exceptions in your
6 unmodified lines
879880 app.testing = True881 client = app.test_client()882823 The test client can be used in a `with` block to defer the closing down824 of the context until the end of the `with` block. This is useful if883 The test client can be used in a ``with`` block to defer the closing down884 of the context until the end of the ``with`` block. This is useful if885 you want to access the context locals for testing::886887 with app.test_client() as c:888 rv = c.get('/?vodka=42')889 assert request.args['vodka'] == '42'890891 Additionally, you may pass optional keyword arguments that will then892 be passed to the application's :attr:`test_client_class` constructor.893 For example::894895 from flask.testing import FlaskClient896897 class CustomClient(FlaskClient):898 def __init__(self, *args, **kwargs):899 self._authentication = kwargs.pop("authentication")900 super(CustomClient,self).__init__( *args, **kwargs)901902 app.test_client_class = CustomClient903 client = app.test_client(authentication='Basic ....')904905 See :class:`~flask.testing.FlaskClient` for more information.906907 .. versionchanged:: 0.4834 added support for `with` block usage for the client.908 added support for ``with`` block usage for the client.909910 .. versionadded:: 0.7911 The `use_cookies` parameter was added as well as the ability912 to override the client to be used by setting the913 :attr:`test_client_class` attribute.914915 .. versionchanged:: 0.11916 Added `**kwargs` to support passing additional keyword arguments to917 the constructor of :attr:`test_client_class`.918 """919 cls = self.test_client_class920 if cls is None:921 from flask.testing import FlaskClient as cls844 return cls(self, self.response_class, use_cookies=use_cookies)922 return cls(self, self.response_class, use_cookies=use_cookies, **kwargs)923924 def open_session(self, request):925 """Creates or opens a new session. Default implementation stores all926 session data in a signed cookie. This requires that the
23 unmodified lines
950 .. versionadded:: 0.7951 """952 return self.session_interface.make_null_session(self)953876 def register_module(self, module, **options):877 """Registers a module with this application. The keyword arguments878 of this function are the same as the ones for the constructor of the879 :class:`Module` class and will override the values of the module if880 provided.881882 .. versionchanged:: 0.7883 The module system was deprecated in favor for the blueprint884 system.885 """886 assert blueprint_is_module(module), 'register_module requires ' \887 'actual module objects. Please upgrade to blueprints though.'888 if not self.enable_modules:889 raise RuntimeError('Module support was disabled but code '890 'attempted to register a module named %r' % module)891 else:892 from warnings import warn893 warn(DeprecationWarning('Modules are deprecated. Upgrade to '894 'using blueprints. Have a look into the documentation for '895 'more information. If this module was registered by a '896 'Flask-Extension upgrade the extension or contact the author '897 'of that extension instead. (Registered %r)' % module),898 stacklevel=2)899900 self.register_blueprint(module, **options)901954 @setupmethod955 def register_blueprint(self, blueprint, **options):956 """Registers a blueprint on the application.957
7 unmodified lines
965 'are created on the fly need unique names.' % \966 (blueprint, self.blueprints[blueprint.name], blueprint.name)967 else:968 self.blueprints[blueprint.name] = blueprint969 self._blueprint_order.append(blueprint)970 first_registration = True971 blueprint.register(self, options, first_registration)972973 def iter_blueprints(self):974 """Iterates over all blueprints by the order they were registered.975976 .. versionadded:: 0.11977 """978 return iter(self._blueprint_order)979980 @setupmethod921 def add_url_rule(self, rule, endpoint=None, view_func=None, **options):981 def add_url_rule(self, rule, endpoint=None, view_func=None, provide_automatic_options=None, **options):982 """Connects a URL rule. Works exactly like the :meth:`route`983 decorator. If a view_func is provided it will be registered with the984 endpoint.985
23 unmodified lines
1009 .. versionchanged:: 0.21010 `view_func` parameter added.10111012 .. versionchanged:: 0.6953 `OPTIONS` is added automatically as method.1013 ``OPTIONS`` is added automatically as method.10141015 :param rule: the URL rule as string1016 :param endpoint: the endpoint for the registered URL rule. Flask1017 itself assumes the name of the view function as1018 endpoint1019 :param view_func: the function to call when serving a request to the1020 provided endpoint1021 :param provide_automatic_options: controls whether the ``OPTIONS``1022 method should be added automatically. This can also be controlled1023 by setting the ``view_func.provide_automatic_options = False``1024 before adding the rule.1025 :param options: the options to be forwarded to the underlying1026 :class:`~werkzeug.routing.Rule` object. A change1027 to Werkzeug is handling of method options. methods1028 is a list of methods this rule should be limited965 to (`GET`, `POST` etc.). By default a rule966 just listens for `GET` (and implicitly `HEAD`).967 Starting with Flask 0.6, `OPTIONS` is implicitly1029 to (``GET``, ``POST`` etc.). By default a rule1030 just listens for ``GET`` (and implicitly ``HEAD``).1031 Starting with Flask 0.6, ``OPTIONS`` is implicitly1032 added and handled by the standard request handling.1033 """1034 if endpoint is None:1035 endpoint = _endpoint_from_view_func(view_func)
1 unmodified line
1037 methods = options.pop('methods', None)10381039 # if the methods are not given and the view_func object knows its1040 # methods we can use that instead. If neither exists, we go with977 # a tuple of only `GET` as default.1041 # a tuple of only ``GET`` as default.1042 if methods is None:1043 methods = getattr(view_func, 'methods', None) or ('GET',)1044 if isinstance(methods, string_types):1045 raise TypeError('Allowed methods have to be iterables of strings, '1046 'for example: @app.route(..., methods=["POST"])')983 methods = set(methods)1047 methods = set(item.upper() for item in methods)10481049 # Methods that should always be added1050 required_methods = set(getattr(view_func, 'required_methods', ()))10511052 # starting with Flask 0.8 the view_func object can disable and1053 # force-enable the automatic options handling.1054 if provide_automatic_options is None:990 provide_automatic_options = getattr(view_func,991 'provide_automatic_options', None)1055 provide_automatic_options = getattr(view_func,1056 'provide_automatic_options', None)10571058 if provide_automatic_options is None:1059 if 'OPTIONS' not in methods:1060 provide_automatic_options = True
33 unmodified lines
1094 :param options: the options to be forwarded to the underlying1095 :class:`~werkzeug.routing.Rule` object. A change1096 to Werkzeug is handling of method options. methods1097 is a list of methods this rule should be limited1033 to (`GET`, `POST` etc.). By default a rule1034 just listens for `GET` (and implicitly `HEAD`).1035 Starting with Flask 0.6, `OPTIONS` is implicitly1098 to (``GET``, ``POST`` etc.). By default a rule1099 just listens for ``GET`` (and implicitly ``HEAD``).1100 Starting with Flask 0.6, ``OPTIONS`` is implicitly1101 added and handled by the standard request handling.1102 """1103 def decorator(f):1104 endpoint = options.pop('endpoint', None)
16 unmodified lines
1121 self.view_functions[endpoint] = f1122 return f1123 return decorator11241125 @staticmethod1126 def _get_exc_class_and_code(exc_class_or_code):1127 """Ensure that we register only exceptions as handler keys"""1128 if isinstance(exc_class_or_code, integer_types):1129 exc_class = default_exceptions[exc_class_or_code]1130 else:1131 exc_class = exc_class_or_code11321133 assert issubclass(exc_class, Exception)11341135 if issubclass(exc_class, HTTPException):1136 return exc_class, exc_class.code1137 else:1138 return exc_class, None11391140 @setupmethod1141 def errorhandler(self, code_or_exception):1062 """A decorator that is used to register a function give a given1142 """A decorator that is used to register a function given an1143 error code. Example::11441145 @app.errorhandler(404)1146 def page_not_found(error):
16 unmodified lines
1163 Setting error handlers via assignments to :attr:`error_handler_spec`1164 however is discouraged as it requires fiddling with nested dictionaries1165 and the special case for arbitrary exception types.11661087 The first `None` refers to the active blueprint. If the error1088 handler should be application wide `None` shall be used.1167 The first ``None`` refers to the active blueprint. If the error1168 handler should be application wide ``None`` shall be used.11691170 .. versionadded:: 0.71171 Use :meth:`register_error_handler` instead of modifying1172 :attr:`error_handler_spec` directly, for application wide error1173 handlers.1094 11741175 .. versionadded:: 0.71176 One can now additionally also register custom exception types1177 that do not necessarily have to be a subclass of the1178 :class:`~werkzeug.exceptions.HTTPException` class.11791100 :param code: the code as integer for the handler1180 :param code_or_exception: the code as integer for the handler, or1181 an arbitrary exception1182 """1183 def decorator(f):1184 self._register_error_handler(None, code_or_exception, f)1185 return f
9 unmodified lines
1195 self._register_error_handler(None, code_or_exception, f)11961197 @setupmethod1198 def _register_error_handler(self, key, code_or_exception, f):1118 if isinstance(code_or_exception, HTTPException):1119 code_or_exception = code_or_exception.code1120 if isinstance(code_or_exception, integer_types):1121 assert code_or_exception != 500 or key is None, \1122 'It is currently not possible to register a 500 internal ' \1123 'server error on a per-blueprint level.'1124 self.error_handler_spec.setdefault(key, {})[code_or_exception] = f1125 else:1126 self.error_handler_spec.setdefault(key, {}).setdefault(None, []) \1127 .append((code_or_exception, f))1199 """1200 :type key: None|str1201 :type code_or_exception: int|T<=Exception1202 :type f: callable1203 """1204 if isinstance(code_or_exception, HTTPException): # old broken behavior1205 raise ValueError(1206 'Tried to register a handler for an exception instance {0!r}. '1207 'Handlers can only be registered for exception classes or HTTP error codes.'1208 .format(code_or_exception))12091210 exc_class, code = self._get_exc_class_and_code(code_or_exception)12111212 handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})1213 handlers[exc_class] = f12141215 @setupmethod1216 def template_filter(self, name=None):1217 """A decorator that is used to register custom template filter.1218 You can specify a name for the filter, otherwise the function
91 unmodified lines
1310 self.jinja_env.globals[name or f.__name__] = f13111312 @setupmethod1313 def before_request(self, f):1228 """Registers a function to run before each request."""1314 """Registers a function to run before each request.1315 1316 For example, this can be used to open a database connection, or to load1317 the logged in user from the session.13181319 The function will be called without any arguments. If it returns a1320 non-None value, the value is handled as if it was the return value from1321 the view, and further request handling is stopped.1322 """1323 self.before_request_funcs.setdefault(None, []).append(f)1324 return f13251326 @setupmethod1327 def before_first_request(self, f):1328 """Registers a function to be run before the first request to this1329 instance of the application.13301331 The function will be called without any arguments and its return1332 value is ignored.13331334 .. versionadded:: 0.81335 """1336 self.before_first_request_funcs.append(f)1337 return f
35 unmodified lines
1373 that they will fail. If they do execute code that might fail they1374 will have to surround the execution of these code by try/except1375 statements and log occurring errors.13761280 When a teardown function was called because of a exception it will1377 When a teardown function was called because of an exception it will1378 be passed an error object.13791380 The return values of teardown functions are ignored.13811382 .. admonition:: Debug Note13831384 In debug mode Flask will not tear down a request on an exception1286 immediately. Instead if will keep it alive so that the interactive1385 immediately. Instead it will keep it alive so that the interactive1386 debugger can still access it. This behavior can be controlled1387 by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.1388 """1389 self.teardown_request_funcs.setdefault(None, []).append(f)
22 unmodified lines
14121413 When a teardown function was called because of an exception it will1414 be passed an error object.14151416 The return values of teardown functions are ignored.14171418 .. versionadded:: 0.91419 """1420 self.teardown_appcontext_funcs.append(f)1421 return f
4 unmodified lines
1426 self.template_context_processors[None].append(f)1427 return f14281429 @setupmethod1430 def shell_context_processor(self, f):1431 """Registers a shell context processor function.14321433 .. versionadded:: 0.111434 """1435 self.shell_context_processors.append(f)1436 return f14371438 @setupmethod1439 def url_value_preprocessor(self, f):1330 """Registers a function as URL value preprocessor for all view1331 functions of the application. It's called before the view functions1332 are called and can modify the url values provided.1440 """Register a URL value preprocessor function for all view1441 functions in the application. These functions will be called before the1442 :meth:`before_request` functions.1443 1444 The function can modify the values captured from the matched url before1445 they are passed to the view. For example, this can be used to pop a1446 common language code value and place it in ``g`` rather than pass it to1447 every view.1448 1449 The function is passed the endpoint name and values dict. The return1450 value is ignored.1451 """1452 self.url_value_preprocessors.setdefault(None, []).append(f)1453 return f1454
5 unmodified lines
1460 """1461 self.url_default_functions.setdefault(None, []).append(f)1462 return f14631464 def _find_error_handler(self, e):1465 """Finds a registered error handler for the request’s blueprint.1466 Otherwise falls back to the app, returns None if not a suitable1467 handler is found.1468 """1469 exc_class, code = self._get_exc_class_and_code(type(e))14701471 def find_handler(handler_map):1472 if not handler_map:1473 return1474 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 handler14801481 # try blueprint handlers1482 handler = find_handler(self.error_handler_spec1483 .get(request.blueprint, {})1484 .get(code))1485 if handler is not None:1486 return handler14871488 # fall back to app handlers1489 return find_handler(self.error_handler_spec[None].get(code))14901491 def handle_http_exception(self, e):1492 """Handles an HTTP exception. By default this will invoke the1493 registered error handlers and fall back to returning the1494 exception as response.14951496 .. versionadded:: 0.31497 """1353 handlers = self.error_handler_spec.get(request.blueprint)1498 # Proxy exceptions don't have error codes. We want to always return1499 # those unchanged as errors1500 if e.code is None:1501 return e1358 if handlers and e.code in handlers:1359 handler = handlers[e.code]1360 else:1361 handler = self.error_handler_spec[None].get(e.code)15021503 handler = self._find_error_handler(e)1504 if handler is None:1505 return e1506 return handler(e)15071508 def trap_http_exception(self, e):1509 """Checks if an HTTP exception should be trapped or not. By default1368 this will return `False` for all exceptions except for a bad request1369 key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to `True`. It1370 also returns `True` if ``TRAP_HTTP_EXCEPTIONS`` is set to `True`.1510 this will return ``False`` for all exceptions except for a bad request1511 key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It1512 also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.15131514 This is called for all HTTP exceptions raised by a view function.1373 If it returns `True` for any exception the error handler for this1515 If it returns ``True`` for any exception the error handler for this1516 exception is not called and it shows up as regular exception in the1517 traceback. This is helpful for debugging implicitly raised HTTP1518 exceptions.1519
21 unmodified lines
1541 # ensure not to trash sys.exc_info() at that point in case someone1542 # wants the traceback preserved in handle_http_exception. Of course1543 # we cannot prevent users from trashing it themselves in a custom1544 # trap_http_exception method so that's their fault then.15451546 if isinstance(e, HTTPException) and not self.trap_http_exception(e):1547 return self.handle_http_exception(e)15481406 blueprint_handlers = ()1407 handlers = self.error_handler_spec.get(request.blueprint)1408 if handlers is not None:1409 blueprint_handlers = handlers.get(None, ())1410 app_handlers = self.error_handler_spec[None].get(None, ())1411 for typecheck, handler in chain(blueprint_handlers, app_handlers):1412 if isinstance(e, typecheck):1413 return handler(e)1549 handler = self._find_error_handler(e)15501551 if handler is None:1415 reraise(exc_type, exc_value, tb)1552 reraise(exc_type, exc_value, tb)1553 return handler(e)15541555 def handle_exception(self, e):1556 """Default exception handling that kicks in when an exception1557 occurs that is not caught. In debug mode the exception will
5 unmodified lines
1563 """1564 exc_type, exc_value, tb = sys.exc_info()15651566 got_request_exception.send(self, exception=e)1429 handler = self.error_handler_spec[None].get(500)1567 handler = self._find_error_handler(InternalServerError())15681569 if self.propagate_exceptions:1570 # if we want to repropagate the exception, we can attempt to1571 # raise it with the whole traceback in case we can do that
6 unmodified lines
15781579 self.log_exception((exc_type, exc_value, tb))1580 if handler is None:1581 return InternalServerError()1444 return handler(e)1582 return self.finalize_request(handler(e), from_error_handler=True)15831584 def log_exception(self, exc_info):1585 """Logs an exception. This is called by :meth:`handle_exception`1586 if debugging is disabled and right before the handler is called.
59 unmodified lines
1646 if rv is None:1647 rv = self.dispatch_request()1648 except Exception as e:1649 rv = self.handle_user_exception(e)1650 return self.finalize_request(rv)16511652 def finalize_request(self, rv, from_error_handler=False):1653 """Given the return value from a view function this finalizes1654 the request by converting it into a response and invoking the1655 postprocessing functions. This is invoked for both normal1656 request dispatching as well as error handlers.16571658 Because this means that it might be called as a result of a1659 failure a special safe mode is available which can be enabled1660 with the `from_error_handler` flag. If enabled, failures in1661 response processing will be logged and otherwise ignored.16621663 :internal:1664 """1665 response = self.make_response(rv)1666 try:1513 response = self.process_response(response)1514 request_finished.send(self, response=response)1667 response = self.process_response(response)1668 request_finished.send(self, response=response)1669 except Exception:1670 if not from_error_handler:1671 raise1672 self.logger.exception('Request finalizing failed with an '1673 'error while handling an error')1674 return response16751676 def try_trigger_before_first_request_functions(self):1677 """Called before each request and will ensure that it triggers
11 unmodified lines
1689 func()1690 self._got_first_request = True16911692 def make_default_options_response(self):1534 """This method is called to create the default `OPTIONS` response.1693 """This method is called to create the default ``OPTIONS`` response.1694 This can be changed through subclassing to change the default1536 behavior of `OPTIONS` responses.1695 behavior of ``OPTIONS`` responses.16961697 .. versionadded:: 0.71698 """1699 adapter = _request_ctx_stack.top.url_adapter
14 unmodified lines
17141715 def should_ignore_error(self, error):1716 """This is called to figure out if an error should be ignored1717 or not as far as the teardown system is concerned. If this1559 function returns `True` then the teardown handlers will not be1718 function returns ``True`` then the teardown handlers will not be1719 passed the error.17201721 .. versionadded:: 0.101722 """1723 return False17241725 def make_response(self, rv):1567 """Converts the return value from a view function to a real1568 response object that is an instance of :attr:`response_class`.1726 """Convert the return value from a view function to an instance of1727 :attr:`response_class`.17281570 The following types are allowed for `rv`:1729 :param rv: the return value from the view function. The view function1730 must return a response. Returning ``None``, or the view ending1731 without returning, is not allowed. The following types are allowed1732 for ``view_rv``:17331572 .. tabularcolumns:: |p{3.5cm}|p{9.5cm}|1734 ``str`` (``unicode`` in Python 2)1735 A response object is created with the string encoded to UTF-81736 as the body.1737 1738 ``bytes`` (``str`` in Python 2)1739 A response object is created with the bytes as the body.1740 1741 ``tuple``1742 Either ``(body, status, headers)``, ``(body, status)``, or1743 ``(body, headers)``, where ``body`` is any of the other types1744 allowed here, ``status`` is a string or an integer, and1745 ``headers`` is a dictionary or a list of ``(key, value)``1746 tuples. If ``body`` is a :attr:`response_class` instance,1747 ``status`` overwrites the exiting value and ``headers`` are1748 extended.1749 1750 :attr:`response_class`1751 The object is returned unchanged.1752 1753 other :class:`~werkzeug.wrappers.Response` class1754 The object is coerced to :attr:`response_class`.1755 1756 :func:`callable`1757 The function is called as a WSGI application. The result is1758 used to create a response object.17591574 ======================= ===========================================1575 :attr:`response_class` the object is returned unchanged1576 :class:`str` a response object is created with the1577 string as body1578 :class:`unicode` a response object is created with the1579 string encoded to utf-8 as body1580 a WSGI function the function is called as WSGI application1581 and buffered as response object1582 :class:`tuple` A tuple in the form ``(response, status,1583 headers)`` or ``(response, headers)``1584 where `response` is any of the1585 types defined here, `status` is a string1586 or an integer and `headers` is a list or1587 a dictionary with header values.1588 ======================= ===========================================15891590 :param rv: the return value from the view function15911760 .. versionchanged:: 0.91761 Previously a tuple was interpreted as the arguments for the1762 response object.1763 """1596 status_or_headers = headers = None1597 if isinstance(rv, tuple):1598 rv, status_or_headers, headers = rv + (None,) * (3 - len(rv))17641600 if rv is None:1601 raise ValueError('View function did not return a response')1765 status = headers = None17661603 if isinstance(status_or_headers, (dict, list)):1604 headers, status_or_headers = status_or_headers, None1767 # unpack tuple returns1768 if isinstance(rv, (tuple, list)):1769 len_rv = len(rv)17701771 # a 3-tuple is unpacked directly1772 if len_rv == 3:1773 rv, status, headers = rv1774 # decide if a 2-tuple has status or headers1775 elif len_rv == 2:1776 if isinstance(rv[1], (Headers, dict, tuple, list)):1777 rv, headers = rv1778 else:1779 rv, status = rv1780 # other sized tuples are not allowed1781 else:1782 raise TypeError(1783 'The view function did not return a valid response tuple.'1784 ' The tuple must have the form (body, status, headers),'1785 ' (body, status), or (body, headers).'1786 )17871788 # the body must not be None1789 if rv is None:1790 raise TypeError(1791 'The view function did not return a valid response. The'1792 ' function either returned None or ended without a return'1793 ' statement.'1794 )17951796 # make sure the body is an instance of the response class1797 if not isinstance(rv, self.response_class):1607 # When we create a response object directly, we let the constructor1608 # set the headers and status. We do this because there can be1609 # some extra logic involved when creating these objects with1610 # specific values (like default content type selection).1798 if isinstance(rv, (text_type, bytes, bytearray)):1612 rv = self.response_class(rv, headers=headers, status=status_or_headers)1613 headers = status_or_headers = None1799 # let the response class set the status and headers instead of1800 # waiting to do it manually, so that the class can handle any1801 # special logic1802 rv = self.response_class(rv, status=status, headers=headers)1803 status = headers = None1804 else:1805 # evaluate a WSGI callable, or coerce a different response1806 # class to the correct type1807 try:1615 rv = self.response_class.force_type(rv, request.environ)1808 rv = self.response_class.force_type(rv, request.environ)1809 except TypeError as e:1810 new_error = TypeError(1811 '{e}\nThe view function did not return a valid'1812 ' response. The return type must be a string, tuple,'1813 ' Response instance, or WSGI callable, but it was a'1814 ' {rv.__class__.__name__}.'.format(e=e, rv=rv)1815 )1816 reraise(TypeError, new_error, sys.exc_info()[2])18171818 # prefer the status if it was provided1617 if status_or_headers is not None:1618 if isinstance(status_or_headers, string_types):1619 rv.status = status_or_headers1819 if status is not None:1820 if isinstance(status, (text_type, bytes, bytearray)):1821 rv.status = status1822 else:1621 rv.status_code = status_or_headers1823 rv.status_code = status18241825 # extend existing headers with provided headers1826 if headers:1827 rv.headers.extend(headers)18281829 return rv183016271831 def create_url_adapter(self, request):1832 """Creates a URL adapter for the given request. The URL adapter1833 is created at a point where the request context is not yet set up1834 so the request is passed explicitly.
37 unmodified lines
1872 try:1873 rv = handler(error, endpoint, values)1874 if rv is not None:1875 return rv1673 except BuildError as error:1674 pass1876 except BuildError as e:1877 # make error available outside except block (py3)1878 error = e18791880 # At this point we want to reraise the exception. If the error is1881 # still the same one we can reraise it with the original traceback,1882 # otherwise we raise it from here.
1 unmodified line
1884 reraise(exc_type, exc_value, tb)1885 raise error18861887 def preprocess_request(self):1684 """Called before the actual request dispatching and will1685 call every as :meth:`before_request` decorated function.1686 If any of these function returns a value it's handled as1687 if it was the return value from the view and further1688 request handling is stopped.16891690 This also triggers the :meth:`url_value_processor` functions before1691 the actual :meth:`before_request` functions are called.1888 """Called before the request is dispatched. Calls1889 :attr:`url_value_preprocessors` registered with the app and the1890 current blueprint (if any). Then calls :attr:`before_request_funcs`1891 registered with the app and the blueprint.1892 1893 If any :meth:`before_request` handler returns a non-None value, the1894 value is handled as if it was the return value from the view, and1895 further request handling is stopped.1896 """18971898 bp = _request_ctx_stack.top.request.blueprint18991900 funcs = self.url_value_preprocessors.get(None, ())1901 if bp is not None and bp in self.url_value_preprocessors:
34 unmodified lines
1936 if not self.session_interface.is_null_session(ctx.session):1937 self.save_session(ctx.session, response)1938 return response19391735 def do_teardown_request(self, exc=None):1940 def do_teardown_request(self, exc=_sentinel):1941 """Called after the actual request dispatching and will1942 call every as :meth:`teardown_request` decorated function. This is1943 not actually called by the :class:`Flask` object itself but is always1944 triggered when the request context is popped. That way we have a
2 unmodified lines
1947 .. versionchanged:: 0.91948 Added the `exc` argument. Previously this was always using the1949 current exception information.1950 """1746 if exc is None:1951 if exc is _sentinel:1952 exc = sys.exc_info()[1]1953 funcs = reversed(self.teardown_request_funcs.get(None, ()))1954 bp = _request_ctx_stack.top.request.blueprint1955 if bp is not None and bp in self.teardown_request_funcs:
1 unmodified line
1957 for func in funcs:1958 func(exc)1959 request_tearing_down.send(self, exc=exc)19601756 def do_teardown_appcontext(self, exc=None):1961 def do_teardown_appcontext(self, exc=_sentinel):1962 """Called when an application context is popped. This works pretty1963 much the same as :meth:`do_teardown_request` but for the application1964 context.19651966 .. versionadded:: 0.91967 """1763 if exc is None:1968 if exc is _sentinel:1969 exc = sys.exc_info()[1]1970 for func in reversed(self.teardown_appcontext_funcs):1971 func(exc)1972 appcontext_tearing_down.send(self, exc=exc)
15 unmodified lines
19881989 def request_context(self, environ):1990 """Creates a :class:`~flask.ctx.RequestContext` from the given1991 environment and binds it to the current context. This must be used in1787 combination with the `with` statement because the request is only bound1788 to the current context for the duration of the `with` block.1992 combination with the ``with`` statement because the request is only bound1993 to the current context for the duration of the ``with`` block.19941995 Example usage::19961997 with app.request_context(environ):1998 do_something_with(request)19991795 The object returned can also be used without the `with` statement2000 The object returned can also be used without the ``with`` statement2001 which is useful for working in the shell. The example above is2002 doing exactly the same as this code::20032004 ctx = app.request_context(environ)
3 unmodified lines
2008 finally:2009 ctx.pop()20102011 .. versionchanged:: 0.31807 Added support for non-with statement usage and `with` statement2012 Added support for non-with statement usage and ``with`` statement2013 is now passed the ctx object.20142015 :param environ: a WSGI environment2016 """
36 unmodified lines
2053 a list of headers and an optional2054 exception context to start the response2055 """2056 ctx = self.request_context(environ)1852 ctx.push()2057 error = None2058 try:2059 try:2060 ctx.push()2061 response = self.full_dispatch_request()2062 except Exception as e:2063 error = e1859 response = self.make_response(self.handle_exception(e))2064 response = self.handle_exception(e)2065 except:2066 error = sys.exc_info()[1]2067 raise2068 return response(environ, start_response)2069 finally:2070 if self.should_ignore_error(error):2071 error = None2072 ctx.auto_pop(error)20731866 @property1867 def modules(self):1868 from warnings import warn1869 warn(DeprecationWarning('Flask.modules is deprecated, use '1870 'Flask.blueprints instead'), stacklevel=2)1871 return self.blueprints18722074 def __call__(self, environ, start_response):2075 """Shortcut for :attr:`wsgi_app`."""2076 return self.wsgi_app(environ, start_response)2077
5 unmodified lines
modified:flask/blueprints.py+9 added-3 removed
4 unmodified lines
56 Blueprints are the recommended way to implement larger or more7 pluggable applications in Flask 0.7 and later.89 :copyright: (c) 2014 by Armin Ronacher.9 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""12from functools import update_wrapper13
27 unmodified lines
41 subdomain = self.options.get('subdomain')42 if subdomain is None:43 subdomain = self.blueprint.subdomain4445 #: The subdomain that the blueprint should be active for, `None`45 #: The subdomain that the blueprint should be active for, ``None``46 #: otherwise.47 self.subdomain = subdomain4849 url_prefix = self.options.get('url_prefix')
38 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
306 unmodified lines
added:flask/cli.py+580 added
1# -*- coding: utf-8 -*-2"""3 flask.cli4 ~~~~~~~~~56 A simple command line application to run flask apps.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import os13import sys14import 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_flag252627class NoAppException(click.UsageError):28 """Raised if an application cannot be found or loaded."""293031def find_best_app(module):32 """Given a module instance this tries to find the best possible33 application in the module or raises an exception.34 """35 from . import Flask3637 # Search for the most common names first.38 for attr_name in 'app', 'application':39 app = getattr(module, attr_name, None)40 if app is not None and isinstance(app, Flask):41 return app4243 # Otherwise find the only object that is a Flask instance.44 matches = [v for k, v in iteritems(module.__dict__)45 if isinstance(v, Flask)]4647 if len(matches) == 1:48 return matches[0]49 raise NoAppException('Failed to find application in module "%s". Are '50 'you sure it contains a Flask application? Maybe '51 'you wrapped it in a WSGI middleware or you are '52 'using a factory function.' % module.__name__)535455def prepare_exec_for_file(filename):56 """Given a filename this will try to calculate the python path, add it57 to the search path and return the actual module name that is expected.58 """59 module = []6061 # Chop off file extensions or package markers62 if os.path.split(filename)[1] == '__init__.py':63 filename = os.path.dirname(filename)64 elif filename.endswith('.py'):65 filename = filename[:-3]66 else:67 raise NoAppException('The file provided (%s) does exist but is not a '68 'valid Python file. This means that it cannot '69 'be used as application. Please change the '70 'extension to .py' % filename)71 filename = os.path.realpath(filename)7273 dirpath = filename74 while 1:75 dirpath, extra = os.path.split(dirpath)76 module.append(extra)77 if not os.path.isfile(os.path.join(dirpath, '__init__.py')):78 break7980 sys.path.insert(0, dirpath)81 return '.'.join(module[::-1])828384def locate_app(app_id):85 """Attempts to locate the application."""86 __traceback_hide__ = True87 if ':' in app_id:88 module, app_obj = app_id.split(':', 1)89 else:90 module = app_id91 app_obj = None9293 try:94 __import__(module)95 except ImportError:96 # Reraise the ImportError if it occurred within the imported module.97 # Determine this by checking whether the trace has a depth > 1.98 if sys.exc_info()[-1].tb_next:99 stack_trace = traceback.format_exc()100 raise NoAppException('There was an error trying to import'101 ' the app (%s):\n%s' % (module, stack_trace))102 else:103 raise NoAppException('The file/path provided (%s) does not appear'104 ' to exist. Please verify the path is '105 'correct. If app is not on PYTHONPATH, '106 'ensure the extension is .py' % module)107108 mod = sys.modules[module]109 if app_obj is None:110 app = find_best_app(mod)111 else:112 app = getattr(mod, app_obj, None)113 if app is None:114 raise RuntimeError('Failed to find application in module "%s"'115 % module)116117 return app118119120def find_default_import_path():121 app = os.environ.get('FLASK_APP')122 if app is None:123 return124 if os.path.isfile(app):125 return prepare_exec_for_file(app)126 return app127128129def get_version(ctx, param, value):130 if not value or ctx.resilient_parsing:131 return132 message = 'Flask %(version)s\nPython %(python_version)s'133 click.echo(message % {134 'version': __version__,135 'python_version': sys.version,136 }, color=ctx.color)137 ctx.exit()138139version_option = click.Option(['--version'],140 help='Show the flask version',141 expose_value=False,142 callback=get_version,143 is_flag=True, is_eager=True)144145class DispatchingApp(object):146 """Special application that dispatches to a Flask application which147 is imported by name in a background thread. If an error happens148 it is recorded and shown as part of the WSGI handling which in case149 of the Werkzeug debugger means that it shows up in the browser.150 """151152 def __init__(self, loader, use_eager_loading=False):153 self.loader = loader154 self._app = None155 self._lock = Lock()156 self._bg_loading_exc_info = None157 if use_eager_loading:158 self._load_unlocked()159 else:160 self._load_in_background()161162 def _load_in_background(self):163 def _load_app():164 __traceback_hide__ = True165 with self._lock:166 try:167 self._load_unlocked()168 except Exception:169 self._bg_loading_exc_info = sys.exc_info()170 t = Thread(target=_load_app, args=())171 t.start()172173 def _flush_bg_loading_exception(self):174 __traceback_hide__ = True175 exc_info = self._bg_loading_exc_info176 if exc_info is not None:177 self._bg_loading_exc_info = None178 reraise(*exc_info)179180 def _load_unlocked(self):181 __traceback_hide__ = True182 self._app = rv = self.loader()183 self._bg_loading_exc_info = None184 return rv185186 def __call__(self, environ, start_response):187 __traceback_hide__ = True188 if self._app is not None:189 return self._app(environ, start_response)190 self._flush_bg_loading_exception()191 with self._lock:192 if self._app is not None:193 rv = self._app194 else:195 rv = self._load_unlocked()196 return rv(environ, start_response)197198199class ScriptInfo(object):200 """Help object to deal with Flask applications. This is usually not201 necessary to interface with as it's used internally in the dispatching202 to click. In future versions of Flask this object will most likely play203 a bigger role. Typically it's created automatically by the204 :class:`FlaskGroup` but you can also manually create it and pass it205 onwards as click object.206 """207208 def __init__(self, app_import_path=None, create_app=None):209 if create_app is None:210 if app_import_path is None:211 app_import_path = find_default_import_path()212 self.app_import_path = app_import_path213 else:214 app_import_path = None215216 #: Optionally the import path for the Flask application.217 self.app_import_path = app_import_path218 #: Optionally a function that is passed the script info to create219 #: the instance of the application.220 self.create_app = create_app221 #: A dictionary with arbitrary data that can be associated with222 #: this script info.223 self.data = {}224 self._loaded_app = None225226 def load_app(self):227 """Loads the Flask app (if not yet loaded) and returns it. Calling228 this multiple times will just result in the already loaded app to229 be returned.230 """231 __traceback_hide__ = True232 if self._loaded_app is not None:233 return self._loaded_app234 if self.create_app is not None:235 rv = self.create_app(self)236 else:237 if not self.app_import_path:238 raise NoAppException(239 'Could not locate Flask application. You did not provide '240 'the FLASK_APP environment variable.\n\nFor more '241 'information see '242 'http://flask.pocoo.org/docs/latest/quickstart/')243 rv = locate_app(self.app_import_path)244 debug = get_debug_flag()245 if debug is not None:246 rv.debug = debug247 self._loaded_app = rv248 return rv249250251pass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True)252253254def with_appcontext(f):255 """Wraps a callback so that it's guaranteed to be executed with the256 script's application context. If callbacks are registered directly257 to the ``app.cli`` object then they are wrapped with this function258 by default unless it's disabled.259 """260 @click.pass_context261 def decorator(__ctx, *args, **kwargs):262 with __ctx.ensure_object(ScriptInfo).load_app().app_context():263 return __ctx.invoke(f, *args, **kwargs)264 return update_wrapper(decorator, f)265266267class AppGroup(click.Group):268 """This works similar to a regular click :class:`~click.Group` but it269 changes the behavior of the :meth:`command` decorator so that it270 automatically wraps the functions in :func:`with_appcontext`.271272 Not to be confused with :class:`FlaskGroup`.273 """274275 def command(self, *args, **kwargs):276 """This works exactly like the method of the same name on a regular277 :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`278 unless it's disabled by passing ``with_appcontext=False``.279 """280 wrap_for_ctx = kwargs.pop('with_appcontext', True)281 def decorator(f):282 if wrap_for_ctx:283 f = with_appcontext(f)284 return click.Group.command(self, *args, **kwargs)(f)285 return decorator286287 def group(self, *args, **kwargs):288 """This works exactly like the method of the same name on a regular289 :class:`click.Group` but it defaults the group class to290 :class:`AppGroup`.291 """292 kwargs.setdefault('cls', AppGroup)293 return click.Group.group(self, *args, **kwargs)294295296class FlaskGroup(AppGroup):297 """Special subclass of the :class:`AppGroup` group that supports298 loading more commands from the configured Flask app. Normally a299 developer does not have to interface with this class but there are300 some very advanced use cases for which it makes sense to create an301 instance of this.302303 For information as of why this is useful see :ref:`custom-scripts`.304305 :param add_default_commands: if this is True then the default run and306 shell commands wil be added.307 :param add_version_option: adds the ``--version`` option.308 :param create_app: an optional callback that is passed the script info309 and returns the loaded app.310 """311312 def __init__(self, add_default_commands=True, create_app=None,313 add_version_option=True, **extra):314 params = list(extra.pop('params', None) or ())315316 if add_version_option:317 params.append(version_option)318319 AppGroup.__init__(self, params=params, **extra)320 self.create_app = create_app321322 if add_default_commands:323 self.add_command(run_command)324 self.add_command(shell_command)325 self.add_command(routes_command)326327 self._loaded_plugin_commands = False328329 def _load_plugin_commands(self):330 if self._loaded_plugin_commands:331 return332 try:333 import pkg_resources334 except ImportError:335 self._loaded_plugin_commands = True336 return337338 for ep in pkg_resources.iter_entry_points('flask.commands'):339 self.add_command(ep.load(), ep.name)340 self._loaded_plugin_commands = True341342 def get_command(self, ctx, name):343 self._load_plugin_commands()344345 # We load built-in commands first as these should always be the346 # same no matter what the app does. If the app does want to347 # override this it needs to make a custom instance of this group348 # and not attach the default commands.349 #350 # This also means that the script stays functional in case the351 # application completely fails.352 rv = AppGroup.get_command(self, ctx, name)353 if rv is not None:354 return rv355356 info = ctx.ensure_object(ScriptInfo)357 try:358 rv = info.load_app().cli.get_command(ctx, name)359 if rv is not None:360 return rv361 except NoAppException:362 pass363364 def list_commands(self, ctx):365 self._load_plugin_commands()366367 # The commands available is the list of both the application (if368 # available) plus the builtin commands.369 rv = set(click.Group.list_commands(self, ctx))370 info = ctx.ensure_object(ScriptInfo)371 try:372 rv.update(info.load_app().cli.list_commands(ctx))373 except Exception:374 # Here we intentionally swallow all exceptions as we don't375 # want the help page to break if the app does not exist.376 # If someone attempts to use the command we try to create377 # the app again and this will give us the error.378 # However, we will not do so silently because that would confuse379 # users.380 traceback.print_exc()381 return sorted(rv)382383 def main(self, *args, **kwargs):384 obj = kwargs.get('obj')385 if obj is None:386 obj = ScriptInfo(create_app=self.create_app)387 kwargs['obj'] = obj388 kwargs.setdefault('auto_envvar_prefix', 'FLASK')389 return AppGroup.main(self, *args, **kwargs)390391392@click.command('run', short_help='Runs a development server.')393@click.option('--host', '-h', default='127.0.0.1',394 help='The interface to bind to.')395@click.option('--port', '-p', default=5000,396 help='The port to bind to.')397@click.option('--reload/--no-reload', default=None,398 help='Enable or disable the reloader. By default the reloader '399 'is active if debug is enabled.')400@click.option('--debugger/--no-debugger', default=None,401 help='Enable or disable the debugger. By default the debugger '402 'is active if debug is enabled.')403@click.option('--eager-loading/--lazy-loader', default=None,404 help='Enable or disable eager loading. By default eager '405 'loading is enabled if the reloader is disabled.')406@click.option('--with-threads/--without-threads', default=False,407 help='Enable or disable multithreading.')408@pass_script_info409def run_command(info, host, port, reload, debugger, eager_loading,410 with_threads):411 """Runs a local development server for the Flask application.412413 This local server is recommended for development purposes only but it414 can also be used for simple intranet deployments. By default it will415 not support any sort of concurrency at all to simplify debugging. This416 can be changed with the --with-threads option which will enable basic417 multithreading.418419 The reloader and debugger are by default enabled if the debug flag of420 Flask is enabled and disabled otherwise.421 """422 from werkzeug.serving import run_simple423424 # Set a global flag that indicates that we were invoked from the425 # command line interface provided server command. This is detected426 # by Flask.run to make the call into a no-op. This is necessary to427 # avoid ugly errors when the script that is loaded here also attempts428 # to start a server.429 os.environ['FLASK_RUN_FROM_CLI_SERVER'] = '1'430431 debug = get_debug_flag()432 if reload is None:433 reload = bool(debug)434 if debugger is None:435 debugger = bool(debug)436 if eager_loading is None:437 eager_loading = not reload438439 app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)440441 # Extra startup messages. This depends a bit on Werkzeug internals to442 # not double execute when the reloader kicks in.443 if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':444 # If we have an import path we can print it out now which can help445 # people understand what's being served. If we do not have an446 # import path because the app was loaded through a callback then447 # we won't print anything.448 if info.app_import_path is not None:449 print(' * Serving Flask app "%s"' % info.app_import_path)450 if debug is not None:451 print(' * Forcing debug mode %s' % (debug and 'on' or 'off'))452453 run_simple(host, port, app, use_reloader=reload,454 use_debugger=debugger, threaded=with_threads)455456457@click.command('shell', short_help='Runs a shell in the app context.')458@with_appcontext459def shell_command():460 """Runs an interactive Python shell in the context of a given461 Flask application. The application will populate the default462 namespace of this shell according to it's configuration.463464 This is useful for executing small snippets of management code465 without having to manually configuring the application.466 """467 import code468 from flask.globals import _app_ctx_stack469 app = _app_ctx_stack.top.app470 banner = 'Python %s on %s\nApp: %s%s\nInstance: %s' % (471 sys.version,472 sys.platform,473 app.import_name,474 app.debug and ' [debug]' or '',475 app.instance_path,476 )477 ctx = {}478479 # Support the regular Python interpreter startup script if someone480 # is using it.481 startup = os.environ.get('PYTHONSTARTUP')482 if startup and os.path.isfile(startup):483 with open(startup, 'r') as f:484 eval(compile(f.read(), startup, 'exec'), ctx)485486 ctx.update(app.make_shell_context())487488 code.interact(banner=banner, local=ctx)489490491@click.command('routes', short_help='Show the routes for the app.')492@click.option(493 '--sort', '-s',494 type=click.Choice(('endpoint', 'methods', 'rule', 'match')),495 default='endpoint',496 help=(497 'Method to sort routes by. "match" is the order that Flask will match '498 'routes when dispatching a request.'499 )500)501@click.option(502 '--all-methods',503 is_flag=True,504 help="Show HEAD and OPTIONS methods."505)506@with_appcontext507def routes_command(sort, all_methods):508 """Show all registered routes with endpoints and methods."""509510 rules = list(current_app.url_map.iter_rules())511 ignored_methods = set(() if all_methods else ('HEAD', 'OPTIONS'))512513 if sort in ('endpoint', 'rule'):514 rules = sorted(rules, key=attrgetter(sort))515 elif sort == 'methods':516 rules = sorted(rules, key=lambda rule: sorted(rule.methods))517518 rule_methods = [519 ', '.join(sorted(rule.methods - ignored_methods)) for rule in rules520 ]521522 headers = ('Endpoint', 'Methods', 'Rule')523 widths = (524 max(len(rule.endpoint) for rule in rules),525 max(len(methods) for methods in rule_methods),526 max(len(rule.rule) for rule in rules),527 )528 widths = [max(len(h), w) for h, w in zip(headers, widths)]529 row = '{{0:<{0}}} {{1:<{1}}} {{2:<{2}}}'.format(*widths)530531 click.echo(row.format(*headers).strip())532 click.echo(row.format(*('-' * width for width in widths)))533534 for rule, methods in zip(rules, rule_methods):535 click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())536537538cli = FlaskGroup(help="""\539This shell command acts as general utility script for Flask applications.540541It loads the application configured (through the FLASK_APP environment542variable) and then provides commands either provided by the application or543Flask itself.544545The most useful commands are the "run" and "shell" command.546547Example usage:548549\b550 %(prefix)s%(cmd)s FLASK_APP=hello.py551 %(prefix)s%(cmd)s FLASK_DEBUG=1552 %(prefix)sflask run553""" % {554 'cmd': os.name == 'posix' and 'export' or 'set',555 'prefix': os.name == 'posix' and '$ ' or '',556})557558559def main(as_module=False):560 this_module = __package__ + '.cli'561 args = sys.argv[1:]562563 if as_module:564 if sys.version_info >= (2, 7):565 name = 'python -m ' + this_module.rsplit('.', 1)[0]566 else:567 name = 'python -m ' + this_module568569 # This module is always executed as "python -m flask.run" and as such570 # we need to ensure that we restore the actual command line so that571 # the reloader can properly operate.572 sys.argv = ['-m', this_module] + sys.argv[1:]573 else:574 name = None575576 cli.main(args=args, prog_name=name)577578579if __name__ == '__main__':580 main(as_module=True)
modified:flask/config.py+51 added-21 removed
3 unmodified lines
4 ~~~~~~~~~~~~56 Implements the configuration related objects.78 :copyright: (c) 2014 by Armin Ronacher.8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import imp12import os13import types14import errno1516from werkzeug.utils import import_string17from ._compat import string_types, iteritems
74 unmodified lines
9293 app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])9495 :param variable_name: name of the environment variable96 :param silent: set to `True` if you want silent failure for missing96 :param silent: set to ``True`` if you want silent failure for missing97 files.98 :return: bool. `True` if able to load config, `False` otherwise.98 :return: bool. ``True`` if able to load config, ``False`` otherwise.99 """100 rv = os.environ.get(variable_name)101 if not rv:102 if silent:
12 unmodified lines
115116 :param filename: the filename of the config. This can either be an117 absolute filename or a filename relative to the118 root path.119 :param silent: set to `True` if you want silent failure for missing119 :param silent: set to ``True`` if you want silent failure for missing120 files.121122 .. versionadded:: 0.7123 `silent` parameter.124 """125 filename = os.path.join(self.root_path, filename)126 d = imp.new_module('config')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)
2 unmodified lines
171 self[key] = getattr(obj, key)172173 def from_json(self, filename, silent=False):174 """Updates the values in the config from a JSON file. This function170 behaves as if the JSON object was a dictionary and passed ot the171 :meth:`from_object` function.175 behaves as if the JSON object was a dictionary and passed to the176 :meth:`from_mapping` function.177178 :param filename: the filename of the JSON file. This can either be an179 absolute filename or a filename relative to the180 root path.176 :param silent: set to `True` if you want silent failure for missing181 :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:
3 unmodified lines
192 if silent and e.errno in (errno.ENOENT, errno.EISDIR):193 return False194 e.strerror = 'Unable to load configuration file (%s)' % e.strerror195 raise196 return self.from_mapping(obj)197198 def from_mapping(self, *mapping, **kwargs):199 """Updates the config like :meth:`update` ignoring items with non-upper200 keys.201202 .. versionadded:: 0.11203 """204 mappings = []205 if len(mapping) == 1:206 if hasattr(mapping[0], 'items'):207 mappings.append(mapping[0].items())208 else:209 mappings.append(mapping[0])210 elif len(mapping) > 1:211 raise TypeError(212 'expected at most 1 positional argument, got %d' % len(mapping)213 )214 mappings.append(kwargs.items())215 for mapping in mappings:191 for key in obj.keys():192 if key.isupper():193 self[key] = obj[key]216 for (key, value) in mapping:217 if key.isupper():218 self[key] = value219 return True220196 def get_namespace(self, namespace, lowercase=True):221 def get_namespace(self, namespace, lowercase=True, trim_namespace=True):222 """Returns a dictionary containing a subset of configuration options223 that match the specified namespace/prefix. Example usage::224225 app.config['IMAGE_STORE_TYPE'] = 'fs'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_')229205 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',
5 unmodified lines
240241 :param namespace: a configuration namespace242 :param lowercase: a flag indicating if the keys of the resulting243 dictionary should be lowercase244 :param trim_namespace: a flag indicating if the keys of the resulting245 dictionary should not include the namespace246220 .. versionadded:: 1.0247 .. versionadded:: 0.11248 """249 rv = {}250 for k, v in iteritems(self):251 if not k.startswith(namespace):252 continue253 if trim_namespace:226 key = k[len(namespace):]254 key = k[len(namespace):]255 else:256 key = k257 if lowercase:258 key = key.lower()259 rv[key] = v260 return rv
3 unmodified lines
modified:flask/ctx.py+56 added-52 removed
3 unmodified lines
4 ~~~~~~~~~56 Implements the objects required to keep the context.78 :copyright: (c) 2014 by Armin Ronacher.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 HTTPException1617from .globals import _request_ctx_stack, _app_ctx_stack20from .module import blueprint_is_module18from .signals import appcontext_pushed, appcontext_popped19from ._compat import BROKEN_PYPY_CTXMGR_EXIT, reraise202122# a singleton sentinel value for parameter defaults23_sentinel = object()242526class _AppCtxGlobals(object):27 """A plain object."""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):
133 unmodified lines
178 sys.exc_clear()179 _app_ctx_stack.push(self)180 appcontext_pushed.send(self.app)181172 def pop(self, exc=None):182 def pop(self, exc=_sentinel):183 """Pops the app context."""184 try:174 self._refcnt -= 1175 if self._refcnt <= 0:176 if exc is None:177 exc = sys.exc_info()[1]178 self.app.do_teardown_appcontext(exc)179 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
25 unmodified lines
221 The request context is automatically popped at the end of the request222 for you. In debug mode the request context is kept around if223 exceptions happen so that interactive debuggers have a chance to224 introspect the data. With 0.4 this can also be forced for requests213 that did not fail and outside of `DEBUG` mode. By setting214 ``'flask._preserve_context'`` to `True` on the WSGI environment the225 that did not fail and outside of ``DEBUG`` mode. By setting226 ``'flask._preserve_context'`` to ``True`` on the WSGI environment the227 context will not pop itself at the end of the request. This is used by228 the :meth:`~flask.Flask.test_client` for example to implement the229 deferred cleanup functionality.230
32 unmodified lines
263 self._after_request_functions = []264265 self.match_request()266255 # XXX: Support for deprecated functionality. This is going away with256 # Flask 1.0257 blueprint = self.request.blueprint258 if blueprint is not None:259 # better safe than sorry, we don't want to break code that260 # already worked261 bp = app.blueprints.get(blueprint)262 if bp is not None and blueprint_is_module(bp):263 self.request._is_old_module = True264267 def _get_g(self):268 return _app_ctx_stack.top.g269 def _set_g(self, value):270 _app_ctx_stack.top.g = value
32 unmodified lines
303 # on the stack. The rationale is that you want to access that304 # information under debug situations. However if someone forgets to305 # pop that context again we want to make sure that on the next push306 # it's invalidated, otherwise we run at risk that something leaks305 # memory. This is usually only a problem in testsuite since this307 # memory. This is usually only a problem in test suite since this308 # functionality is not active in production environments.309 top = _request_ctx_stack.top310 if top is not None and top.preserved:311 top.pop(top._preserved_exc)
20 unmodified lines
332 self.session = self.app.open_session(self.request)333 if self.session is None:334 self.session = self.app.make_null_session()335334 def pop(self, exc=None):336 def pop(self, exc=_sentinel):337 """Pops the request context and unbinds it by doing that. This will338 also trigger the execution of functions registered by the339 :meth:`~flask.Flask.teardown_request` decorator.340
1 unmodified line
342 Added the `exc` argument.343 """344 app_ctx = self._implicit_app_ctx_stack.pop()345346 try:344 clear_request = False345 if not self._implicit_app_ctx_stack:346 self.preserved = False347 self._preserved_exc = None348 if exc is None:349 exc = sys.exc_info()[1]350 self.app.do_teardown_request(exc)347 clear_request = False348 if not self._implicit_app_ctx_stack:349 self.preserved = False350 self._preserved_exc = None351 if exc is _sentinel:352 exc = sys.exc_info()[1]353 self.app.do_teardown_request(exc)354352 # If this interpreter supports clearing the exception information353 # we do that now. This will only go into effect on Python 2.x,354 # on 3.x it disappears automatically at the end of the exception355 # stack.356 if hasattr(sys, 'exc_clear'):357 sys.exc_clear()355 # If this interpreter supports clearing the exception information356 # we do that now. This will only go into effect on Python 2.x,357 # on 3.x it disappears automatically at the end of the exception358 # stack.359 if hasattr(sys, 'exc_clear'):360 sys.exc_clear()361359 request_close = getattr(self.request, 'close', None)360 if request_close is not None:361 request_close()362 clear_request = True362 request_close = getattr(self.request, 'close', None)363 if request_close is not None:364 request_close()365 clear_request = True366 finally:367 rv = _request_ctx_stack.pop()368364 rv = _request_ctx_stack.pop()365 assert rv is self, 'Popped wrong request context. (%r instead of %r)' \366 % (rv, self)369 # get rid of circular dependencies at the end of the request370 # so that we don't require the GC to be active.371 if clear_request:372 rv.request.environ['werkzeug.request'] = None373368 # get rid of circular dependencies at the end of the request369 # so that we don't require the GC to be active.370 if clear_request:371 rv.request.environ['werkzeug.request'] = None374 # Get rid of the app as well if necessary.375 if app_ctx is not None:376 app_ctx.pop(exc)377373 # Get rid of the app as well if necessary.374 if app_ctx is not None:375 app_ctx.pop(exc)378 assert rv is self, 'Popped wrong request context. ' \379 '(%r instead of %r)' % (rv, self)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+82 added-2 removed
3 unmodified lines
4 ~~~~~~~~~~~~~~~~~~56 Various helpers to make the development experience better.78 :copyright: (c) 2014 by Armin Ronacher.8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from ._compat import implements_to_string11import os12from warnings import warn1314from ._compat import implements_to_string, text_type15from .app import Flask16from .blueprints import Blueprint17from .globals import _request_ctx_stack181920class UnexpectedUnicodeError(AssertionError, UnicodeError):21 """Raised in places where we want some better error reporting for22 unexpected unicode or binary data.23 """
66 unmodified lines
90 raise DebugFilesKeyError(request, key)91 newcls.__name__ = oldcls.__name__92 newcls.__module__ = oldcls.__module__93 request.files.__class__ = newcls949596def _dump_loader_info(loader):97 yield 'class: %s.%s' % (type(loader).__module__, type(loader).__name__)98 for key, value in sorted(loader.__dict__.items()):99 if key.startswith('_'):100 continue101 if isinstance(value, (tuple, list)):102 if not all(isinstance(x, (str, text_type)) for x in value):103 continue104 yield '%s:' % key105 for item in value:106 yield ' - %s' % item107 continue108 elif not isinstance(value, (str, text_type, int, float, bool)):109 continue110 yield '%s: %r' % (key, value)111112113def explain_template_loading_attempts(app, template, attempts):114 """This should help developers understand what failed"""115 info = ['Locating template "%s":' % template]116 total_found = 0117 blueprint = None118 reqctx = _request_ctx_stack.top119 if reqctx is not None and reqctx.request.blueprint is not None:120 blueprint = reqctx.request.blueprint121122 for idx, (loader, srcobj, triple) in enumerate(attempts):123 if isinstance(srcobj, Flask):124 src_info = 'application "%s"' % srcobj.import_name125 elif isinstance(srcobj, Blueprint):126 src_info = 'blueprint "%s" (%s)' % (srcobj.name,127 srcobj.import_name)128 else:129 src_info = repr(srcobj)130131 info.append('% 5d: trying loader of %s' % (132 idx + 1, src_info))133134 for line in _dump_loader_info(loader):135 info.append(' %s' % line)136137 if triple is None:138 detail = 'no match'139 else:140 detail = 'found (%r)' % (triple[1] or '<string>')141 total_found += 1142 info.append(' -> %s' % detail)143144 seems_fishy = False145 if total_found == 0:146 info.append('Error: the template could not be found.')147 seems_fishy = True148 elif total_found > 1:149 info.append('Warning: multiple loaders returned a match for the template.')150 seems_fishy = True151152 if blueprint is not None and seems_fishy:153 info.append(' The template was looked up from an endpoint that '154 'belongs to the blueprint "%s".' % blueprint)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+26 added-3 removed
14 unmodified lines
15 everybody involved.1617 This is used by `flask.ext`.1819 :copyright: (c) 2014 by Armin Ronacher.19 :copyright: (c) 2015 by Armin Ronacher.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/globals.py+21 added-4 removed
4 unmodified lines
56 Defines all the global objects that are proxies to the current7 active context.89 :copyright: (c) 2014 by Armin Ronacher.9 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213from functools import partial14from werkzeug.local import LocalStack, LocalProxy151617_request_ctx_err_msg = '''\18Working outside of request context.1920This typically means that you attempted to use functionality that needed21an active HTTP request. Consult the documentation on testing for22information about how to avoid this problem.\23'''24_app_ctx_err_msg = '''\25Working outside of application context.2627This typically means that you attempted to use functionality that needed28to interface with the current application object in a way. To solve29this set up an application context with app.app_context(). See the30documentation for more information.\31'''323334def _lookup_req_object(name):35 top = _request_ctx_stack.top36 if top is None:20 raise RuntimeError('working outside of request context')37 raise RuntimeError(_request_ctx_err_msg)38 return getattr(top, name)394041def _lookup_app_object(name):42 top = _app_ctx_stack.top43 if top is None:27 raise RuntimeError('working outside of application context')44 raise RuntimeError(_app_ctx_err_msg)45 return getattr(top, name)464748def _find_app():49 top = _app_ctx_stack.top50 if top is None:34 raise RuntimeError('working outside of application context')51 raise RuntimeError(_app_ctx_err_msg)52 return top.app535455# context locals
6 unmodified lines
modified:flask/helpers.py+218 added-111 removed
3 unmodified lines
4 ~~~~~~~~~~~~~56 Implements various helpers.78 :copyright: (c) 2014 by Armin Ronacher.8 :copyright: (c) 2015 by Armin Ronacher.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():
79 unmodified lines
197 """Generates a URL to the given endpoint with the method provided.198199 Variable arguments that are unknown to the target endpoint are appended200 to the generated URL as query arguments. If the value of a query argument191 is `None`, the whole pair is skipped. In case blueprints are active201 is ``None``, the whole pair is skipped. In case blueprints are active202 you can shortcut references to the same blueprint by prefixing the203 local endpoint with a dot (``.``).204205 This will reference the index function local to the current blueprint::
6 unmodified lines
212 errors through :attr:`Flask.url_build_error_handlers`. The `url_for`213 function results in a :exc:`~werkzeug.routing.BuildError` when the current214 app does not have a URL for the given endpoint and values. When it does, the215 :data:`~flask.current_app` calls its :attr:`~Flask.url_build_error_handlers` if206 it is not `None`, which can return a string to use as the result of216 it is not ``None``, which can return a string to use as the result of217 `url_for` (instead of `url_for`'s default to raise the218 :exc:`~werkzeug.routing.BuildError` exception) or re-raise the exception.219 An example::220
32 unmodified lines
253 :exc:`~werkzeug.routing.BuildError`.254255 :param endpoint: the endpoint of the URL (name of the function)256 :param values: the variable arguments of the URL rule247 :param _external: if set to `True`, an absolute URL is generated. Server248 address can be changed via `SERVER_NAME` configuration variable which257 :param _external: if set to ``True``, an absolute URL is generated. Server258 address can be changed via ``SERVER_NAME`` configuration variable which259 defaults to `localhost`.260 :param _scheme: a string specifying the desired URL scheme. The `_external`251 parameter must be set to `True` or a `ValueError` is raised.261 parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default262 behavior uses the same scheme as the current request, or263 ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no264 request context is available. As of Werkzeug 0.10, this also can be set265 to an empty string to build protocol-relative URLs.266 :param _anchor: if provided this is added as anchor to the URL.267 :param _method: if provided this explicitly specifies an HTTP method.268 """269 appctx = _app_ctx_stack.top
3 unmodified lines
273 'application context being pushed. This has to be '274 'executed when application context is available.')275276 # If request specific information is available we have some extra263 # features that support "relative" urls.277 # features that support "relative" URLs.278 if reqctx is not None:279 url_adapter = reqctx.url_adapter280 blueprint_name = request.blueprint281 if not reqctx.request._is_old_module:
11 unmodified lines
293 endpoint = endpoint[1:]294 external = values.pop('_external', False)295296 # Otherwise go with the url adapter from the appctx and make283 # the urls external by default.297 # the URLs external by default.298 else:299 url_adapter = appctx.url_adapter300 if url_adapter is None:301 raise RuntimeError('Application was not able to create a URL '
6 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:304 rv = url_adapter.build(endpoint, values, method=method,305 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)
2 unmodified lines
342343def get_template_attribute(template_name, attribute):344 """Loads a macro (or variable) a template exports. This can be used to345 invoke a macro from within Python code. If you for example have a322 template named `_cider.html` with the following contents:346 template named :file:`_cider.html` with the following contents:347348 .. sourcecode:: html+jinja349350 {% macro hello(name) %}Hello {{ name }}!{% endmacro %}
44 unmodified lines
395def get_flashed_messages(with_categories=False, category_filter=[]):396 """Pulls all flashed messages from the session and returns them.397 Further calls in the same request to the function will return398 the same messages. By default just the messages are returned,375 but when `with_categories` is set to `True`, the return value will399 but when `with_categories` is set to ``True``, the return value will400 be a list of tuples in the form ``(category, message)`` instead.401402 Filter the flashed messages to one or more categories by providing those403 categories in `category_filter`. This allows rendering categories in404 separate html blocks. The `with_categories` and `category_filter`405 arguments are distinct:406407 * `with_categories` controls whether categories are returned with message384 text (`True` gives a tuple, where `False` gives just the message text).408 text (``True`` gives a tuple, where ``False`` gives just the message text).409 * `category_filter` filters the messages down to only those matching the410 provided categories.411412 See :ref:`message-flashing-pattern` for examples.
3 unmodified lines
416417 .. versionchanged:: 0.9418 `category_filter` parameter added.419396 :param with_categories: set to `True` to also receive categories.420 :param with_categories: set to ``True`` to also receive categories.421 :param category_filter: whitelist of categories to limit return values422 """423 flashes = _request_ctx_stack.top.flashes424 if flashes is None:
7 unmodified lines
432433434def send_file(filename_or_fp, mimetype=None, as_attachment=False,435 attachment_filename=None, add_etags=True,412 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` attribute417 to ``True`` to directly emit an `X-Sendfile` header. This however418 requires support of the underlying webserver for `X-Sendfile`.441 to ``True`` to directly emit an ``X-Sendfile`` header. This however442 requires support of the underlying webserver for ``X-Sendfile``.443444 By default it will try to guess the mimetype for you, but you can445 also explicitly provide one. For extra security you probably want446 to send certain files as attachment (HTML for instance). The mimetype447 guessing requires a `filename` or an `attachment_filename` to be448 provided.449426 Please never pass filenames to this function from user sources without427 checking them first. Something like this is usually sufficient to428 avoid security problems::450 ETags will also be attached automatically if a `filename` is provided. You451 can turn this off by setting `add_etags=False`.452430 if '..' in filename or filename.startswith('/'):431 abort(404)453 If `conditional=True` and `filename` is provided, this method will try to454 upgrade the response stream to support range requests. This will allow455 the request to be answered with partial content response.456457 Please never pass filenames to this function from user sources;458 you should use :func:`send_from_directory` instead.459460 .. versionadded:: 0.2461462 .. versionadded:: 0.5463 The `add_etags`, `cache_timeout` and `conditional` parameters were
7 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.458 :param as_attachment: set to `True` if you want to send this file with475 .. 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.462 :param add_etags: set to `False` to disable attaching of etags.463 :param conditional: set to `True` to enable conditional responses.504 :param add_etags: set to ``False`` to disable attaching of etags.505 :param conditional: set to ``True`` to enable conditional responses.506465 :param cache_timeout: the timeout in seconds for the headers. When `None`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 as the529 # 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>')631 def wiki_page(filename):632 filename = safe_join(app.config['WIKI_FOLDER'], filename)633 with open(filename, 'rb') as fd:572 content = fd.read() # Read and process the file content...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.
6 unmodified lines
671 filename, as_attachment=True)672673 .. admonition:: Sending files and Performance674604 It is strongly recommended to activate either `X-Sendfile` support in675 It is strongly recommended to activate either ``X-Sendfile`` support in676 your webserver or (if no authentication happens) to tell the webserver677 to serve files for the given path on its own without calling into the678 web application for improved performance.679
7 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
35 unmodified lines
735 'module "%s". This can happen because the '736 'module came from an import hook that does '737 'not provide file name information or because '738 'it\'s a namespace package. In this case '665 'the root path needs to be explictly '739 'the root path needs to be explicitly '740 'provided.' % import_name)741742 # filepath is import_name.py for a module, or __init__.py for a package.743 return os.path.dirname(os.path.abspath(filepath))
51 unmodified lines
795 __import__(import_name)796 filename = sys.modules[import_name].__file__797 package_path = os.path.abspath(os.path.dirname(filename))798725 # In case the root module is a pcakage we need to chop of the799 # In case the root module is a package we need to chop of the800 # rightmost part. This needs to go through a helper function801 # because of python 3.3 namespace packages.802 if _matching_loader_thinks_module_is_package(803 loader, root_mod_name):
49 unmodified lines
853 #: The name of the package or module. Do not change this once854 #: it was set by the constructor.855 self.import_name = import_name856783 #: location of the templates. `None` if templates should not be857 #: location of the templates. ``None`` if templates should not be858 #: exposed.859 self.template_folder = template_folder860861 if root_path is None:
9 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):805 if self._static_url_path is None:806 if self.static_folder is None:807 return None881 if self._static_url_path is not None:882 return self._static_url_path883 if self.static_folder is not None:884 return '/' + os.path.basename(self.static_folder)809 return self._static_url_path885 def _set_static_url_path(self, value):886 self._static_url_path = value887 static_url_path = property(_get_static_url_path, _set_static_url_path)888 del _get_static_url_path, _set_static_url_path889890 @property891 def has_static_folder(self):817 """This is `True` if the package bound object's container has a818 folder named ``'static'``.892 """This is ``True`` if the package bound object's container has a893 folder for static files.894895 .. versionadded:: 0.5896 """897 return self.static_folder is not None
15 unmodified lines
913 the configuration of :data:`~flask.current_app`.914915 Static file functions such as :func:`send_from_directory` use this916 function, and :func:`send_file` calls this function on842 :data:`~flask.current_app` when the given cache_timeout is `None`. If a917 :data:`~flask.current_app` when the given cache_timeout is ``None``. If a918 cache_timeout is given in :func:`send_file`, that timeout is used;919 otherwise, this method is called.920921 This allows subclasses to change the behavior when sending files based
7 unmodified lines
929 return flask.Flask.get_send_file_max_age(self, name)930931 .. versionadded:: 0.9932 """858 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.
19 unmodified lines
957 /templates958 /layout.html959 /index.html960886 If you want to open the `schema.sql` file you would do the961 If you want to open the :file:`schema.sql` file you would do the962 following::963964 with app.open_resource('schema.sql') as f:965 contents = f.read()
5 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 False
modified:flask/json.py+65 added-28 removed
1# -*- coding: utf-8 -*-2"""3 flask.jsonimpl4 ~~~~~~~~~~~~~~3 flask.json4 ~~~~~~~~~~56 Implementation helpers for the JSON support in Flask.78 :copyright: (c) 2014 by Armin Ronacher.8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import io12import uuid13from datetime import datetime13from datetime import date14from .globals import current_app, request15from ._compat import text_type, PY21617from werkzeug.http import http_date18from 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.
29 unmodified lines
5657 def default(self, o):58 """Implement this method in a subclass such that it returns a59 serializable object for ``o``, or calls the base implementation (to63 raise a ``TypeError``).60 raise a :exc:`TypeError`).6162 For example, to support arbitrary iterators, you could implement63 default like this::64
5 unmodified lines
70 else:71 return list(iterable)72 return JSONEncoder.default(self, o)73 """77 if isinstance(o, datetime):78 return http_date(o)74 if isinstance(o, date):75 return http_date(o.timetuple())76 if isinstance(o, uuid.UUID):77 return str(o)78 if hasattr(o, '__html__'):79 return text_type(o.__html__())
1 unmodified line
818283class JSONDecoder(_json.JSONDecoder):84 """The default JSON decoder. This one does not change the behavior from88 the default simplejson encoder. Consult the :mod:`json` documentation85 the default simplejson decoder. Consult the :mod:`json` documentation86 for more information. This decoder is not only used for the load87 functions of this module but also :attr:`~flask.Request`.88 """899091def _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 `application/json` mimetype. The arguments204 to this function are the same as to the :class:`dict` 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 }245224 For security reasons only objects are supported toplevel. For more225 information about this, have a look at :ref:`json-security`.246227 This function's response will be pretty printed if it was not requested228 with ``X-Requested-With: XMLHttpRequest`` to simplify debugging unless229 the ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to false.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 = None234 if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] \235 and not request.is_xhr:260 separators = (',', ':')261262 if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug:263 indent = 2237 return current_app.response_class(dumps(dict(*args, **kwargs),238 indent=indent),239 mimetype='application/json')264 separators = (', ', ': ')265266 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+60 added-11 removed
3 unmodified lines
4 ~~~~~~~~~~~~~56 Implements the logging support for Flask.78 :copyright: (c) 2014 by Armin Ronacher.8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112from __future__ import absolute_import1314from logging import getLogger, StreamHandler, Formatter, getLoggerClass, DEBUG14import sys1516from werkzeug.local import LocalProxy17from logging import getLogger, StreamHandler, Formatter, getLoggerClass, \18 DEBUG, ERROR19from .globals import _request_ctx_stack202122PROD_LOG_FORMAT = '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'23DEBUG_LOG_FORMAT = (24 '-' * 80 + '\n' +25 '%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n' +26 '%(message)s\n' +27 '-' * 8028)293031@LocalProxy32def _proxy_stream():33 """Finds the most appropriate error stream for the application. If a34 WSGI request is in flight we log to wsgi.errors, otherwise this resolves35 to sys.stderr.36 """37 ctx = _request_ctx_stack.top38 if ctx is not None:39 return ctx.request.environ['wsgi.errors']40 return sys.stderr414243def _should_log_for(app, mode):44 policy = app.config['LOGGER_HANDLER_POLICY']45 if policy == mode or policy == 'always':46 return True47 return False484950def create_logger(app):51 """Creates a logger for the given application. This logger works52 similar to a regular Python logger but changes the effective logging53 level based on the application's debug flag. Furthermore this
2 unmodified lines
56 """57 Logger = getLoggerClass()5859 class DebugLogger(Logger):27 def getEffectiveLevel(x):28 if x.level == 0 and app.debug:60 def getEffectiveLevel(self):61 if self.level == 0 and app.debug:62 return DEBUG30 return Logger.getEffectiveLevel(x)63 return Logger.getEffectiveLevel(self)6465 class DebugHandler(StreamHandler):33 def emit(x, record):34 StreamHandler.emit(x, record) if app.debug else None66 def emit(self, record):67 if app.debug and _should_log_for(app, 'debug'):68 StreamHandler.emit(self, record)6970 class ProductionHandler(StreamHandler):71 def emit(self, record):72 if not app.debug and _should_log_for(app, 'production'):73 StreamHandler.emit(self, record)7436 handler = DebugHandler()37 handler.setLevel(DEBUG)38 handler.setFormatter(Formatter(app.debug_log_format))75 debug_handler = DebugHandler()76 debug_handler.setLevel(DEBUG)77 debug_handler.setFormatter(Formatter(DEBUG_LOG_FORMAT))7879 prod_handler = ProductionHandler(_proxy_stream)80 prod_handler.setLevel(ERROR)81 prod_handler.setFormatter(Formatter(PROD_LOG_FORMAT))8283 logger = getLogger(app.logger_name)84 # just in case that was not a new logger, get rid of all the handlers85 # already attached to it.86 del logger.handlers[:]87 logger.__class__ = DebugLogger44 logger.addHandler(handler)88 logger.addHandler(debug_handler)89 logger.addHandler(prod_handler)9091 # Disable propagation by default92 logger.propagate = False9394 return logger
deleted:flask/module.py-42 removed
1# -*- coding: utf-8 -*-2"""3 flask.module4 ~~~~~~~~~~~~56 Implements a class that represents module blueprints.78 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import os1314from .blueprints import Blueprint151617def blueprint_is_module(bp):18 """Used to figure out if something is actually a module"""19 return isinstance(bp, Module)202122class Module(Blueprint):23 """Deprecated module support. Until Flask 0.6 modules were a different24 name of the concept now available as blueprints in Flask. They are25 essentially doing the same but have some bad semantics for templates and26 static files that were fixed with blueprints.2728 .. versionchanged:: 0.729 Modules were deprecated in favor for blueprints.30 """3132 def __init__(self, import_name, name=None, url_prefix=None,33 static_path=None, subdomain=None):34 if name is None:35 assert '.' in import_name, 'name required if package name ' \36 'does not point to a submodule'37 name = import_name.rsplit('.', 1)[1]38 Blueprint.__init__(self, name, import_name, url_prefix=url_prefix,39 subdomain=subdomain, template_folder='templates')4041 if os.path.isdir(os.path.join(self.root_path, 'static')):42 self._static_folder = 'static'
modified:flask/sessions.py+110 added-76 removed
3 unmodified lines
4 ~~~~~~~~~~~~~~56 Implements cookie based sessions based on itsdangerous.78 :copyright: (c) 2014 by Armin Ronacher.8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import uuid13import hashlib14import warnings15from base64 import b64encode, b64decode16from datetime import datetime17from werkzeug.http import http_date, parse_date18from werkzeug.datastructures import CallbackDict19from . import Markup, json20from ._compat import iteritems, text_type21from .helpers import total_seconds, is_ip2223from itsdangerous import URLSafeTimedSerializer, BadSignature242524def total_seconds(td):25 return td.days * 60 * 60 * 24 + td.seconds262726class SessionMixin(object):27 """Expands a basic dictionary with an accessors that are expected28 by Flask extensions and users for the session.29 """
9 unmodified lines
39 del _get_permanent, _set_permanent4041 #: some session backends can tell you if a session is new, but that is42 #: not necessarily guaranteed. Use with caution. The default mixin45 #: implementation just hardcodes `False` in.43 #: implementation just hardcodes ``False`` in.44 new = False4548 #: for some backends this will always be `True`, but some backends will46 #: for some backends this will always be ``True``, but some backends will47 #: default this to false and detect changes in the dictionary for as48 #: long as changes do not happen on mutable structures in the session.51 #: The default mixin implementation just hardcodes `True` in.49 #: The default mixin implementation just hardcodes ``True`` in.50 modified = True5152 #: the accessed variable indicates whether or not the session object has53 #: been accessed in that request. This allows flask to append a `Vary:
2 unmodified lines
56 #: session cookie as keys when caching pages, preventing multiple users57 #: from being served the same cache.58 accessed = True5960def _tag(value):61 if isinstance(value, tuple):62 return {' t': [_tag(x) for x in value]}63 elif isinstance(value, uuid.UUID):64 return {' u': value.hex}65 elif isinstance(value, bytes):66 return {' b': b64encode(value).decode('ascii')}67 elif callable(getattr(value, '__html__', None)):68 return {' m': text_type(value.__html__())}69 elif isinstance(value, list):70 return [_tag(x) for x in value]71 elif isinstance(value, datetime):72 return {' d': http_date(value)}73 elif isinstance(value, dict):74 return dict((k, _tag(v)) for k, v in iteritems(value))75 elif isinstance(value, str):76 try:77 return text_type(value)78 except UnicodeError:79 from flask.debughelpers import UnexpectedUnicodeError80 raise UnexpectedUnicodeError(u'A byte string with '81 u'non-ASCII data was passed to the session system '82 u'which can only store unicode strings. Consider '83 u'base64 encoding your string (String was %r)' % value)84 return value858687class TaggedJSONSerializer(object):88 """A customized JSON serializer that supports a few extra types that89 we take for granted when serializing (tuples, markup objects, datetime).90 """9192 def dumps(self, value):68 def _tag(value):69 if isinstance(value, tuple):70 return {' t': [_tag(x) for x in value]}71 elif isinstance(value, uuid.UUID):72 return {' u': value.hex}73 elif isinstance(value, bytes):74 return {' b': b64encode(value).decode('ascii')}75 elif callable(getattr(value, '__html__', None)):76 return {' m': text_type(value.__html__())}77 elif isinstance(value, list):78 return [_tag(x) for x in value]79 elif isinstance(value, datetime):80 return {' d': http_date(value)}81 elif isinstance(value, dict):82 return dict((k, _tag(v)) for k, v in iteritems(value))83 elif isinstance(value, str):84 try:85 return text_type(value)86 except UnicodeError:87 raise UnexpectedUnicodeError(u'A byte string with '88 u'non-ASCII data was passed to the session system '89 u'which can only store unicode strings. Consider '90 u'base64 encoding your string (String was %r)' % value)91 return value93 return json.dumps(_tag(value), separators=(',', ':'))9495 LOADS_MAP = {96 ' t': tuple,97 ' u': uuid.UUID,98 ' b': b64decode,99 ' m': Markup,100 ' d': parse_date,101 }102103 def loads(self, value):104 def object_hook(obj):105 if len(obj) != 1:106 return obj107 the_key, the_value = next(iteritems(obj))99 if the_key == ' t':100 return tuple(the_value)101 elif the_key == ' u':102 return uuid.UUID(the_value)103 elif the_key == ' b':104 return b64decode(the_value)105 elif the_key == ' m':106 return Markup(the_value)107 elif the_key == ' d':108 return parse_date(the_value)108 # Check the key for a corresponding function109 return_function = self.LOADS_MAP.get(the_key)110 if return_function:111 # Pass the value to the function112 return return_function(the_value)113 # Didn't find a function for this object114 return obj115 return json.loads(value, object_hook=object_hook)116117118session_json_serializer = TaggedJSONSerializer()119120121class SecureCookieSession(CallbackDict, SessionMixin):117 """Baseclass for sessions based on signed cookies."""122 """Base class for sessions based on signed cookies."""123124 def __init__(self, initial=None):125 def on_update(self):126 self.modified = True
16 unmodified lines
143 but fail on setting.144 """145146 def _fail(self, *args, **kwargs):142 raise RuntimeError('the session is unavailable because no secret '147 raise RuntimeError('The session is unavailable because no secret '148 'key was set. Set the secret_key on the '149 'application to something unique and secret.')150 __setitem__ = __delitem__ = clear = pop = popitem = \151 update = setdefault = _fail
14 unmodified lines
166167 class Session(dict, SessionMixin):168 pass169165 If :meth:`open_session` returns `None` Flask will call into170 If :meth:`open_session` returns ``None`` Flask will call into171 :meth:`make_null_session` to create a session that acts as replacement172 if the session support cannot work because some requirement is not173 fulfilled. The default :class:`NullSession` class that is created174 will complain that the secret key was not set.
13 unmodified lines
188 #: this type.189 null_session_class = NullSession190191 #: A flag that indicates if the session interface is pickle based.187 #: This can be used by flask extensions to make a decision in regards192 #: This can be used by Flask extensions to make a decision in regards193 #: to how to deal with the session object.194 #:195 #: .. versionadded:: 0.10196 pickle_based = False
19 unmodified lines
216 """217 return isinstance(obj, self.null_session_class)218219 def get_cookie_domain(self, app):215 """Helpful helper method that returns the cookie domain that should216 be used for the session cookie if session cookies are used.220 """Returns the domain that should be set for the session cookie.221 222 Uses ``SESSION_COOKIE_DOMAIN`` if it is configured, otherwise223 falls back to detecting the domain based on ``SERVER_NAME``.224 225 Once detected (or if not set at all), ``SESSION_COOKIE_DOMAIN`` is226 updated to avoid re-running the logic.227 """218 if app.config['SESSION_COOKIE_DOMAIN'] is not None:219 return app.config['SESSION_COOKIE_DOMAIN']220 if app.config['SERVER_NAME'] is not None:221 # chop of the port which is usually not supported by browsers222 rv = '.' + app.config['SERVER_NAME'].rsplit(':', 1)[0]228224 # Google chrome does not like cookies set to .localhost, so225 # we just go with no domain then. Flask documents anyways that226 # cross domain cookies need a fully qualified domain name227 if rv == '.localhost':228 rv = None229 rv = app.config['SESSION_COOKIE_DOMAIN']230230 # If we infer the cookie domain from the server name we need231 # to check if we are in a subpath. In that case we can't232 # set a cross domain cookie.233 if rv is not None:234 path = self.get_cookie_path(app)235 if path != '/':236 rv = rv.lstrip('.')231 # set explicitly, or cached from SERVER_NAME detection232 # if False, return None233 if rv is not None:234 return rv if rv else None235238 return rv236 rv = app.config['SERVER_NAME']237238 # server name not set, cache False to return none next time239 if not rv:240 app.config['SESSION_COOKIE_DOMAIN'] = False241 return None242243 # chop off the port which is usually not supported by browsers244 # remove any leading '.' since we'll add that later245 rv = rv.rsplit(':', 1)[0].lstrip('.')246247 if '.' not in rv:248 # Chrome doesn't allow names without a '.'249 # this should only come up with localhost250 # hack around this by not setting the name, and show a warning251 warnings.warn(252 '"{rv}" is not a valid cookie domain, it must contain a ".".'253 ' Add an entry to your hosts file, for example'254 ' "{rv}.localdomain", and use that instead.'.format(rv=rv)255 )256 app.config['SESSION_COOKIE_DOMAIN'] = False257 return None258259 ip = is_ip(rv)260261 if ip:262 warnings.warn(263 'The session cookie domain is an IP address. This may not work'264 ' as intended in some browsers. Add an entry to your hosts'265 ' file, for example "localhost.localdomain", and use that'266 ' instead.'267 )268269 # if this is not an ip and app is mounted at the root, allow subdomain270 # matching by adding a '.' prefix271 if self.get_cookie_path(app) == '/' and not ip:272 rv = '.' + rv273274 app.config['SESSION_COOKIE_DOMAIN'] = rv275 return rv276277 def get_cookie_path(self, app):278 """Returns the path for which the cookie should be valid. The279 default implementation uses the value from the ``SESSION_COOKIE_PATH``280 config var if it's set, and falls back to ``APPLICATION_ROOT`` or244 uses ``/`` if it's `None`.281 uses ``/`` if it's ``None``.282 """283 return app.config['SESSION_COOKIE_PATH'] or \284 app.config['APPLICATION_ROOT'] or '/'285
11 unmodified lines
297 return app.config['SESSION_COOKIE_SECURE']298299 def get_expiration_time(self, app, session):300 """A helper method that returns an expiration date for the session264 or `None` if the session is linked to the browser session. The301 or ``None`` if the session is linked to the browser session. The302 default implementation returns now + the permanent session303 lifetime configured on the application.304 """305 if session.permanent:306 return datetime.utcnow() + app.permanent_session_lifetime307308 def should_set_cookie(self, app, session):272 """Indicates weather a cookie should be set now or not. This is309 """Indicates whether a cookie should be set now or not. This is310 used by session backends to figure out if they should emit a311 set-cookie header or not. The default behavior is controlled by312 the ``SESSION_REFRESH_EACH_REQUEST`` config variable. If276 it's set to `False` then a cookie is only set if the session is277 modified, if set to `True` it's always set if the session is313 it's set to ``False`` then a cookie is only set if the session is314 modified, if set to ``True`` it's always set if the session is315 permanent.316317 This check is usually skipped if sessions get deleted.318282 .. versionadded:: 1.0319 .. versionadded:: 0.11320 """321 if session.modified:322 return True323 save_each = app.config['SESSION_REFRESH_EACH_REQUEST']324 return save_each and session.permanent325326 def open_session(self, app, request):290 """This method has to be implemented and must either return `None`327 """This method has to be implemented and must either return ``None``328 in case the loading failed because of a configuration error or an329 instance of a session object which implements a dictionary like330 interface + the methods and attributes on :class:`SessionMixin`.331 """
86 unmodified lines
418 val = self.get_signing_serializer(app).dumps(dict(session))419 response.set_cookie(app.session_cookie_name, val,420 expires=expires, httponly=httponly,421 domain=domain, path=path, secure=secure)385386387from flask.debughelpers import UnexpectedUnicodeError
modified:flask/signals.py+5 added-4 removed
2 unmodified lines
3 flask.signals4 ~~~~~~~~~~~~~56 Implements signals based on blinker if available, otherwise7 falls silently back to a noop7 falls silently back to a noop.89 :copyright: (c) 2014 by Armin Ronacher.9 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""12signals_available = False13try:
22 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 sourcecode or consult45# 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+38 added-32 removed
3 unmodified lines
4 ~~~~~~~~~~~~~~~~56 Implements the bridge to Jinja2.78 :copyright: (c) 2014 by Armin Ronacher.8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import posixpath11from jinja2 import BaseLoader, Environment as BaseEnvironment, \12 TemplateNotFound1314from .globals import _request_ctx_stack, _app_ctx_stack16from .signals import template_rendered17from .module import blueprint_is_module18from ._compat import itervalues, iteritems15from .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 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 = []61 trv = None6258 for loader, local_name in self._iter_loaders(template):63 for srcobj, loader in self._iter_loaders(template):64 try:60 return loader.get_source(environment, local_name)65 rv = loader.get_source(environment, template)66 if trv is None:67 trv = rv68 except TemplateNotFound:62 pass69 rv = None70 attempts.append((loader, srcobj, rv))7172 from .debughelpers import explain_template_loading_attempts73 explain_template_loading_attempts(self.app, template, attempts)7475 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:69 yield loader, template90 yield self.app, loader9171 # old style module based loaders in case we are dealing with a72 # blueprint that is an old style module73 try:74 module, local_name = posixpath.normpath(template).split('/', 1)75 blueprint = self.app.blueprints[module]76 if blueprint_is_module(blueprint):77 loader = blueprint.jinja_loader78 if loader is not None:79 yield loader, local_name80 except (ValueError, KeyError):81 pass8283 for blueprint in itervalues(self.app.blueprints):84 if blueprint_is_module(blueprint):85 continue92 for blueprint in self.app.iter_blueprints():93 loader = blueprint.jinja_loader94 if loader is not None:88 yield loader, template95 yield blueprint, loader9697 def list_templates(self):98 result = set()99 loader = self.app.jinja_loader100 if loader is not None:101 result.update(loader.list_templates())10296 for name, blueprint in iteritems(self.app.blueprints):103 for blueprint in self.app.iter_blueprints():104 loader = blueprint.jinja_loader105 if loader is not None:106 for template in loader.list_templates():100 prefix = ''101 if blueprint_is_module(blueprint):102 prefix = name + '/'103 result.add(prefix + template)107 result.add(template)108109 return list(result)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 string133 with the given context.139 with the given context. Template variables will be autoescaped.140135 :param source: the sourcecode of the template to be141 :param source: the source code of the template to be142 rendered143 :param context: the variables that should be available in the144 context of the template.145 """
4 unmodified lines
modified:flask/testing.py+22 added-5 removed
4 unmodified lines
56 Implements test support helpers. This module is lazily imported7 and usually not used in production environments.89 :copyright: (c) 2014 by Armin Ronacher.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 ::7273 with client.session_transaction() as session:74 session['value'] = 427576 Internally this is implemented by going through a temporary test
36 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+24 added-20 removed
3 unmodified lines
4 ~~~~~~~~~~~56 This module provides class-based views inspired by the ones in Django.78 :copyright: (c) 2014 by Armin Ronacher.8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from .globals import request12from ._compat import with_metaclass
34 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 #: The canonical way to decorate class-based views is to decorate the55 #: return value of as_view(). However since this moves parts of the
46 unmodified lines
102 return view103104105class MethodViewType(type):106 """Metaclass for :class:`MethodView` that determines what methods the view107 defines.108 """109107 def __new__(cls, name, bases, d):108 rv = type.__new__(cls, name, bases, d)110 def __init__(cls, name, bases, d):111 super(MethodViewType, cls).__init__(name, bases, d)112113 if 'methods' not in d:110 methods = set(rv.methods or [])111 for key in d:112 if key in http_method_funcs:114 methods = set()115116 for key in http_method_funcs:117 if hasattr(cls, key):118 methods.add(key.upper())114 # If we have no method at all in there we don't want to115 # add a method list. (This is for instance the case for116 # the baseclass or another subclass of a base method view117 # that does not introduce new methods).119120 # If we have no method at all in there we don't want to add a121 # method list. This is for instance the case for the base class122 # or another subclass of a base method view that does not introduce123 # new methods.124 if methods:119 rv.methods = sorted(methods)120 return rv125 cls.methods = methods126127128class MethodView(with_metaclass(MethodViewType, View)):124 """Like a regular class-based view but that dispatches requests to125 particular methods. For instance if you implement a method called126 :meth:`get` it means you will response to ``'GET'`` requests and127 the :meth:`dispatch_request` implementation will automatically128 forward your request to that. Also :attr:`options` is set for you129 automatically::129 """A class-based view that dispatches request methods to the corresponding130 class methods. For example, if you implement a ``get`` method, it will be131 used to handle ``GET`` requests. ::132133 class CounterAPI(MethodView):132134 def get(self):135 return session.get('counter', 0)136137 def post(self):
1 unmodified line
139 return 'OK'140141 app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))142 """143144 def dispatch_request(self, *args, **kwargs):145 meth = getattr(self, request.method.lower(), None)146147 # If the request method is HEAD and we don't have a handler for it148 # retry with GET.149 if meth is None and request.method == 'HEAD':150 meth = getattr(self, 'get', None)151152 assert meth is not None, 'Unimplemented method %r' % request.method153 return meth(*args, **kwargs)
modified:flask/wrappers.py+26 added-20 removed
3 unmodified lines
4 ~~~~~~~~~~~~~~56 Implements the WSGI wrappers (request and response).78 :copyright: (c) 2014 by Armin Ronacher.8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112from werkzeug.wrappers import Request as RequestBase, Response as ResponseBase13from werkzeug.exceptions import BadRequest1415from .debughelpers import attach_enctype_error_multidict15from . import json16from .globals import _request_ctx_stack171918_missing = object()192021def _get_data(req, cache):
23 unmodified lines
45 #: .. versionadded:: 0.646 url_rule = None4748 #: A dict of view arguments that matched the request. If an exception51 #: happened when matching, this will be `None`.49 #: happened when matching, this will be ``None``.50 view_args = None5152 #: If matching the URL failed, this is the exception that will be53 #: raised / was raised as part of the request handling. This is
6 unmodified lines
60 _is_old_module = False6162 @property63 def max_content_length(self):66 """Read-only view of the `MAX_CONTENT_LENGTH` config key."""64 """Read-only view of the ``MAX_CONTENT_LENGTH`` config key."""65 ctx = _request_ctx_stack.top66 if ctx is not None:67 return ctx.app.config['MAX_CONTENT_LENGTH']68
1 unmodified line
70 def endpoint(self):71 """The endpoint that matched the request. This in combination with72 :attr:`view_args` can be used to reconstruct the same or a73 modified URL. If an exception happened when matching, this will76 be `None`.74 be ``None``.75 """76 if self.url_rule is not None:77 return self.url_rule.endpoint78
17 unmodified lines
96 return self.url_rule.endpoint.rsplit('.', 1)[0]9798 @property99 def json(self):102 """If the mimetype is `application/json` this will contain the103 parsed JSON data. Otherwise this will be `None`.100 """If the mimetype is :mimetype:`application/json` this will contain the101 parsed JSON data. Otherwise this will be ``None``.102103 The :meth:`get_json` method should be used instead.104 """107 # XXX: deprecate property105 from warnings import warn106 warn(DeprecationWarning('json is deprecated. '107 'Use get_json() instead.'), stacklevel=2)108 return self.get_json()109110 @property111 def is_json(self):112 """Indicates if this request is JSON or not. By default a request113 is considered to include JSON data if the mimetype is114 ``application/json`` or ``application/*+json``.114 :mimetype:`application/json` or :mimetype:`application/*+json`.115116 .. versionadded:: 0.11117 """118 mt = self.mimetype
3 unmodified lines
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 ``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.132132 :param force: if set to `True` the mimetype is ignored.133 :param silent: if set to `True` this method will fail silently134 and return `None`.135 :param cache: if set to `True` the parsed JSON data is remembered133 :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
29 unmodified lines
175 add it by subclassing.176177 .. versionadded:: 0.8178 """179 ctx = _request_ctx_stack.top180 if ctx is not None and ctx.app.config.get('DEBUG', False):181 raise BadRequest('Failed to decode JSON object: {0}'.format(e))182 raise BadRequest()183184 def _load_form_data(self):185 RequestBase._load_form_data(self)
2 unmodified lines
188 # subclass that raises a different error for key errors.189 ctx = _request_ctx_stack.top190 if ctx is not None and ctx.app.debug and \191 self.mimetype != 'multipart/form-data' and not self.files:192 from .debughelpers import attach_enctype_error_multidict193 attach_enctype_error_multidict(self)194195196class Response(ResponseBase):
9 unmodified lines
deleted:scripts/testproj/templates/index.html-2 removed
1{{ url_for('static', filename='test.css') }}2{{ url_for('foo.static', filename='test.css') }}
deleted:scripts/testproj/test.py-46 removed
1from flask import Flask, Module, render_template, url_for234mod = Module(__name__)5mod2 = Module(__name__, 'testmod2')6mod3 = Module(__name__, name='somemod', subdomain='meh')789@app.after_request10def after_request(response):11 g.db.close()12 return response131415@app.route('/')16def index_foo():17 x1 = url_for('somemod.index')18 x2 = url_for('.index')19 return render_template('test/index.html')202122@mod.route('/')23def index():24 x1 = url_for('somemod.index')25 x2 = url_for('.index')26 return render_template('test/index.html')272829@mod2.route('/')30def mod2_index():31 return render_template('testmod2/index.html')323334@mod3.route('/')35def mod3_index():36 return render_template('something-else/index.html')373839app = Flask(__name__)40app.register_module(mod)41app.register_module(mod2)424344def handle_404(error):45 return 'Testing', 40446app.error_handlers[404] = handle_404
modified:scripts/flask-07-upgrade.py+4 added-3 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`.
2 unmodified lines
15 attempts to accomplish is impossible to do statically it tries to support16 the most common patterns at least. The diff it generates should be17 hand reviewed and not applied blindly without making backups.1819 :copyright: (c) Copyright 2014 by Armin Ronacher.19 :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
modified:scripts/flaskext_compat.py+4 added-4 removed
10 unmodified lines
11 import flaskext_compat12 flaskext_compat.activate()13 from flask.ext import foo1415 :copyright: (c) 2014 by Armin Ronacher.15 :copyright: (c) 2015 by Armin Ronacher.16 :license: BSD, see LICENSE for more details.17"""18import types19import sys20import os20import imp212223class ExtensionImporter(object):24 """This importer redirects imports from this submodule to other locations.
18 unmodified lines
4344 def install(self):45 sys.meta_path[:] = [x for x in sys.meta_path if self != x] + [self]4647 def find_module(self, fullname):47 def find_module(self, fullname, path=None):48 if fullname.startswith(self.prefix):49 return self5051 def load_module(self, fullname):
65 unmodified lines
117118119def activate():120 import flask121 ext_module = imp.new_module('flask.ext')121 ext_module = types.ModuleType('flask.ext')122 ext_module.__path__ = []123 flask.ext = sys.modules['flask.ext'] = ext_module124 importer = ExtensionImporter(['flask_%s', 'flaskext.%s'], 'flask.ext')125 importer.install()
deleted:scripts/flaskext_test.py-309 removed
1# -*- coding: utf-8 -*-2"""3 Flask Extension Tests4 ~~~~~~~~~~~~~~~~~~~~~56 Tests the Flask extensions.78 :copyright: (c) 2014 by Ali Afshar.9 :license: BSD, see LICENSE for more details.10"""1112import os13import sys14import shutil15import urllib216import tempfile17import subprocess18import argparse1920from flask import json2122from setuptools.package_index import PackageIndex23from setuptools.archive_util import unpack_archive2425flask_svc_url = 'http://flask.pocoo.org/extensions/'262728# OS X has awful paths when using mkstemp or gettempdir(). I don't29# care about security or clashes here, so pick something that is30# actually rememberable.31if sys.platform == 'darwin':32 _tempdir = '/private/tmp'33else:34 _tempdir = tempfile.gettempdir()35tdir = _tempdir + '/flaskext-test'36flaskdir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))373839# virtualenv hack *cough*40os.environ['PYTHONDONTWRITEBYTECODE'] = ''414243RESULT_TEMPATE = u'''\44<!doctype html>45<title>Flask-Extension Test Results</title>46<style type=text/css>47 body { font-family: 'Georgia', serif; font-size: 17px; color: #000; }48 a { color: #004B6B; }49 a:hover { color: #6D4100; }50 h1, h2, h3 { font-family: 'Garamond', 'Georgia', serif; font-weight: normal; }51 h1 { font-size: 30px; margin: 15px 0 5px 0; }52 h2 { font-size: 24px; margin: 15px 0 5px 0; }53 h3 { font-size: 19px; margin: 15px 0 5px 0; }54 textarea, code,55 pre { font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono',56 'Bitstream Vera Sans Mono', monospace!important; font-size: 15px;57 background: #eee; }58 pre { padding: 7px 15px; line-height: 1.3; }59 p { line-height: 1.4; }60 table { border: 1px solid black; border-collapse: collapse;61 margin: 15px 0; }62 td, th { border: 1px solid black; padding: 4px 10px;63 text-align: left; }64 th { background: #eee; font-weight: normal; }65 tr.success { background: #D3F5CC; }66 tr.failed { background: #F5D2CB; }67</style>68<h1>Flask-Extension Test Results</h1>69<p>70 This page contains the detailed test results for the test run of71 all {{ 'approved' if approved }} Flask extensions.72<h2>Summary</h2>73<table class=results>74 <thead>75 <tr>76 <th>Extension77 <th>Version78 <th>Author79 <th>License80 <th>Outcome81 {%- for iptr, _ in results[0].logs|dictsort %}82 <th>{{ iptr }}83 {%- endfor %}84 </tr>85 </thead>86 <tbody>87 {%- for result in results %}88 {% set outcome = 'success' if result.success else 'failed' %}89 <tr class={{ outcome }}>90 <th>{{ result.name }}91 <td>{{ result.version }}92 <td>{{ result.author }}93 <td>{{ result.license }}94 <td>{{ outcome }}95 {%- for iptr, _ in result.logs|dictsort %}96 <td><a href="#{{ result.name }}-{{ iptr }}">see log</a>97 {%- endfor %}98 </tr>99 {%- endfor %}100 </tbody>101</table>102<h2>Test Logs</h2>103<p>Detailed test logs for all tests on all platforms:104{%- for result in results %}105 {%- for iptr, log in result.logs|dictsort %}106 <h3 id="{{ result.name }}-{{ iptr }}">107 {{ result.name }} - {{ result.version }} [{{ iptr }}]</h3>108 <pre>{{ log }}</pre>109 {%- endfor %}110{%- endfor %}111'''112113114def log(msg, *args):115 print '[EXTTEST]', msg % args116117118class TestResult(object):119120 def __init__(self, name, folder, statuscode, interpreters):121 intrptr = os.path.join(folder, '.tox/%s/bin/python'122 % interpreters[0])123 self.statuscode = statuscode124 self.folder = folder125 self.success = statuscode == 0126127 def fetch(field):128 try:129 c = subprocess.Popen([intrptr, 'setup.py',130 '--' + field], cwd=folder,131 stdout=subprocess.PIPE)132 return c.communicate()[0].strip()133 except OSError:134 return '?'135 self.name = name136 self.license = fetch('license')137 self.author = fetch('author')138 self.version = fetch('version')139140 self.logs = {}141 for interpreter in interpreters:142 logfile = os.path.join(folder, '.tox/%s/log/test.log'143 % interpreter)144 if os.path.isfile(logfile):145 self.logs[interpreter] = open(logfile).read()146 else:147 self.logs[interpreter] = ''148149150def create_tdir():151 try:152 shutil.rmtree(tdir)153 except Exception:154 pass155 os.mkdir(tdir)156157158def package_flask():159 distfolder = tdir + '/.flask-dist'160 c = subprocess.Popen(['python', 'setup.py', 'sdist', '--formats=gztar',161 '--dist', distfolder], cwd=flaskdir)162 c.wait()163 return os.path.join(distfolder, os.listdir(distfolder)[0])164165166def get_test_command(checkout_dir):167 if os.path.isfile(checkout_dir + '/Makefile'):168 return 'make test'169 return 'python setup.py test'170171172def fetch_extensions_list():173 req = urllib2.Request(flask_svc_url, headers={'accept':'application/json'})174 d = urllib2.urlopen(req).read()175 data = json.loads(d)176 for ext in data['extensions']:177 yield ext178179180def checkout_extension(name):181 log('Downloading extension %s to temporary folder', name)182 root = os.path.join(tdir, name)183 os.mkdir(root)184 checkout_path = PackageIndex().download(name, root)185186 unpack_archive(checkout_path, root)187 path = None188 for fn in os.listdir(root):189 path = os.path.join(root, fn)190 if os.path.isdir(path):191 break192 log('Downloaded to %s', path)193 return path194195196tox_template = """[tox]197envlist=%(env)s198199[testenv]200deps=201 %(deps)s202 distribute203 py204commands=bash flaskext-runtest.sh {envlogdir}/test.log205downloadcache=%(cache)s206"""207208209def create_tox_ini(checkout_path, interpreters, flask_dep):210 tox_path = os.path.join(checkout_path, 'tox-flask-test.ini')211 if not os.path.exists(tox_path):212 with open(tox_path, 'w') as f:213 f.write(tox_template % {214 'env': ','.join(interpreters),215 'cache': tdir,216 'deps': flask_dep217 })218 return tox_path219220221def iter_extensions(only_approved=True):222 for ext in fetch_extensions_list():223 if ext['approved'] or not only_approved:224 yield ext['name']225226227def test_extension(name, interpreters, flask_dep):228 checkout_path = checkout_extension(name)229 log('Running tests with tox in %s', checkout_path)230231 # figure out the test command and write a wrapper script. We232 # can't write that directly into the tox ini because tox does233 # not invoke the command from the shell so we have no chance234 # to pipe the output into a logfile. The /dev/null hack is235 # to trick py.test (if used) into not guessing widths from the236 # invoking terminal.237 test_command = get_test_command(checkout_path)238 log('Test command: %s', test_command)239 f = open(checkout_path + '/flaskext-runtest.sh', 'w')240 f.write(test_command + ' &> "$1" < /dev/null\n')241 f.close()242243 # if there is a tox.ini, remove it, it will cause troubles244 # for us. Remove it if present, we are running tox ourselves245 # afterall.246247 create_tox_ini(checkout_path, interpreters, flask_dep)248 rv = subprocess.call(['tox', '-c', 'tox-flask-test.ini'], cwd=checkout_path)249 return TestResult(name, checkout_path, rv, interpreters)250251252def run_tests(extensions, interpreters):253 results = {}254 create_tdir()255 log('Packaging Flask')256 flask_dep = package_flask()257 log('Running extension tests')258 log('Temporary Environment: %s', tdir)259 for name in extensions:260 log('Testing %s', name)261 result = test_extension(name, interpreters, flask_dep)262 if result.success:263 log('Extension test succeeded')264 else:265 log('Extension test failed')266 results[name] = result267 return results268269270def render_results(results, approved):271 from jinja2 import Template272 items = results.values()273 items.sort(key=lambda x: x.name.lower())274 rv = Template(RESULT_TEMPATE, autoescape=True).render(results=items,275 approved=approved)276 fd, filename = tempfile.mkstemp(suffix='.html')277 os.fdopen(fd, 'w').write(rv.encode('utf-8') + '\n')278 return filename279280281def main():282 parser = argparse.ArgumentParser(description='Runs Flask extension tests')283 parser.add_argument('--all', dest='all', action='store_true',284 help='run against all extensions, not just approved')285 parser.add_argument('--browse', dest='browse', action='store_true',286 help='show browser with the result summary')287 parser.add_argument('--env', dest='env', default='py25,py26,py27',288 help='the tox environments to run against')289 parser.add_argument('--extension=', dest='extension', default=None,290 help='tests a single extension')291 args = parser.parse_args()292293 if args.extension is not None:294 only_approved = False295 extensions = [args.extension]296 else:297 only_approved = not args.all298 extensions = iter_extensions(only_approved)299300 results = run_tests(extensions, [x.strip() for x in args.env.split(',')])301 filename = render_results(results, only_approved)302 if args.browse:303 import webbrowser304 webbrowser.open('file:///' + filename.lstrip('/'))305 print 'Results written to', filename306307308if __name__ == '__main__':309 main()
added:scripts/flaskext_tester.py+309 added
1# -*- coding: utf-8 -*-2"""3 Flask Extension Tests4 ~~~~~~~~~~~~~~~~~~~~~56 Tests the Flask extensions.78 :copyright: (c) 2015 by Ali Afshar.9 :license: BSD, see LICENSE for more details.10"""1112import os13import sys14import shutil15import urllib216import tempfile17import subprocess18import argparse1920from flask import json2122from setuptools.package_index import PackageIndex23from setuptools.archive_util import unpack_archive2425flask_svc_url = 'http://flask.pocoo.org/extensions/'262728# OS X has awful paths when using mkstemp or gettempdir(). I don't29# care about security or clashes here, so pick something that is30# actually memorable.31if sys.platform == 'darwin':32 _tempdir = '/private/tmp'33else:34 _tempdir = tempfile.gettempdir()35tdir = _tempdir + '/flaskext-test'36flaskdir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))373839# virtualenv hack *cough*40os.environ['PYTHONDONTWRITEBYTECODE'] = ''414243RESULT_TEMPATE = u'''\44<!doctype html>45<title>Flask-Extension Test Results</title>46<style type=text/css>47 body { font-family: 'Georgia', serif; font-size: 17px; color: #000; }48 a { color: #004B6B; }49 a:hover { color: #6D4100; }50 h1, h2, h3 { font-family: 'Garamond', 'Georgia', serif; font-weight: normal; }51 h1 { font-size: 30px; margin: 15px 0 5px 0; }52 h2 { font-size: 24px; margin: 15px 0 5px 0; }53 h3 { font-size: 19px; margin: 15px 0 5px 0; }54 textarea, code,55 pre { font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono',56 'Bitstream Vera Sans Mono', monospace!important; font-size: 15px;57 background: #eee; }58 pre { padding: 7px 15px; line-height: 1.3; }59 p { line-height: 1.4; }60 table { border: 1px solid black; border-collapse: collapse;61 margin: 15px 0; }62 td, th { border: 1px solid black; padding: 4px 10px;63 text-align: left; }64 th { background: #eee; font-weight: normal; }65 tr.success { background: #D3F5CC; }66 tr.failed { background: #F5D2CB; }67</style>68<h1>Flask-Extension Test Results</h1>69<p>70 This page contains the detailed test results for the test run of71 all {{ 'approved' if approved }} Flask extensions.72<h2>Summary</h2>73<table class=results>74 <thead>75 <tr>76 <th>Extension77 <th>Version78 <th>Author79 <th>License80 <th>Outcome81 {%- for iptr, _ in results[0].logs|dictsort %}82 <th>{{ iptr }}83 {%- endfor %}84 </tr>85 </thead>86 <tbody>87 {%- for result in results %}88 {% set outcome = 'success' if result.success else 'failed' %}89 <tr class={{ outcome }}>90 <th>{{ result.name }}91 <td>{{ result.version }}92 <td>{{ result.author }}93 <td>{{ result.license }}94 <td>{{ outcome }}95 {%- for iptr, _ in result.logs|dictsort %}96 <td><a href="#{{ result.name }}-{{ iptr }}">see log</a>97 {%- endfor %}98 </tr>99 {%- endfor %}100 </tbody>101</table>102<h2>Test Logs</h2>103<p>Detailed test logs for all tests on all platforms:104{%- for result in results %}105 {%- for iptr, log in result.logs|dictsort %}106 <h3 id="{{ result.name }}-{{ iptr }}">107 {{ result.name }} - {{ result.version }} [{{ iptr }}]</h3>108 <pre>{{ log }}</pre>109 {%- endfor %}110{%- endfor %}111'''112113114def log(msg, *args):115 print('[EXTTEST] ' + (msg % args))116117118class TestResult(object):119120 def __init__(self, name, folder, statuscode, interpreters):121 intrptr = os.path.join(folder, '.tox/%s/bin/python'122 % interpreters[0])123 self.statuscode = statuscode124 self.folder = folder125 self.success = statuscode == 0126127 def fetch(field):128 try:129 c = subprocess.Popen([intrptr, 'setup.py',130 '--' + field], cwd=folder,131 stdout=subprocess.PIPE)132 return c.communicate()[0].strip()133 except OSError:134 return '?'135 self.name = name136 self.license = fetch('license')137 self.author = fetch('author')138 self.version = fetch('version')139140 self.logs = {}141 for interpreter in interpreters:142 logfile = os.path.join(folder, '.tox/%s/log/test.log'143 % interpreter)144 if os.path.isfile(logfile):145 self.logs[interpreter] = open(logfile).read()146 else:147 self.logs[interpreter] = ''148149150def create_tdir():151 try:152 shutil.rmtree(tdir)153 except Exception:154 pass155 os.mkdir(tdir)156157158def package_flask():159 distfolder = tdir + '/.flask-dist'160 c = subprocess.Popen(['python', 'setup.py', 'sdist', '--formats=gztar',161 '--dist', distfolder], cwd=flaskdir)162 c.wait()163 return os.path.join(distfolder, os.listdir(distfolder)[0])164165166def get_test_command(checkout_dir):167 if os.path.isfile(checkout_dir + '/Makefile'):168 return 'make test'169 return 'python setup.py test'170171172def fetch_extensions_list():173 req = urllib2.Request(flask_svc_url, headers={'accept':'application/json'})174 d = urllib2.urlopen(req).read()175 data = json.loads(d)176 for ext in data['extensions']:177 yield ext178179180def checkout_extension(name):181 log('Downloading extension %s to temporary folder', name)182 root = os.path.join(tdir, name)183 os.mkdir(root)184 checkout_path = PackageIndex().download(name, root)185186 unpack_archive(checkout_path, root)187 path = None188 for fn in os.listdir(root):189 path = os.path.join(root, fn)190 if os.path.isdir(path):191 break192 log('Downloaded to %s', path)193 return path194195196tox_template = """[tox]197envlist=%(env)s198199[testenv]200deps=201 %(deps)s202 distribute203 py204commands=bash flaskext-runtest.sh {envlogdir}/test.log205downloadcache=%(cache)s206"""207208209def create_tox_ini(checkout_path, interpreters, flask_dep):210 tox_path = os.path.join(checkout_path, 'tox-flask-test.ini')211 if not os.path.exists(tox_path):212 with open(tox_path, 'w') as f:213 f.write(tox_template % {214 'env': ','.join(interpreters),215 'cache': tdir,216 'deps': flask_dep217 })218 return tox_path219220221def iter_extensions(only_approved=True):222 for ext in fetch_extensions_list():223 if ext['approved'] or not only_approved:224 yield ext['name']225226227def test_extension(name, interpreters, flask_dep):228 checkout_path = checkout_extension(name)229 log('Running tests with tox in %s', checkout_path)230231 # figure out the test command and write a wrapper script. We232 # can't write that directly into the tox ini because tox does233 # not invoke the command from the shell so we have no chance234 # to pipe the output into a logfile. The /dev/null hack is235 # to trick py.test (if used) into not guessing widths from the236 # invoking terminal.237 test_command = get_test_command(checkout_path)238 log('Test command: %s', test_command)239 f = open(checkout_path + '/flaskext-runtest.sh', 'w')240 f.write(test_command + ' &> "$1" < /dev/null\n')241 f.close()242243 # if there is a tox.ini, remove it, it will cause troubles244 # for us. Remove it if present, we are running tox ourselves245 # afterall.246247 create_tox_ini(checkout_path, interpreters, flask_dep)248 rv = subprocess.call(['tox', '-c', 'tox-flask-test.ini'], cwd=checkout_path)249 return TestResult(name, checkout_path, rv, interpreters)250251252def run_tests(extensions, interpreters):253 results = {}254 create_tdir()255 log('Packaging Flask')256 flask_dep = package_flask()257 log('Running extension tests')258 log('Temporary Environment: %s', tdir)259 for name in extensions:260 log('Testing %s', name)261 result = test_extension(name, interpreters, flask_dep)262 if result.success:263 log('Extension test succeeded')264 else:265 log('Extension test failed')266 results[name] = result267 return results268269270def render_results(results, approved):271 from jinja2 import Template272 items = results.values()273 items.sort(key=lambda x: x.name.lower())274 rv = Template(RESULT_TEMPATE, autoescape=True).render(results=items,275 approved=approved)276 fd, filename = tempfile.mkstemp(suffix='.html')277 os.fdopen(fd, 'w').write(rv.encode('utf-8') + '\n')278 return filename279280281def main():282 parser = argparse.ArgumentParser(description='Runs Flask extension tests')283 parser.add_argument('--all', dest='all', action='store_true',284 help='run against all extensions, not just approved')285 parser.add_argument('--browse', dest='browse', action='store_true',286 help='show browser with the result summary')287 parser.add_argument('--env', dest='env', default='py25,py26,py27',288 help='the tox environments to run against')289 parser.add_argument('--extension=', dest='extension', default=None,290 help='tests a single extension')291 args = parser.parse_args()292293 if args.extension is not None:294 only_approved = False295 extensions = [args.extension]296 else:297 only_approved = not args.all298 extensions = iter_extensions(only_approved)299300 results = run_tests(extensions, [x.strip() for x in args.env.split(',')])301 filename = render_results(results, only_approved)302 if args.browse:303 import webbrowser304 webbrowser.open('file:///' + filename.lstrip('/'))305 print('Results written to {}'.format(filename))306307308if __name__ == '__main__':309 main()
modified:scripts/make-release.py+5 added-11 removed
5 unmodified lines
67 Helper script that performs a release. Does pretty much everything8 automatically for us.910 :copyright: (c) 2014 by Armin Ronacher.10 :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()
added:tests/static/config.json+4 added
1{2 "TEST_KEY": "foo",3 "SECRET_KEY": "devkey"4}
added:tests/static/index.html+1 added
1<h1>Hello World!</h1>
added:tests/templates/nested/nested.txt+1 added
1I'm nested
added:tests/templates/_macro.html+1 added
1{% macro hello(name) %}Hello {{ name }}!{% endmacro %}
added:tests/templates/context_template.html+1 added
1<p>{{ value }}|{{ injected_value }}
added:tests/templates/escaping_template.html+6 added
1{{ text }}2{{ html }}3{% autoescape false %}{{ text }}4{{ html }}{% endautoescape %}5{% autoescape true %}{{ text }}6{{ html }}{% endautoescape %}
added:tests/templates/mail.txt+1 added
1{{ foo}} Mail
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/templates/simple_template.html+1 added
1<h1>{{ whiskey }}</h1>
added:tests/templates/template_filter.html+1 added
1{{ value|super_reverse }}
added:tests/templates/template_test.html+3 added
1{% if value is boolean %}2 Success!3{% endif %}
added:tests/test_apps/blueprintapp/apps/admin/static/css/test.css+1 added
1/* nested file */
added:tests/test_apps/blueprintapp/apps/admin/static/test.txt+1 added
1Admin File
added:tests/test_apps/blueprintapp/apps/admin/templates/admin/index.html+1 added
1Hello from the Admin
added:tests/test_apps/blueprintapp/apps/admin/__init__.py+15 added
1from flask import Blueprint, render_template23admin = Blueprint('admin', __name__, url_prefix='/admin',4 template_folder='templates',5 static_folder='static')678@admin.route('/')9def index():10 return render_template('admin/index.html')111213@admin.route('/index2')14def index2():15 return render_template('./admin/index.html')
added:tests/test_apps/blueprintapp/apps/frontend/templates/frontend/index.html+1 added
1Hello from the Frontend
added:tests/test_apps/blueprintapp/apps/frontend/__init__.py+13 added
1from flask import Blueprint, render_template23frontend = Blueprint('frontend', __name__, template_folder='templates')456@frontend.route('/')7def index():8 return render_template('frontend/index.html')91011@frontend.route('/missing')12def missing_template():13 return render_template('missing_template.html')
added:tests/test_apps/blueprintapp/apps/__init__.py
added:tests/test_apps/blueprintapp/__init__.py+8 added
1from flask import Flask23app = Flask(__name__)4app.config['DEBUG'] = True5from blueprintapp.apps.admin import admin6from blueprintapp.apps.frontend import frontend7app.register_blueprint(admin)8app.register_blueprint(frontend)
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')
added:tests/test_apps/subdomaintestmodule/static/hello.txt+1 added
1Hello Subdomain
added:tests/test_apps/subdomaintestmodule/__init__.py+4 added
1from flask import Module234mod = Module(__name__, 'foo', subdomain='foo')
added:tests/conftest.py+134 added
1# -*- coding: utf-8 -*-2"""3 tests.conftest4 ~~~~~~~~~~~~~~56 :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 textwrap161718@pytest.fixture19def test_apps(monkeypatch):20 monkeypatch.syspath_prepend(21 os.path.abspath(os.path.join(22 os.path.dirname(__file__), 'test_apps'))23 )2425@pytest.fixture(autouse=True)26def leak_detector(request):27 def ensure_clean_request_context():28 # make sure we're not leaking a request context since we are29 # testing flask internally in debug mode in a few cases30 leaks = []31 while flask._request_ctx_stack.top is not None:32 leaks.append(flask._request_ctx_stack.pop())33 assert leaks == []34 request.addfinalizer(ensure_clean_request_context)353637@pytest.fixture(params=(True, False))38def limit_loader(request, monkeypatch):39 """Patch pkgutil.get_loader to give loader without get_filename or archive.4041 This provides for tests where a system has custom loaders, e.g. Google App42 Engine's HardenedModulesHook, which have neither the `get_filename` method43 nor the `archive` attribute.4445 This fixture will run the testcase twice, once with and once without the46 limitation/mock.47 """48 if not request.param:49 return5051 class LimitedLoader(object):52 def __init__(self, loader):53 self.loader = loader5455 def __getattr__(self, name):56 if name in ('archive', 'get_filename'):57 msg = 'Mocking a loader which does not have `%s.`' % name58 raise AttributeError(msg)59 return getattr(self.loader, name)6061 old_get_loader = pkgutil.get_loader6263 def get_loader(*args, **kwargs):64 return LimitedLoader(old_get_loader(*args, **kwargs))65 monkeypatch.setattr(pkgutil, 'get_loader', get_loader)666768@pytest.fixture69def modules_tmpdir(tmpdir, monkeypatch):70 '''A tmpdir added to sys.path'''71 rv = tmpdir.mkdir('modules_tmpdir')72 monkeypatch.syspath_prepend(str(rv))73 return rv747576@pytest.fixture77def modules_tmpdir_prefix(modules_tmpdir, monkeypatch):78 monkeypatch.setattr(sys, 'prefix', str(modules_tmpdir))79 return modules_tmpdir808182@pytest.fixture83def site_packages(modules_tmpdir, monkeypatch):84 '''Create a fake site-packages'''85 rv = modules_tmpdir \86 .mkdir('lib')\87 .mkdir('python{x[0]}.{x[1]}'.format(x=sys.version_info))\88 .mkdir('site-packages')89 monkeypatch.syspath_prepend(str(rv))90 return rv919293@pytest.fixture94def install_egg(modules_tmpdir, monkeypatch):95 '''Generate egg from package name inside base and put the egg into96 sys.path'''97 def inner(name, base=modules_tmpdir):98 if not isinstance(name, str):99 raise ValueError(name)100 base.join(name).ensure_dir()101 base.join(name).join('__init__.py').ensure()102103 egg_setup = base.join('setup.py')104 egg_setup.write(textwrap.dedent("""105 from setuptools import setup106 setup(name='{0}',107 version='1.0',108 packages=['site_egg'],109 zip_safe=True)110 """.format(name)))111112 import subprocess113 subprocess.check_call(114 [sys.executable, 'setup.py', 'bdist_egg'],115 cwd=str(modules_tmpdir)116 )117 egg_path, = modules_tmpdir.join('dist/').listdir()118 monkeypatch.syspath_prepend(str(egg_path))119 return egg_path120 return inner121122123@pytest.fixture124def purge_module(request):125 def inner(name):126 request.addfinalizer(lambda: sys.modules.pop(name, None))127 return inner128129130@pytest.yield_fixture(autouse=True)131def catch_deprecation_warnings(recwarn):132 yield133 gc.collect()134 assert not recwarn.list
added:tests/test_appctx.py+170 added
1# -*- coding: utf-8 -*-2"""3 tests.appctx4 ~~~~~~~~~~~~56 Tests the application context.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1314import flask151617def test_basic_url_generation():18 app = flask.Flask(__name__)19 app.config['SERVER_NAME'] = 'localhost'20 app.config['PREFERRED_URL_SCHEME'] = 'https'2122 @app.route('/')23 def index():24 pass2526 with app.app_context():27 rv = flask.url_for('index')28 assert rv == 'https://localhost/'2930def test_url_generation_requires_server_name():31 app = flask.Flask(__name__)32 with app.app_context():33 with pytest.raises(RuntimeError):34 flask.url_for('index')3536def 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__)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__)48 with app.app_context():49 assert flask.current_app._get_current_object() == app50 assert flask._app_ctx_stack.top is None5152def test_app_tearing_down():53 cleanup_stuff = []54 app = flask.Flask(__name__)55 @app.teardown_appcontext56 def cleanup(exception):57 cleanup_stuff.append(exception)5859 with app.app_context():60 pass6162 assert cleanup_stuff == [None]6364def test_app_tearing_down_with_previous_exception():65 cleanup_stuff = []66 app = flask.Flask(__name__)67 @app.teardown_appcontext68 def cleanup(exception):69 cleanup_stuff.append(exception)7071 try:72 raise Exception('dummy')73 except Exception:74 pass7576 with app.app_context():77 pass7879 assert cleanup_stuff == [None]8081def test_app_tearing_down_with_handled_exception():82 cleanup_stuff = []83 app = flask.Flask(__name__)84 @app.teardown_appcontext85 def cleanup(exception):86 cleanup_stuff.append(exception)8788 with app.app_context():89 try:90 raise Exception('dummy')91 except Exception:92 pass9394 assert cleanup_stuff == [None]9596def test_app_ctx_globals_methods():97 app = flask.Flask(__name__)98 with app.app_context():99 # get100 assert flask.g.get('foo') is None101 assert flask.g.get('foo', 'bar') == 'bar'102 # __contains__103 assert 'foo' not in flask.g104 flask.g.foo = 'bar'105 assert 'foo' in flask.g106 # setdefault107 flask.g.setdefault('bar', 'the cake is a lie')108 flask.g.setdefault('bar', 'hello world')109 assert flask.g.bar == 'the cake is a lie'110 # pop111 assert flask.g.pop('bar') == 'the cake is a lie'112 with pytest.raises(KeyError):113 flask.g.pop('bar')114 assert flask.g.pop('bar', 'more cake') == 'more cake'115 # __iter__116 assert list(flask.g) == ['foo']117118def test_custom_app_ctx_globals_class():119 class CustomRequestGlobals(object):120 def __init__(self):121 self.spam = 'eggs'122 app = flask.Flask(__name__)123 app.app_ctx_globals_class = CustomRequestGlobals124 with app.app_context():125 assert flask.render_template_string('{{ g.spam }}') == 'eggs'126127def test_context_refcounts():128 called = []129 app = flask.Flask(__name__)130 @app.teardown_request131 def teardown_req(error=None):132 called.append('request')133 @app.teardown_appcontext134 def teardown_app(error=None):135 called.append('app')136 @app.route('/')137 def index():138 with flask._app_ctx_stack.top:139 with flask._request_ctx_stack.top:140 pass141 env = flask._request_ctx_stack.top.request.environ142 assert env['werkzeug.request'] is not None143 return u''144 c = app.test_client()145 res = c.get('/')146 assert res.status_code == 200147 assert res.data == b''148 assert called == ['request', 'app']149150151def test_clean_pop():152 called = []153 app = flask.Flask(__name__)154155 @app.teardown_request156 def teardown_req(error=None):157 1 / 0158159 @app.teardown_appcontext160 def teardown_app(error=None):161 called.append('TEARDOWN')162163 try:164 with app.test_request_context():165 called.append(flask.current_app.name)166 except ZeroDivisionError:167 pass168169 assert called == ['test_appctx', 'TEARDOWN']170 assert not flask.current_app
added:tests/test_basic.py+1924 added
1# -*- coding: utf-8 -*-2"""3 tests.basic4 ~~~~~~~~~~~~~~~~~~~~~56 The basic functionality.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1314import re15import uuid16import time17import flask18import pickle19from datetime import datetime20from threading import Thread21from flask._compat import text_type22from werkzeug.exceptions import BadRequest, NotFound, Forbidden23from werkzeug.http import parse_date24from werkzeug.routing import BuildError25import werkzeug.serving262728def test_options_work():29 app = flask.Flask(__name__)3031 @app.route('/', methods=['GET', 'POST'])32 def index():33 return 'Hello World'34 rv = app.test_client().open('/', method='OPTIONS')35 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']36 assert rv.data == b''373839def test_options_on_multiple_rules():40 app = flask.Flask(__name__)4142 @app.route('/', methods=['GET', 'POST'])43 def index():44 return 'Hello World'4546 @app.route('/', methods=['PUT'])47 def index_put():48 return 'Aha!'49 rv = app.test_client().open('/', method='OPTIONS')50 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']515253def test_provide_automatic_options_attr():54 app = flask.Flask(__name__)5556 def index():57 return 'Hello World!'58 index.provide_automatic_options = False59 app.route('/')(index)60 rv = app.test_client().open('/', method='OPTIONS')61 assert rv.status_code == 4056263 app = flask.Flask(__name__)6465 def index2():66 return 'Hello World!'67 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_provide_automatic_options_kwarg():74 app = flask.Flask(__name__)7576 def index():77 return flask.request.method7879 def more():80 return flask.request.method8182 app.add_url_rule('/', view_func=index, provide_automatic_options=False)83 app.add_url_rule(84 '/more', view_func=more, methods=['GET', 'POST'],85 provide_automatic_options=False86 )8788 c = app.test_client()89 assert c.get('/').data == b'GET'9091 rv = c.post('/')92 assert rv.status_code == 40593 assert sorted(rv.allow) == ['GET', 'HEAD']9495 # Older versions of Werkzeug.test.Client don't have an options method96 if hasattr(c, 'options'):97 rv = c.options('/')98 else:99 rv = c.open('/', method='OPTIONS')100101 assert rv.status_code == 405102103 rv = c.head('/')104 assert rv.status_code == 200105 assert not rv.data # head truncates106 assert c.post('/more').data == b'POST'107 assert c.get('/more').data == b'GET'108109 rv = c.delete('/more')110 assert rv.status_code == 405111 assert sorted(rv.allow) == ['GET', 'HEAD', 'POST']112113 if hasattr(c, 'options'):114 rv = c.options('/more')115 else:116 rv = c.open('/more', method='OPTIONS')117118 assert rv.status_code == 405119120121def test_request_dispatching():122 app = flask.Flask(__name__)123124 @app.route('/')125 def index():126 return flask.request.method127128 @app.route('/more', methods=['GET', 'POST'])129 def more():130 return flask.request.method131132 c = app.test_client()133 assert c.get('/').data == b'GET'134 rv = c.post('/')135 assert rv.status_code == 405136 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']137 rv = c.head('/')138 assert rv.status_code == 200139 assert not rv.data # head truncates140 assert c.post('/more').data == b'POST'141 assert c.get('/more').data == b'GET'142 rv = c.delete('/more')143 assert rv.status_code == 405144 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']145146147def test_disallow_string_for_allowed_methods():148 app = flask.Flask(__name__)149 with pytest.raises(TypeError):150 @app.route('/', methods='GET POST')151 def index():152 return "Hey"153154155def test_url_mapping():156 app = flask.Flask(__name__)157158 random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"159160 def index():161 return flask.request.method162163 def more():164 return flask.request.method165166 def options():167 return random_uuid4168169170 app.add_url_rule('/', 'index', index)171 app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])172173 # Issue 1288: Test that automatic options are not added when non-uppercase 'options' in methods174 app.add_url_rule('/options', 'options', options, methods=['options'])175176 c = app.test_client()177 assert c.get('/').data == b'GET'178 rv = c.post('/')179 assert rv.status_code == 405180 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']181 rv = c.head('/')182 assert rv.status_code == 200183 assert not rv.data # head truncates184 assert c.post('/more').data == b'POST'185 assert c.get('/more').data == b'GET'186 rv = c.delete('/more')187 assert rv.status_code == 405188 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']189 rv = c.open('/options', method='OPTIONS')190 assert rv.status_code == 200191 assert random_uuid4 in rv.data.decode("utf-8")192193194def test_werkzeug_routing():195 from werkzeug.routing import Submount, Rule196 app = flask.Flask(__name__)197 app.url_map.add(Submount('/foo', [198 Rule('/bar', endpoint='bar'),199 Rule('/', endpoint='index')200 ]))201202 def bar():203 return 'bar'204205 def index():206 return 'index'207 app.view_functions['bar'] = bar208 app.view_functions['index'] = index209210 c = app.test_client()211 assert c.get('/foo/').data == b'index'212 assert c.get('/foo/bar').data == b'bar'213214215def test_endpoint_decorator():216 from werkzeug.routing import Submount, Rule217 app = flask.Flask(__name__)218 app.url_map.add(Submount('/foo', [219 Rule('/bar', endpoint='bar'),220 Rule('/', endpoint='index')221 ]))222223 @app.endpoint('bar')224 def bar():225 return 'bar'226227 @app.endpoint('index')228 def index():229 return 'index'230231 c = app.test_client()232 assert c.get('/foo/').data == b'index'233 assert c.get('/foo/bar').data == b'bar'234235236def test_session():237 app = flask.Flask(__name__)238 app.secret_key = 'testkey'239240 @app.route('/set', methods=['POST'])241 def set():242 flask.session['value'] = flask.request.form['value']243 return 'value set'244245 @app.route('/get')246 def get():247 return flask.session['value']248249 c = app.test_client()250 assert c.post('/set', data={'value': '42'}).data == b'value set'251 assert c.get('/get').data == b'42'252253254def test_session_using_server_name():255 app = flask.Flask(__name__)256 app.config.update(257 SECRET_KEY='foo',258 SERVER_NAME='example.com'259 )260261 @app.route('/')262 def index():263 flask.session['testing'] = 42264 return 'Hello World'265 rv = app.test_client().get('/', 'http://example.com/')266 assert 'domain=.example.com' in rv.headers['set-cookie'].lower()267 assert 'httponly' in rv.headers['set-cookie'].lower()268269270def test_session_using_server_name_and_port():271 app = flask.Flask(__name__)272 app.config.update(273 SECRET_KEY='foo',274 SERVER_NAME='example.com:8080'275 )276277 @app.route('/')278 def index():279 flask.session['testing'] = 42280 return 'Hello World'281 rv = app.test_client().get('/', 'http://example.com:8080/')282 assert 'domain=.example.com' in rv.headers['set-cookie'].lower()283 assert 'httponly' in rv.headers['set-cookie'].lower()284285286def test_session_using_server_name_port_and_path():287 app = flask.Flask(__name__)288 app.config.update(289 SECRET_KEY='foo',290 SERVER_NAME='example.com:8080',291 APPLICATION_ROOT='/foo'292 )293294 @app.route('/')295 def index():296 flask.session['testing'] = 42297 return 'Hello World'298 rv = app.test_client().get('/', 'http://example.com:8080/foo')299 assert 'domain=example.com' in rv.headers['set-cookie'].lower()300 assert 'path=/foo' in rv.headers['set-cookie'].lower()301 assert 'httponly' in rv.headers['set-cookie'].lower()302303304def test_session_using_application_root():305 class PrefixPathMiddleware(object):306307 def __init__(self, app, prefix):308 self.app = app309 self.prefix = prefix310311 def __call__(self, environ, start_response):312 environ['SCRIPT_NAME'] = self.prefix313 return self.app(environ, start_response)314315 app = flask.Flask(__name__)316 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar')317 app.config.update(318 SECRET_KEY='foo',319 APPLICATION_ROOT='/bar'320 )321322 @app.route('/')323 def index():324 flask.session['testing'] = 42325 return 'Hello World'326 rv = app.test_client().get('/', 'http://example.com:8080/')327 assert 'path=/bar' in rv.headers['set-cookie'].lower()328329330def test_session_using_session_settings():331 app = flask.Flask(__name__)332 app.config.update(333 SECRET_KEY='foo',334 SERVER_NAME='www.example.com:8080',335 APPLICATION_ROOT='/test',336 SESSION_COOKIE_DOMAIN='.example.com',337 SESSION_COOKIE_HTTPONLY=False,338 SESSION_COOKIE_SECURE=True,339 SESSION_COOKIE_PATH='/'340 )341342 @app.route('/')343 def index():344 flask.session['testing'] = 42345 return 'Hello World'346 rv = app.test_client().get('/', 'http://www.example.com:8080/test/')347 cookie = rv.headers['set-cookie'].lower()348 assert 'domain=.example.com' in cookie349 assert 'path=/' in cookie350 assert 'secure' in cookie351 assert 'httponly' not in cookie352353354def test_session_localhost_warning(recwarn):355 app = flask.Flask(__name__)356 app.config.update(357 SECRET_KEY='testing',358 SERVER_NAME='localhost:5000',359 )360361 @app.route('/')362 def index():363 flask.session['testing'] = 42364 return 'testing'365366 rv = app.test_client().get('/', 'http://localhost:5000/')367 assert 'domain' not in rv.headers['set-cookie'].lower()368 w = recwarn.pop(UserWarning)369 assert '"localhost" is not a valid cookie domain' in str(w.message)370371372def test_session_ip_warning(recwarn):373 app = flask.Flask(__name__)374 app.config.update(375 SECRET_KEY='testing',376 SERVER_NAME='127.0.0.1:5000',377 )378379 @app.route('/')380 def index():381 flask.session['testing'] = 42382 return 'testing'383384 rv = app.test_client().get('/', 'http://127.0.0.1:5000/')385 assert 'domain=127.0.0.1' in rv.headers['set-cookie'].lower()386 w = recwarn.pop(UserWarning)387 assert 'cookie domain is an IP' in str(w.message)388389390def test_missing_session():391 app = flask.Flask(__name__)392393 def expect_exception(f, *args, **kwargs):394 e = pytest.raises(RuntimeError, f, *args, **kwargs)395 assert e.value.args and 'session is unavailable' in e.value.args[0]396 with app.test_request_context():397 assert flask.session.get('missing_key') is None398 expect_exception(flask.session.__setitem__, 'foo', 42)399 expect_exception(flask.session.pop, 'foo')400401402def test_session_expiration():403 permanent = True404 app = flask.Flask(__name__)405 app.secret_key = 'testkey'406407 @app.route('/')408 def index():409 flask.session['test'] = 42410 flask.session.permanent = permanent411 return ''412413 @app.route('/test')414 def test():415 return text_type(flask.session.permanent)416417 client = app.test_client()418 rv = client.get('/')419 assert 'set-cookie' in rv.headers420 match = re.search(r'(?i)\bexpires=([^;]+)', rv.headers['set-cookie'])421 expires = parse_date(match.group())422 expected = datetime.utcnow() + app.permanent_session_lifetime423 assert expires.year == expected.year424 assert expires.month == expected.month425 assert expires.day == expected.day426427 rv = client.get('/test')428 assert rv.data == b'True'429430 permanent = False431 rv = app.test_client().get('/')432 assert 'set-cookie' in rv.headers433 match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])434 assert match is None435436437def test_session_stored_last():438 app = flask.Flask(__name__)439 app.secret_key = 'development-key'440 app.testing = True441442 @app.after_request443 def modify_session(response):444 flask.session['foo'] = 42445 return response446447 @app.route('/')448 def dump_session_contents():449 return repr(flask.session.get('foo'))450451 c = app.test_client()452 assert c.get('/').data == b'None'453 assert c.get('/').data == b'42'454455456def test_session_special_types():457 app = flask.Flask(__name__)458 app.secret_key = 'development-key'459 app.testing = True460 now = datetime.utcnow().replace(microsecond=0)461 the_uuid = uuid.uuid4()462463 @app.after_request464 def modify_session(response):465 flask.session['m'] = flask.Markup('Hello!')466 flask.session['u'] = the_uuid467 flask.session['dt'] = now468 flask.session['b'] = b'\xff'469 flask.session['t'] = (1, 2, 3)470 return response471472 @app.route('/')473 def dump_session_contents():474 return pickle.dumps(dict(flask.session))475476 c = app.test_client()477 c.get('/')478 rv = pickle.loads(c.get('/').data)479 assert rv['m'] == flask.Markup('Hello!')480 assert type(rv['m']) == flask.Markup481 assert rv['dt'] == now482 assert rv['u'] == the_uuid483 assert rv['b'] == b'\xff'484 assert type(rv['b']) == bytes485 assert rv['t'] == (1, 2, 3)486487488def test_session_cookie_setting():489 app = flask.Flask(__name__)490 app.testing = True491 app.secret_key = 'dev key'492 is_permanent = True493494 @app.route('/bump')495 def bump():496 rv = flask.session['foo'] = flask.session.get('foo', 0) + 1497 flask.session.permanent = is_permanent498 return str(rv)499500 @app.route('/read')501 def read():502 return str(flask.session.get('foo', 0))503504 def run_test(expect_header):505 with app.test_client() as c:506 assert c.get('/bump').data == b'1'507 assert c.get('/bump').data == b'2'508 assert c.get('/bump').data == b'3'509510 rv = c.get('/read')511 set_cookie = rv.headers.get('set-cookie')512 assert (set_cookie is not None) == expect_header513 assert rv.data == b'3'514515 is_permanent = True516 app.config['SESSION_REFRESH_EACH_REQUEST'] = True517 run_test(expect_header=True)518519 is_permanent = True520 app.config['SESSION_REFRESH_EACH_REQUEST'] = False521 run_test(expect_header=False)522523 is_permanent = False524 app.config['SESSION_REFRESH_EACH_REQUEST'] = True525 run_test(expect_header=False)526527 is_permanent = False528 app.config['SESSION_REFRESH_EACH_REQUEST'] = False529 run_test(expect_header=False)530531532def test_session_vary_cookie():533 app = flask.Flask(__name__)534 app.secret_key = 'testkey'535536 @app.route('/set-session')537 def set_session():538 flask.session['test'] = 'test'539 return ''540541 @app.route('/get-session')542 def get_session():543 s = flask.session.get('test')544 return ''545546 @app.route('/get-session-with-dictionary')547 def get_session_with_dictionary():548 s = flask.session['test']549 return ''550551 @app.route('/no-vary-header')552 def no_vary_header():553 return ''554555 c = app.test_client()556557 rv = c.get('/set-session')558 assert rv.headers['Vary'] == 'Cookie'559560 rv = c.get('/get-session')561 assert rv.headers['Vary'] == 'Cookie'562563 rv = c.get('/get-session-with-dictionary')564 assert rv.headers['Vary'] == 'Cookie'565566 rv = c.get('/no-vary-header')567 assert 'Vary' not in rv.headers568569570def test_flashes():571 app = flask.Flask(__name__)572 app.secret_key = 'testkey'573574 with app.test_request_context():575 assert not flask.session.modified576 flask.flash('Zap')577 flask.session.modified = False578 flask.flash('Zip')579 assert flask.session.modified580 assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']581582583def test_extended_flashing():584 # Be sure app.testing=True below, else tests can fail silently.585 #586 # Specifically, if app.testing is not set to True, the AssertionErrors587 # in the view functions will cause a 500 response to the test client588 # instead of propagating exceptions.589590 app = flask.Flask(__name__)591 app.secret_key = 'testkey'592 app.testing = True593594 @app.route('/')595 def index():596 flask.flash(u'Hello World')597 flask.flash(u'Hello World', 'error')598 flask.flash(flask.Markup(u'<em>Testing</em>'), 'warning')599 return ''600601 @app.route('/test/')602 def test():603 messages = flask.get_flashed_messages()604 assert list(messages) == [605 u'Hello World',606 u'Hello World',607 flask.Markup(u'<em>Testing</em>')608 ]609 return ''610611 @app.route('/test_with_categories/')612 def test_with_categories():613 messages = flask.get_flashed_messages(with_categories=True)614 assert len(messages) == 3615 assert list(messages) == [616 ('message', u'Hello World'),617 ('error', u'Hello World'),618 ('warning', flask.Markup(u'<em>Testing</em>'))619 ]620 return ''621622 @app.route('/test_filter/')623 def test_filter():624 messages = flask.get_flashed_messages(625 category_filter=['message'], with_categories=True)626 assert list(messages) == [('message', u'Hello World')]627 return ''628629 @app.route('/test_filters/')630 def test_filters():631 messages = flask.get_flashed_messages(632 category_filter=['message', 'warning'], with_categories=True)633 assert list(messages) == [634 ('message', u'Hello World'),635 ('warning', flask.Markup(u'<em>Testing</em>'))636 ]637 return ''638639 @app.route('/test_filters_without_returning_categories/')640 def test_filters2():641 messages = flask.get_flashed_messages(642 category_filter=['message', 'warning'])643 assert len(messages) == 2644 assert messages[0] == u'Hello World'645 assert messages[1] == flask.Markup(u'<em>Testing</em>')646 return ''647648 # Create new test client on each test to clean flashed messages.649650 c = app.test_client()651 c.get('/')652 c.get('/test/')653654 c = app.test_client()655 c.get('/')656 c.get('/test_with_categories/')657658 c = app.test_client()659 c.get('/')660 c.get('/test_filter/')661662 c = app.test_client()663 c.get('/')664 c.get('/test_filters/')665666 c = app.test_client()667 c.get('/')668 c.get('/test_filters_without_returning_categories/')669670671def test_request_processing():672 app = flask.Flask(__name__)673 evts = []674675 @app.before_request676 def before_request():677 evts.append('before')678679 @app.after_request680 def after_request(response):681 response.data += b'|after'682 evts.append('after')683 return response684685 @app.route('/')686 def index():687 assert 'before' in evts688 assert 'after' not in evts689 return 'request'690 assert 'after' not in evts691 rv = app.test_client().get('/').data692 assert 'after' in evts693 assert rv == b'request|after'694695696def test_request_preprocessing_early_return():697 app = flask.Flask(__name__)698 evts = []699700 @app.before_request701 def before_request1():702 evts.append(1)703704 @app.before_request705 def before_request2():706 evts.append(2)707 return "hello"708709 @app.before_request710 def before_request3():711 evts.append(3)712 return "bye"713714 @app.route('/')715 def index():716 evts.append('index')717 return "damnit"718719 rv = app.test_client().get('/').data.strip()720 assert rv == b'hello'721 assert evts == [1, 2]722723724def test_after_request_processing():725 app = flask.Flask(__name__)726 app.testing = True727728 @app.route('/')729 def index():730 @flask.after_this_request731 def foo(response):732 response.headers['X-Foo'] = 'a header'733 return response734 return 'Test'735 c = app.test_client()736 resp = c.get('/')737 assert resp.status_code == 200738 assert resp.headers['X-Foo'] == 'a header'739740741def test_teardown_request_handler():742 called = []743 app = flask.Flask(__name__)744745 @app.teardown_request746 def teardown_request(exc):747 called.append(True)748 return "Ignored"749750 @app.route('/')751 def root():752 return "Response"753 rv = app.test_client().get('/')754 assert rv.status_code == 200755 assert b'Response' in rv.data756 assert len(called) == 1757758759def test_teardown_request_handler_debug_mode():760 called = []761 app = flask.Flask(__name__)762 app.testing = True763764 @app.teardown_request765 def teardown_request(exc):766 called.append(True)767 return "Ignored"768769 @app.route('/')770 def root():771 return "Response"772 rv = app.test_client().get('/')773 assert rv.status_code == 200774 assert b'Response' in rv.data775 assert len(called) == 1776777778def test_teardown_request_handler_error():779 called = []780 app = flask.Flask(__name__)781 app.config['LOGGER_HANDLER_POLICY'] = 'never'782783 @app.teardown_request784 def teardown_request1(exc):785 assert type(exc) == ZeroDivisionError786 called.append(True)787 # This raises a new error and blows away sys.exc_info(), so we can788 # test that all teardown_requests get passed the same original789 # exception.790 try:791 raise TypeError()792 except:793 pass794795 @app.teardown_request796 def teardown_request2(exc):797 assert type(exc) == ZeroDivisionError798 called.append(True)799 # This raises a new error and blows away sys.exc_info(), so we can800 # test that all teardown_requests get passed the same original801 # exception.802 try:803 raise TypeError()804 except:805 pass806807 @app.route('/')808 def fails():809 1 // 0810 rv = app.test_client().get('/')811 assert rv.status_code == 500812 assert b'Internal Server Error' in rv.data813 assert len(called) == 2814815816def test_before_after_request_order():817 called = []818 app = flask.Flask(__name__)819820 @app.before_request821 def before1():822 called.append(1)823824 @app.before_request825 def before2():826 called.append(2)827828 @app.after_request829 def after1(response):830 called.append(4)831 return response832833 @app.after_request834 def after2(response):835 called.append(3)836 return response837838 @app.teardown_request839 def finish1(exc):840 called.append(6)841842 @app.teardown_request843 def finish2(exc):844 called.append(5)845846 @app.route('/')847 def index():848 return '42'849 rv = app.test_client().get('/')850 assert rv.data == b'42'851 assert called == [1, 2, 3, 4, 5, 6]852853854def test_error_handling():855 app = flask.Flask(__name__)856 app.config['LOGGER_HANDLER_POLICY'] = 'never'857858 @app.errorhandler(404)859 def not_found(e):860 return 'not found', 404861862 @app.errorhandler(500)863 def internal_server_error(e):864 return 'internal server error', 500865866 @app.errorhandler(Forbidden)867 def forbidden(e):868 return 'forbidden', 403869870 @app.route('/')871 def index():872 flask.abort(404)873874 @app.route('/error')875 def error():876 1 // 0877878 @app.route('/forbidden')879 def error2():880 flask.abort(403)881 c = app.test_client()882 rv = c.get('/')883 assert rv.status_code == 404884 assert rv.data == b'not found'885 rv = c.get('/error')886 assert rv.status_code == 500887 assert b'internal server error' == rv.data888 rv = c.get('/forbidden')889 assert rv.status_code == 403890 assert b'forbidden' == rv.data891892893def test_error_handling_processing():894 app = flask.Flask(__name__)895 app.config['LOGGER_HANDLER_POLICY'] = 'never'896897 @app.errorhandler(500)898 def internal_server_error(e):899 return 'internal server error', 500900901 @app.route('/')902 def broken_func():903 1 // 0904905 @app.after_request906 def after_request(resp):907 resp.mimetype = 'text/x-special'908 return resp909910 with app.test_client() as c:911 resp = c.get('/')912 assert resp.mimetype == 'text/x-special'913 assert resp.data == b'internal server error'914915916def test_baseexception_error_handling():917 app = flask.Flask(__name__)918 app.config['LOGGER_HANDLER_POLICY'] = 'never'919920 @app.route('/')921 def broken_func():922 raise KeyboardInterrupt()923924 with app.test_client() as c:925 with pytest.raises(KeyboardInterrupt):926 c.get('/')927928 ctx = flask._request_ctx_stack.top929 assert ctx.preserved930 assert type(ctx._preserved_exc) is KeyboardInterrupt931932933def test_before_request_and_routing_errors():934 app = flask.Flask(__name__)935936 @app.before_request937 def attach_something():938 flask.g.something = 'value'939940 @app.errorhandler(404)941 def return_something(error):942 return flask.g.something, 404943 rv = app.test_client().get('/')944 assert rv.status_code == 404945 assert rv.data == b'value'946947948def test_user_error_handling():949 class MyException(Exception):950 pass951952 app = flask.Flask(__name__)953954 @app.errorhandler(MyException)955 def handle_my_exception(e):956 assert isinstance(e, MyException)957 return '42'958959 @app.route('/')960 def index():961 raise MyException()962963 c = app.test_client()964 assert c.get('/').data == b'42'965966967def test_http_error_subclass_handling():968 class ForbiddenSubclass(Forbidden):969 pass970971 app = flask.Flask(__name__)972973 @app.errorhandler(ForbiddenSubclass)974 def handle_forbidden_subclass(e):975 assert isinstance(e, ForbiddenSubclass)976 return 'banana'977978 @app.errorhandler(403)979 def handle_forbidden_subclass(e):980 assert not isinstance(e, ForbiddenSubclass)981 assert isinstance(e, Forbidden)982 return 'apple'983984 @app.route('/1')985 def index1():986 raise ForbiddenSubclass()987988 @app.route('/2')989 def index2():990 flask.abort(403)991992 @app.route('/3')993 def index3():994 raise Forbidden()995996 c = app.test_client()997 assert c.get('/1').data == b'banana'998 assert c.get('/2').data == b'apple'999 assert c.get('/3').data == b'apple'100010011002def test_trapping_of_bad_request_key_errors():1003 app = flask.Flask(__name__)1004 app.testing = True10051006 @app.route('/fail')1007 def fail():1008 flask.request.form['missing_key']1009 c = app.test_client()1010 assert c.get('/fail').status_code == 40010111012 app.config['TRAP_BAD_REQUEST_ERRORS'] = True1013 c = app.test_client()1014 with pytest.raises(KeyError) as e:1015 c.get("/fail")1016 assert e.errisinstance(BadRequest)101710181019def test_trapping_of_all_http_exceptions():1020 app = flask.Flask(__name__)1021 app.testing = True1022 app.config['TRAP_HTTP_EXCEPTIONS'] = True10231024 @app.route('/fail')1025 def fail():1026 flask.abort(404)10271028 c = app.test_client()1029 with pytest.raises(NotFound):1030 c.get('/fail')103110321033def test_enctype_debug_helper():1034 from flask.debughelpers import DebugFilesKeyError1035 app = flask.Flask(__name__)1036 app.debug = True10371038 @app.route('/fail', methods=['POST'])1039 def index():1040 return flask.request.files['foo'].filename10411042 # with statement is important because we leave an exception on the1043 # stack otherwise and we want to ensure that this is not the case1044 # to not negatively affect other tests.1045 with app.test_client() as c:1046 with pytest.raises(DebugFilesKeyError) as e:1047 c.post('/fail', data={'foo': 'index.txt'})1048 assert 'no file contents were transmitted' in str(e.value)1049 assert 'This was submitted: "index.txt"' in str(e.value)105010511052def test_response_types():1053 app = flask.Flask(__name__)1054 app.testing = True10551056 @app.route('/text')1057 def from_text():1058 return u'Hällo Wörld'10591060 @app.route('/bytes')1061 def from_bytes():1062 return u'Hällo Wörld'.encode('utf-8')10631064 @app.route('/full_tuple')1065 def from_full_tuple():1066 return 'Meh', 400, {1067 'X-Foo': 'Testing',1068 'Content-Type': 'text/plain; charset=utf-8'1069 }10701071 @app.route('/text_headers')1072 def from_text_headers():1073 return 'Hello', {1074 'X-Foo': 'Test',1075 'Content-Type': 'text/plain; charset=utf-8'1076 }10771078 @app.route('/text_status')1079 def from_text_status():1080 return 'Hi, status!', 40010811082 @app.route('/response_headers')1083 def from_response_headers():1084 return flask.Response('Hello world', 404, {'X-Foo': 'Baz'}), {1085 "X-Foo": "Bar",1086 "X-Bar": "Foo"1087 }10881089 @app.route('/response_status')1090 def from_response_status():1091 return app.response_class('Hello world', 400), 50010921093 @app.route('/wsgi')1094 def from_wsgi():1095 return NotFound()10961097 c = app.test_client()10981099 assert c.get('/text').data == u'Hällo Wörld'.encode('utf-8')1100 assert c.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')11011102 rv = c.get('/full_tuple')1103 assert rv.data == b'Meh'1104 assert rv.headers['X-Foo'] == 'Testing'1105 assert rv.status_code == 4001106 assert rv.mimetype == 'text/plain'11071108 rv = c.get('/text_headers')1109 assert rv.data == b'Hello'1110 assert rv.headers['X-Foo'] == 'Test'1111 assert rv.status_code == 2001112 assert rv.mimetype == 'text/plain'11131114 rv = c.get('/text_status')1115 assert rv.data == b'Hi, status!'1116 assert rv.status_code == 4001117 assert rv.mimetype == 'text/html'11181119 rv = c.get('/response_headers')1120 assert rv.data == b'Hello world'1121 assert rv.headers.getlist('X-Foo') == ['Baz', 'Bar']1122 assert rv.headers['X-Bar'] == 'Foo'1123 assert rv.status_code == 40411241125 rv = c.get('/response_status')1126 assert rv.data == b'Hello world'1127 assert rv.status_code == 50011281129 rv = c.get('/wsgi')1130 assert b'Not Found' in rv.data1131 assert rv.status_code == 404113211331134def test_response_type_errors():1135 app = flask.Flask(__name__)1136 app.testing = True11371138 @app.route('/none')1139 def from_none():1140 pass11411142 @app.route('/small_tuple')1143 def from_small_tuple():1144 return 'Hello',11451146 @app.route('/large_tuple')1147 def from_large_tuple():1148 return 'Hello', 234, {'X-Foo': 'Bar'}, '???'11491150 @app.route('/bad_type')1151 def from_bad_type():1152 return True11531154 @app.route('/bad_wsgi')1155 def from_bad_wsgi():1156 return lambda: None11571158 c = app.test_client()11591160 with pytest.raises(TypeError) as e:1161 c.get('/none')1162 assert 'returned None' in str(e)11631164 with pytest.raises(TypeError) as e:1165 c.get('/small_tuple')1166 assert 'tuple must have the form' in str(e)11671168 pytest.raises(TypeError, c.get, '/large_tuple')11691170 with pytest.raises(TypeError) as e:1171 c.get('/bad_type')1172 assert 'it was a bool' in str(e)11731174 pytest.raises(TypeError, c.get, '/bad_wsgi')117511761177def test_make_response():1178 app = flask.Flask(__name__)1179 with app.test_request_context():1180 rv = flask.make_response()1181 assert rv.status_code == 2001182 assert rv.data == b''1183 assert rv.mimetype == 'text/html'11841185 rv = flask.make_response('Awesome')1186 assert rv.status_code == 2001187 assert rv.data == b'Awesome'1188 assert rv.mimetype == 'text/html'11891190 rv = flask.make_response('W00t', 404)1191 assert rv.status_code == 4041192 assert rv.data == b'W00t'1193 assert rv.mimetype == 'text/html'119411951196def test_make_response_with_response_instance():1197 app = flask.Flask(__name__)1198 with app.test_request_context():1199 rv = flask.make_response(1200 flask.jsonify({'msg': 'W00t'}), 400)1201 assert rv.status_code == 4001202 assert rv.data == b'{"msg":"W00t"}\n'1203 assert rv.mimetype == 'application/json'12041205 rv = flask.make_response(1206 flask.Response(''), 400)1207 assert rv.status_code == 4001208 assert rv.data == b''1209 assert rv.mimetype == 'text/html'12101211 rv = flask.make_response(1212 flask.Response('', headers={'Content-Type': 'text/html'}),1213 400, [('X-Foo', 'bar')])1214 assert rv.status_code == 4001215 assert rv.headers['Content-Type'] == 'text/html'1216 assert rv.headers['X-Foo'] == 'bar'121712181219def test_jsonify_no_prettyprint():1220 app = flask.Flask(__name__)1221 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1222 with app.test_request_context():1223 compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1224 uncompressed_msg = {1225 "msg": {1226 "submsg": "W00t"1227 },1228 "msg2": "foobar"1229 }12301231 rv = flask.make_response(1232 flask.jsonify(uncompressed_msg), 200)1233 assert rv.data == compressed_msg123412351236def test_jsonify_prettyprint():1237 app = flask.Flask(__name__)1238 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1239 with app.test_request_context():1240 compressed_msg = {"msg":{"submsg":"W00t"},"msg2":"foobar"}1241 pretty_response =\1242 b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'12431244 rv = flask.make_response(1245 flask.jsonify(compressed_msg), 200)1246 assert rv.data == pretty_response124712481249def test_jsonify_mimetype():1250 app = flask.Flask(__name__)1251 app.config.update({"JSONIFY_MIMETYPE": 'application/vnd.api+json'})1252 with app.test_request_context():1253 msg = {1254 "msg": {"submsg": "W00t"},1255 }1256 rv = flask.make_response(1257 flask.jsonify(msg), 200)1258 assert rv.mimetype == 'application/vnd.api+json'125912601261def test_jsonify_args_and_kwargs_check():1262 app = flask.Flask(__name__)1263 with app.test_request_context():1264 with pytest.raises(TypeError) as e:1265 flask.jsonify('fake args', kwargs='fake')1266 assert 'behavior undefined' in str(e.value)126712681269def test_url_generation():1270 app = flask.Flask(__name__)12711272 @app.route('/hello/<name>', methods=['POST'])1273 def hello():1274 pass1275 with app.test_request_context():1276 assert flask.url_for('hello', name='test x') == '/hello/test%20x'1277 assert flask.url_for('hello', name='test x', _external=True) == \1278 'http://localhost/hello/test%20x'127912801281def test_build_error_handler():1282 app = flask.Flask(__name__)12831284 # Test base case, a URL which results in a BuildError.1285 with app.test_request_context():1286 pytest.raises(BuildError, flask.url_for, 'spam')12871288 # Verify the error is re-raised if not the current exception.1289 try:1290 with app.test_request_context():1291 flask.url_for('spam')1292 except BuildError as err:1293 error = err1294 try:1295 raise RuntimeError('Test case where BuildError is not current.')1296 except RuntimeError:1297 pytest.raises(1298 BuildError, app.handle_url_build_error, error, 'spam', {})12991300 # Test a custom handler.1301 def handler(error, endpoint, values):1302 # Just a test.1303 return '/test_handler/'1304 app.url_build_error_handlers.append(handler)1305 with app.test_request_context():1306 assert flask.url_for('spam') == '/test_handler/'130713081309def test_build_error_handler_reraise():1310 app = flask.Flask(__name__)13111312 # Test a custom handler which reraises the BuildError1313 def handler_raises_build_error(error, endpoint, values):1314 raise error1315 app.url_build_error_handlers.append(handler_raises_build_error)13161317 with app.test_request_context():1318 pytest.raises(BuildError, flask.url_for, 'not.existing')131913201321def test_url_for_passes_special_values_to_build_error_handler():1322 app = flask.Flask(__name__)13231324 @app.url_build_error_handlers.append1325 def handler(error, endpoint, values):1326 assert values == {1327 '_external': False,1328 '_anchor': None,1329 '_method': None,1330 '_scheme': None,1331 }1332 return 'handled'13331334 with app.test_request_context():1335 flask.url_for('/')133613371338def test_custom_converters():1339 from werkzeug.routing import BaseConverter13401341 class ListConverter(BaseConverter):13421343 def to_python(self, value):1344 return value.split(',')13451346 def to_url(self, value):1347 base_to_url = super(ListConverter, self).to_url1348 return ','.join(base_to_url(x) for x in value)1349 app = flask.Flask(__name__)1350 app.url_map.converters['list'] = ListConverter13511352 @app.route('/<list:args>')1353 def index(args):1354 return '|'.join(args)1355 c = app.test_client()1356 assert c.get('/1,2,3').data == b'1|2|3'135713581359def test_static_files():1360 app = flask.Flask(__name__)1361 app.testing = True1362 rv = app.test_client().get('/static/index.html')1363 assert rv.status_code == 2001364 assert rv.data.strip() == b'<h1>Hello World!</h1>'1365 with app.test_request_context():1366 assert flask.url_for('static', filename='index.html') == \1367 '/static/index.html'1368 rv.close()136913701371def test_static_path_deprecated(recwarn):1372 app = flask.Flask(__name__, static_path='/foo')1373 recwarn.pop(DeprecationWarning)13741375 app.testing = True1376 rv = app.test_client().get('/foo/index.html')1377 assert rv.status_code == 2001378 rv.close()13791380 with app.test_request_context():1381 assert flask.url_for('static', filename='index.html') == '/foo/index.html'138213831384def test_static_url_path():1385 app = flask.Flask(__name__, static_url_path='/foo')1386 app.testing = True1387 rv = app.test_client().get('/foo/index.html')1388 assert rv.status_code == 2001389 rv.close()13901391 with app.test_request_context():1392 assert flask.url_for('static', filename='index.html') == '/foo/index.html'139313941395def test_static_route_with_host_matching():1396 app = flask.Flask(__name__, host_matching=True, static_host='example.com')1397 c = app.test_client()1398 rv = c.get('http://example.com/static/index.html')1399 assert rv.status_code == 2001400 rv.close()1401 with app.test_request_context():1402 rv = flask.url_for('static', filename='index.html', _external=True)1403 assert rv == 'http://example.com/static/index.html'1404 # Providing static_host without host_matching=True should error.1405 with pytest.raises(Exception):1406 flask.Flask(__name__, static_host='example.com')1407 # Providing host_matching=True with static_folder but without static_host should error.1408 with pytest.raises(Exception):1409 flask.Flask(__name__, host_matching=True)1410 # Providing host_matching=True without static_host but with static_folder=None should not error.1411 flask.Flask(__name__, host_matching=True, static_folder=None)141214131414def test_request_locals():1415 assert repr(flask.g) == '<LocalProxy unbound>'1416 assert not flask.g141714181419def test_test_app_proper_environ():1420 app = flask.Flask(__name__)1421 app.config.update(1422 SERVER_NAME='localhost.localdomain:5000'1423 )14241425 @app.route('/')1426 def index():1427 return 'Foo'14281429 @app.route('/', subdomain='foo')1430 def subdomain():1431 return 'Foo SubDomain'14321433 rv = app.test_client().get('/')1434 assert rv.data == b'Foo'14351436 rv = app.test_client().get('/', 'http://localhost.localdomain:5000')1437 assert rv.data == b'Foo'14381439 rv = app.test_client().get('/', 'https://localhost.localdomain:5000')1440 assert rv.data == b'Foo'14411442 app.config.update(SERVER_NAME='localhost.localdomain')1443 rv = app.test_client().get('/', 'https://localhost.localdomain')1444 assert rv.data == b'Foo'14451446 try:1447 app.config.update(SERVER_NAME='localhost.localdomain:443')1448 rv = app.test_client().get('/', 'https://localhost.localdomain')1449 # Werkzeug 0.81450 assert rv.status_code == 4041451 except ValueError as e:1452 # Werkzeug 0.71453 assert str(e) == (1454 "the server name provided "1455 "('localhost.localdomain:443') does not match the "1456 "server name from the WSGI environment ('localhost.localdomain')"1457 )14581459 try:1460 app.config.update(SERVER_NAME='localhost.localdomain')1461 rv = app.test_client().get('/', 'http://foo.localhost')1462 # Werkzeug 0.81463 assert rv.status_code == 4041464 except ValueError as e:1465 # Werkzeug 0.71466 assert str(e) == (1467 "the server name provided "1468 "('localhost.localdomain') does not match the "1469 "server name from the WSGI environment ('foo.localhost')"1470 )14711472 rv = app.test_client().get('/', 'http://foo.localhost.localdomain')1473 assert rv.data == b'Foo SubDomain'147414751476def test_exception_propagation():1477 def apprunner(config_key):1478 app = flask.Flask(__name__)1479 app.config['LOGGER_HANDLER_POLICY'] = 'never'14801481 @app.route('/')1482 def index():1483 1 // 01484 c = app.test_client()1485 if config_key is not None:1486 app.config[config_key] = True1487 with pytest.raises(Exception):1488 c.get('/')1489 else:1490 assert c.get('/').status_code == 50014911492 # we have to run this test in an isolated thread because if the1493 # debug flag is set to true and an exception happens the context is1494 # not torn down. This causes other tests that run after this fail1495 # when they expect no exception on the stack.1496 for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None:1497 t = Thread(target=apprunner, args=(config_key,))1498 t.start()1499 t.join()150015011502@pytest.mark.parametrize('debug', [True, False])1503@pytest.mark.parametrize('use_debugger', [True, False])1504@pytest.mark.parametrize('use_reloader', [True, False])1505@pytest.mark.parametrize('propagate_exceptions', [None, True, False])1506def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1507 use_reloader, propagate_exceptions):1508 rv = {}15091510 # Mocks werkzeug.serving.run_simple method1511 def run_simple_mock(*args, **kwargs):1512 rv['passthrough_errors'] = kwargs.get('passthrough_errors')15131514 app = flask.Flask(__name__)1515 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1516 app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1517 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)151815191520def test_max_content_length():1521 app = flask.Flask(__name__)1522 app.config['MAX_CONTENT_LENGTH'] = 6415231524 @app.before_request1525 def always_first():1526 flask.request.form['myfile']1527 assert False15281529 @app.route('/accept', methods=['POST'])1530 def accept_file():1531 flask.request.form['myfile']1532 assert False15331534 @app.errorhandler(413)1535 def catcher(error):1536 return '42'15371538 c = app.test_client()1539 rv = c.post('/accept', data={'myfile': 'foo' * 100})1540 assert rv.data == b'42'154115421543def test_url_processors():1544 app = flask.Flask(__name__)15451546 @app.url_defaults1547 def add_language_code(endpoint, values):1548 if flask.g.lang_code is not None and \1549 app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1550 values.setdefault('lang_code', flask.g.lang_code)15511552 @app.url_value_preprocessor1553 def pull_lang_code(endpoint, values):1554 flask.g.lang_code = values.pop('lang_code', None)15551556 @app.route('/<lang_code>/')1557 def index():1558 return flask.url_for('about')15591560 @app.route('/<lang_code>/about')1561 def about():1562 return flask.url_for('something_else')15631564 @app.route('/foo')1565 def something_else():1566 return flask.url_for('about', lang_code='en')15671568 c = app.test_client()15691570 assert c.get('/de/').data == b'/de/about'1571 assert c.get('/de/about').data == b'/foo'1572 assert c.get('/foo').data == b'/en/about'157315741575def test_inject_blueprint_url_defaults():1576 app = flask.Flask(__name__)1577 bp = flask.Blueprint('foo.bar.baz', __name__,1578 template_folder='template')15791580 @bp.url_defaults1581 def bp_defaults(endpoint, values):1582 values['page'] = 'login'15831584 @bp.route('/<page>')1585 def view(page):1586 pass15871588 app.register_blueprint(bp)15891590 values = dict()1591 app.inject_url_defaults('foo.bar.baz.view', values)1592 expected = dict(page='login')1593 assert values == expected15941595 with app.test_request_context('/somepage'):1596 url = flask.url_for('foo.bar.baz.view')1597 expected = '/login'1598 assert url == expected159916001601def test_nonascii_pathinfo():1602 app = flask.Flask(__name__)1603 app.testing = True16041605 @app.route(u'/киртест')1606 def index():1607 return 'Hello World!'16081609 c = app.test_client()1610 rv = c.get(u'/киртест')1611 assert rv.data == b'Hello World!'161216131614def test_debug_mode_complains_after_first_request():1615 app = flask.Flask(__name__)1616 app.debug = True16171618 @app.route('/')1619 def index():1620 return 'Awesome'1621 assert not app.got_first_request1622 assert app.test_client().get('/').data == b'Awesome'1623 with pytest.raises(AssertionError) as e:1624 @app.route('/foo')1625 def broken():1626 return 'Meh'1627 assert 'A setup function was called' in str(e)16281629 app.debug = False16301631 @app.route('/foo')1632 def working():1633 return 'Meh'1634 assert app.test_client().get('/foo').data == b'Meh'1635 assert app.got_first_request163616371638def test_before_first_request_functions():1639 got = []1640 app = flask.Flask(__name__)16411642 @app.before_first_request1643 def foo():1644 got.append(42)1645 c = app.test_client()1646 c.get('/')1647 assert got == [42]1648 c.get('/')1649 assert got == [42]1650 assert app.got_first_request165116521653def test_before_first_request_functions_concurrent():1654 got = []1655 app = flask.Flask(__name__)16561657 @app.before_first_request1658 def foo():1659 time.sleep(0.2)1660 got.append(42)16611662 c = app.test_client()16631664 def get_and_assert():1665 c.get("/")1666 assert got == [42]16671668 t = Thread(target=get_and_assert)1669 t.start()1670 get_and_assert()1671 t.join()1672 assert app.got_first_request167316741675def test_routing_redirect_debugging():1676 app = flask.Flask(__name__)1677 app.debug = True16781679 @app.route('/foo/', methods=['GET', 'POST'])1680 def foo():1681 return 'success'1682 with app.test_client() as c:1683 with pytest.raises(AssertionError) as e:1684 c.post('/foo', data={})1685 assert 'http://localhost/foo/' in str(e)1686 assert ('Make sure to directly send '1687 'your POST-request to this URL') in str(e)16881689 rv = c.get('/foo', data={}, follow_redirects=True)1690 assert rv.data == b'success'16911692 app.debug = False1693 with app.test_client() as c:1694 rv = c.post('/foo', data={}, follow_redirects=True)1695 assert rv.data == b'success'169616971698def test_route_decorator_custom_endpoint():1699 app = flask.Flask(__name__)1700 app.debug = True17011702 @app.route('/foo/')1703 def foo():1704 return flask.request.endpoint17051706 @app.route('/bar/', endpoint='bar')1707 def for_bar():1708 return flask.request.endpoint17091710 @app.route('/bar/123', endpoint='123')1711 def for_bar_foo():1712 return flask.request.endpoint17131714 with app.test_request_context():1715 assert flask.url_for('foo') == '/foo/'1716 assert flask.url_for('bar') == '/bar/'1717 assert flask.url_for('123') == '/bar/123'17181719 c = app.test_client()1720 assert c.get('/foo/').data == b'foo'1721 assert c.get('/bar/').data == b'bar'1722 assert c.get('/bar/123').data == b'123'172317241725def test_preserve_only_once():1726 app = flask.Flask(__name__)1727 app.debug = True17281729 @app.route('/fail')1730 def fail_func():1731 1 // 017321733 c = app.test_client()1734 for x in range(3):1735 with pytest.raises(ZeroDivisionError):1736 c.get('/fail')17371738 assert flask._request_ctx_stack.top is not None1739 assert flask._app_ctx_stack.top is not None1740 # implicit appctx disappears too1741 flask._request_ctx_stack.top.pop()1742 assert flask._request_ctx_stack.top is None1743 assert flask._app_ctx_stack.top is None174417451746def test_preserve_remembers_exception():1747 app = flask.Flask(__name__)1748 app.debug = True1749 errors = []17501751 @app.route('/fail')1752 def fail_func():1753 1 // 017541755 @app.route('/success')1756 def success_func():1757 return 'Okay'17581759 @app.teardown_request1760 def teardown_handler(exc):1761 errors.append(exc)17621763 c = app.test_client()17641765 # After this failure we did not yet call the teardown handler1766 with pytest.raises(ZeroDivisionError):1767 c.get('/fail')1768 assert errors == []17691770 # But this request triggers it, and it's an error1771 c.get('/success')1772 assert len(errors) == 21773 assert isinstance(errors[0], ZeroDivisionError)17741775 # At this point another request does nothing.1776 c.get('/success')1777 assert len(errors) == 31778 assert errors[1] is None177917801781def test_get_method_on_g():1782 app = flask.Flask(__name__)1783 app.testing = True17841785 with app.app_context():1786 assert flask.g.get('x') is None1787 assert flask.g.get('x', 11) == 111788 flask.g.x = 421789 assert flask.g.get('x') == 421790 assert flask.g.x == 42179117921793def test_g_iteration_protocol():1794 app = flask.Flask(__name__)1795 app.testing = True17961797 with app.app_context():1798 flask.g.foo = 231799 flask.g.bar = 421800 assert 'foo' in flask.g1801 assert 'foos' not in flask.g1802 assert sorted(flask.g) == ['bar', 'foo']180318041805def test_subdomain_basic_support():1806 app = flask.Flask(__name__)1807 app.config['SERVER_NAME'] = 'localhost'18081809 @app.route('/')1810 def normal_index():1811 return 'normal index'18121813 @app.route('/', subdomain='test')1814 def test_index():1815 return 'test index'18161817 c = app.test_client()1818 rv = c.get('/', 'http://localhost/')1819 assert rv.data == b'normal index'18201821 rv = c.get('/', 'http://test.localhost/')1822 assert rv.data == b'test index'182318241825def test_subdomain_matching():1826 app = flask.Flask(__name__)1827 app.config['SERVER_NAME'] = 'localhost'18281829 @app.route('/', subdomain='<user>')1830 def index(user):1831 return 'index for %s' % user18321833 c = app.test_client()1834 rv = c.get('/', 'http://mitsuhiko.localhost/')1835 assert rv.data == b'index for mitsuhiko'183618371838def test_subdomain_matching_with_ports():1839 app = flask.Flask(__name__)1840 app.config['SERVER_NAME'] = 'localhost:3000'18411842 @app.route('/', subdomain='<user>')1843 def index(user):1844 return 'index for %s' % user18451846 c = app.test_client()1847 rv = c.get('/', 'http://mitsuhiko.localhost:3000/')1848 assert rv.data == b'index for mitsuhiko'184918501851def test_multi_route_rules():1852 app = flask.Flask(__name__)18531854 @app.route('/')1855 @app.route('/<test>/')1856 def index(test='a'):1857 return test18581859 rv = app.test_client().open('/')1860 assert rv.data == b'a'1861 rv = app.test_client().open('/b/')1862 assert rv.data == b'b'186318641865def test_multi_route_class_views():1866 class View(object):18671868 def __init__(self, app):1869 app.add_url_rule('/', 'index', self.index)1870 app.add_url_rule('/<test>/', 'index', self.index)18711872 def index(self, test='a'):1873 return test18741875 app = flask.Flask(__name__)1876 _ = View(app)1877 rv = app.test_client().open('/')1878 assert rv.data == b'a'1879 rv = app.test_client().open('/b/')1880 assert rv.data == b'b'188118821883def test_run_defaults(monkeypatch):1884 rv = {}18851886 # Mocks werkzeug.serving.run_simple method1887 def run_simple_mock(*args, **kwargs):1888 rv['result'] = 'running...'18891890 app = flask.Flask(__name__)1891 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1892 app.run()1893 assert rv['result'] == 'running...'189418951896def test_run_server_port(monkeypatch):1897 rv = {}18981899 # Mocks werkzeug.serving.run_simple method1900 def run_simple_mock(hostname, port, application, *args, **kwargs):1901 rv['result'] = 'running on %s:%s ...' % (hostname, port)19021903 app = flask.Flask(__name__)1904 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1905 hostname, port = 'localhost', 80001906 app.run(hostname, port, debug=True)1907 assert rv['result'] == 'running on %s:%s ...' % (hostname, port)190819091910@pytest.mark.parametrize('host,port,expect_host,expect_port', (1911 (None, None, 'pocoo.org', 8080),1912 ('localhost', None, 'localhost', 8080),1913 (None, 80, 'pocoo.org', 80),1914 ('localhost', 80, 'localhost', 80),1915))1916def test_run_from_config(monkeypatch, host, port, expect_host, expect_port):1917 def run_simple_mock(hostname, port, *args, **kwargs):1918 assert hostname == expect_host1919 assert port == expect_port19201921 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1922 app = flask.Flask(__name__)1923 app.config['SERVER_NAME'] = 'pocoo.org:8080'1924 app.run(host, port)
added:tests/test_blueprints.py+593 added
1# -*- coding: utf-8 -*-2"""3 tests.blueprints4 ~~~~~~~~~~~~~~~~56 Blueprints (and currently modules)78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1314import flask1516from flask._compat import text_type17from werkzeug.http import parse_cache_control_header18from jinja2 import TemplateNotFound192021def test_blueprint_specific_error_handling():22 frontend = flask.Blueprint('frontend', __name__)23 backend = flask.Blueprint('backend', __name__)24 sideend = flask.Blueprint('sideend', __name__)2526 @frontend.errorhandler(403)27 def frontend_forbidden(e):28 return 'frontend says no', 4032930 @frontend.route('/frontend-no')31 def frontend_no():32 flask.abort(403)3334 @backend.errorhandler(403)35 def backend_forbidden(e):36 return 'backend says no', 4033738 @backend.route('/backend-no')39 def backend_no():40 flask.abort(403)4142 @sideend.route('/what-is-a-sideend')43 def sideend_no():44 flask.abort(403)4546 app = flask.Flask(__name__)47 app.register_blueprint(frontend)48 app.register_blueprint(backend)49 app.register_blueprint(sideend)5051 @app.errorhandler(403)52 def app_forbidden(e):53 return 'application itself says no', 4035455 c = app.test_client()5657 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'6061def test_blueprint_specific_user_error_handling():62 class MyDecoratorException(Exception):63 pass64 class MyFunctionException(Exception):65 pass6667 blue = flask.Blueprint('blue', __name__)6869 @blue.errorhandler(MyDecoratorException)70 def my_decorator_exception_handler(e):71 assert isinstance(e, MyDecoratorException)72 return 'boom'7374 def my_function_exception_handler(e):75 assert isinstance(e, MyFunctionException)76 return 'bam'77 blue.register_error_handler(MyFunctionException, my_function_exception_handler)7879 @blue.route('/decorator')80 def blue_deco_test():81 raise MyDecoratorException()82 @blue.route('/function')83 def blue_func_test():84 raise MyFunctionException()8586 app = flask.Flask(__name__)87 app.register_blueprint(blue)8889 c = app.test_client()9091 assert c.get('/decorator').data == b'boom'92 assert c.get('/function').data == b'bam'9394def test_blueprint_url_definitions():95 bp = flask.Blueprint('test', __name__)9697 @bp.route('/foo', defaults={'baz': 42})98 def foo(bar, baz):99 return '%s/%d' % (bar, baz)100101 @bp.route('/bar')102 def bar(bar):103 return text_type(bar)104105 app = flask.Flask(__name__)106 app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23})107 app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19})108109 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'114115def test_blueprint_url_processors():116 bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')117118 @bp.url_defaults119 def add_language_code(endpoint, values):120 values.setdefault('lang_code', flask.g.lang_code)121122 @bp.url_value_preprocessor123 def pull_lang_code(endpoint, values):124 flask.g.lang_code = values.pop('lang_code')125126 @bp.route('/')127 def index():128 return flask.url_for('.about')129130 @bp.route('/about')131 def about():132 return flask.url_for('.index')133134 app = flask.Flask(__name__)135 app.register_blueprint(bp)136137 c = app.test_client()138139 assert c.get('/de/').data == b'/de/about'140 assert c.get('/de/about').data == b'/de/'141142def test_templates_and_static(test_apps):143 from blueprintapp import app144 c = app.test_client()145146 rv = c.get('/')147 assert rv.data == b'Hello from the Frontend'148 rv = c.get('/admin/')149 assert rv.data == b'Hello from the Admin'150 rv = c.get('/admin/index2')151 assert rv.data == b'Hello from the Admin'152 rv = c.get('/admin/static/test.txt')153 assert rv.data.strip() == b'Admin File'154 rv.close()155 rv = c.get('/admin/static/css/test.css')156 assert rv.data.strip() == b'/* nested file */'157 rv.close()158159 # try/finally, in case other tests use this app for Blueprint tests.160 max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT']161 try:162 expected_max_age = 3600163 if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == expected_max_age:164 expected_max_age = 7200165 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age166 rv = c.get('/admin/static/css/test.css')167 cc = parse_cache_control_header(rv.headers['Cache-Control'])168 assert cc.max_age == expected_max_age169 rv.close()170 finally:171 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default172173 with app.test_request_context():174 assert flask.url_for('admin.static', filename='test.txt') == '/admin/static/test.txt'175176 with app.test_request_context():177 with pytest.raises(TemplateNotFound) as e:178 flask.render_template('missing.html')179 assert e.value.name == 'missing.html'180181 with flask.Flask(__name__).test_request_context():182 assert flask.render_template('nested/nested.txt') == 'I\'m nested'183184def test_default_static_cache_timeout():185 app = flask.Flask(__name__)186 class MyBlueprint(flask.Blueprint):187 def get_send_file_max_age(self, filename):188 return 100189190 blueprint = MyBlueprint('blueprint', __name__, static_folder='static')191 app.register_blueprint(blueprint)192193 # try/finally, in case other tests use this app for Blueprint tests.194 max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT']195 try:196 with app.test_request_context():197 unexpected_max_age = 3600198 if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == unexpected_max_age:199 unexpected_max_age = 7200200 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = unexpected_max_age201 rv = blueprint.send_static_file('index.html')202 cc = parse_cache_control_header(rv.headers['Cache-Control'])203 assert cc.max_age == 100204 rv.close()205 finally:206 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default207208def test_templates_list(test_apps):209 from blueprintapp import app210 templates = sorted(app.jinja_env.list_templates())211 assert templates == ['admin/index.html', 'frontend/index.html']212213def test_dotted_names():214 frontend = flask.Blueprint('myapp.frontend', __name__)215 backend = flask.Blueprint('myapp.backend', __name__)216217 @frontend.route('/fe')218 def frontend_index():219 return flask.url_for('myapp.backend.backend_index')220221 @frontend.route('/fe2')222 def frontend_page2():223 return flask.url_for('.frontend_index')224225 @backend.route('/be')226 def backend_index():227 return flask.url_for('myapp.frontend.frontend_index')228229 app = flask.Flask(__name__)230 app.register_blueprint(frontend)231 app.register_blueprint(backend)232233 c = app.test_client()234 assert c.get('/fe').data.strip() == b'/be'235 assert c.get('/fe2').data.strip() == b'/fe'236 assert c.get('/be').data.strip() == b'/fe'237238def test_dotted_names_from_app():239 app = flask.Flask(__name__)240 app.testing = True241 test = flask.Blueprint('test', __name__)242243 @app.route('/')244 def app_index():245 return flask.url_for('test.index')246247 @test.route('/test/')248 def index():249 return flask.url_for('app_index')250251 app.register_blueprint(test)252253 with app.test_client() as c:254 rv = c.get('/')255 assert rv.data == b'/test/'256257def test_empty_url_defaults():258 bp = flask.Blueprint('bp', __name__)259260 @bp.route('/', defaults={'page': 1})261 @bp.route('/page/<int:page>')262 def something(page):263 return str(page)264265 app = flask.Flask(__name__)266 app.register_blueprint(bp)267268 c = app.test_client()269 assert c.get('/').data == b'1'270 assert c.get('/page/2').data == b'2'271272def test_route_decorator_custom_endpoint():273274 bp = flask.Blueprint('bp', __name__)275276 @bp.route('/foo')277 def foo():278 return flask.request.endpoint279280 @bp.route('/bar', endpoint='bar')281 def foo_bar():282 return flask.request.endpoint283284 @bp.route('/bar/123', endpoint='123')285 def foo_bar_foo():286 return flask.request.endpoint287288 @bp.route('/bar/foo')289 def bar_foo():290 return flask.request.endpoint291292 app = flask.Flask(__name__)293 app.register_blueprint(bp, url_prefix='/py')294295 @app.route('/')296 def index():297 return flask.request.endpoint298299 c = app.test_client()300 assert c.get('/').data == b'index'301 assert c.get('/py/foo').data == b'bp.foo'302 assert c.get('/py/bar').data == b'bp.bar'303 assert c.get('/py/bar/123').data == b'bp.123'304 assert c.get('/py/bar/foo').data == b'bp.bar_foo'305306def test_route_decorator_custom_endpoint_with_dots():307 bp = flask.Blueprint('bp', __name__)308309 @bp.route('/foo')310 def foo():311 return flask.request.endpoint312313 try:314 @bp.route('/bar', endpoint='bar.bar')315 def foo_bar():316 return flask.request.endpoint317 except AssertionError:318 pass319 else:320 raise AssertionError('expected AssertionError not raised')321322 try:323 @bp.route('/bar/123', endpoint='bar.123')324 def foo_bar_foo():325 return flask.request.endpoint326 except AssertionError:327 pass328 else:329 raise AssertionError('expected AssertionError not raised')330331 def foo_foo_foo():332 pass333334 pytest.raises(335 AssertionError,336 lambda: bp.add_url_rule(337 '/bar/123', endpoint='bar.123', view_func=foo_foo_foo338 )339 )340341 pytest.raises(342 AssertionError,343 bp.route('/bar/123', endpoint='bar.123'),344 lambda: None345 )346347 app = flask.Flask(__name__)348 app.register_blueprint(bp, url_prefix='/py')349350 c = app.test_client()351 assert c.get('/py/foo').data == b'bp.foo'352 # The rule's didn't actually made it through353 rv = c.get('/py/bar')354 assert rv.status_code == 404355 rv = c.get('/py/bar/123')356 assert rv.status_code == 404357358359def test_endpoint_decorator():360 from werkzeug.routing import Rule361 app = flask.Flask(__name__)362 app.url_map.add(Rule('/foo', endpoint='bar'))363364 bp = flask.Blueprint('bp', __name__)365366 @bp.endpoint('bar')367 def foobar():368 return flask.request.endpoint369370 app.register_blueprint(bp, url_prefix='/bp_prefix')371372 c = app.test_client()373 assert c.get('/foo').data == b'bar'374 assert c.get('/bp_prefix/bar').status_code == 404375376377def test_template_filter():378 bp = flask.Blueprint('bp', __name__)379 @bp.app_template_filter()380 def my_reverse(s):381 return s[::-1]382 app = flask.Flask(__name__)383 app.register_blueprint(bp, url_prefix='/py')384 assert 'my_reverse' in app.jinja_env.filters.keys()385 assert app.jinja_env.filters['my_reverse'] == my_reverse386 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'387388def test_add_template_filter():389 bp = flask.Blueprint('bp', __name__)390 def my_reverse(s):391 return s[::-1]392 bp.add_app_template_filter(my_reverse)393 app = flask.Flask(__name__)394 app.register_blueprint(bp, url_prefix='/py')395 assert 'my_reverse' in app.jinja_env.filters.keys()396 assert app.jinja_env.filters['my_reverse'] == my_reverse397 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'398399def test_template_filter_with_name():400 bp = flask.Blueprint('bp', __name__)401 @bp.app_template_filter('strrev')402 def my_reverse(s):403 return s[::-1]404 app = flask.Flask(__name__)405 app.register_blueprint(bp, url_prefix='/py')406 assert 'strrev' in app.jinja_env.filters.keys()407 assert app.jinja_env.filters['strrev'] == my_reverse408 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'409410def test_add_template_filter_with_name():411 bp = flask.Blueprint('bp', __name__)412 def my_reverse(s):413 return s[::-1]414 bp.add_app_template_filter(my_reverse, 'strrev')415 app = flask.Flask(__name__)416 app.register_blueprint(bp, url_prefix='/py')417 assert 'strrev' in app.jinja_env.filters.keys()418 assert app.jinja_env.filters['strrev'] == my_reverse419 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'420421def test_template_filter_with_template():422 bp = flask.Blueprint('bp', __name__)423 @bp.app_template_filter()424 def super_reverse(s):425 return s[::-1]426 app = flask.Flask(__name__)427 app.register_blueprint(bp, url_prefix='/py')428 @app.route('/')429 def index():430 return flask.render_template('template_filter.html', value='abcd')431 rv = app.test_client().get('/')432 assert rv.data == b'dcba'433434def test_template_filter_after_route_with_template():435 app = flask.Flask(__name__)436 @app.route('/')437 def index():438 return flask.render_template('template_filter.html', value='abcd')439 bp = flask.Blueprint('bp', __name__)440 @bp.app_template_filter()441 def super_reverse(s):442 return s[::-1]443 app.register_blueprint(bp, url_prefix='/py')444 rv = app.test_client().get('/')445 assert rv.data == b'dcba'446447def test_add_template_filter_with_template():448 bp = flask.Blueprint('bp', __name__)449 def super_reverse(s):450 return s[::-1]451 bp.add_app_template_filter(super_reverse)452 app = flask.Flask(__name__)453 app.register_blueprint(bp, url_prefix='/py')454 @app.route('/')455 def index():456 return flask.render_template('template_filter.html', value='abcd')457 rv = app.test_client().get('/')458 assert rv.data == b'dcba'459460def test_template_filter_with_name_and_template():461 bp = flask.Blueprint('bp', __name__)462 @bp.app_template_filter('super_reverse')463 def my_reverse(s):464 return s[::-1]465 app = flask.Flask(__name__)466 app.register_blueprint(bp, url_prefix='/py')467 @app.route('/')468 def index():469 return flask.render_template('template_filter.html', value='abcd')470 rv = app.test_client().get('/')471 assert rv.data == b'dcba'472473def test_add_template_filter_with_name_and_template():474 bp = flask.Blueprint('bp', __name__)475 def my_reverse(s):476 return s[::-1]477 bp.add_app_template_filter(my_reverse, 'super_reverse')478 app = flask.Flask(__name__)479 app.register_blueprint(bp, url_prefix='/py')480 @app.route('/')481 def index():482 return flask.render_template('template_filter.html', value='abcd')483 rv = app.test_client().get('/')484 assert rv.data == b'dcba'485486def test_template_test():487 bp = flask.Blueprint('bp', __name__)488 @bp.app_template_test()489 def is_boolean(value):490 return isinstance(value, bool)491 app = flask.Flask(__name__)492 app.register_blueprint(bp, url_prefix='/py')493 assert 'is_boolean' in app.jinja_env.tests.keys()494 assert app.jinja_env.tests['is_boolean'] == is_boolean495 assert app.jinja_env.tests['is_boolean'](False)496497def test_add_template_test():498 bp = flask.Blueprint('bp', __name__)499 def is_boolean(value):500 return isinstance(value, bool)501 bp.add_app_template_test(is_boolean)502 app = flask.Flask(__name__)503 app.register_blueprint(bp, url_prefix='/py')504 assert 'is_boolean' in app.jinja_env.tests.keys()505 assert app.jinja_env.tests['is_boolean'] == is_boolean506 assert app.jinja_env.tests['is_boolean'](False)507508def test_template_test_with_name():509 bp = flask.Blueprint('bp', __name__)510 @bp.app_template_test('boolean')511 def is_boolean(value):512 return isinstance(value, bool)513 app = flask.Flask(__name__)514 app.register_blueprint(bp, url_prefix='/py')515 assert 'boolean' in app.jinja_env.tests.keys()516 assert app.jinja_env.tests['boolean'] == is_boolean517 assert app.jinja_env.tests['boolean'](False)518519def test_add_template_test_with_name():520 bp = flask.Blueprint('bp', __name__)521 def is_boolean(value):522 return isinstance(value, bool)523 bp.add_app_template_test(is_boolean, 'boolean')524 app = flask.Flask(__name__)525 app.register_blueprint(bp, url_prefix='/py')526 assert 'boolean' in app.jinja_env.tests.keys()527 assert app.jinja_env.tests['boolean'] == is_boolean528 assert app.jinja_env.tests['boolean'](False)529530def test_template_test_with_template():531 bp = flask.Blueprint('bp', __name__)532 @bp.app_template_test()533 def boolean(value):534 return isinstance(value, bool)535 app = flask.Flask(__name__)536 app.register_blueprint(bp, url_prefix='/py')537 @app.route('/')538 def index():539 return flask.render_template('template_test.html', value=False)540 rv = app.test_client().get('/')541 assert b'Success!' in rv.data542543def test_template_test_after_route_with_template():544 app = flask.Flask(__name__)545 @app.route('/')546 def index():547 return flask.render_template('template_test.html', value=False)548 bp = flask.Blueprint('bp', __name__)549 @bp.app_template_test()550 def boolean(value):551 return isinstance(value, bool)552 app.register_blueprint(bp, url_prefix='/py')553 rv = app.test_client().get('/')554 assert b'Success!' in rv.data555556def test_add_template_test_with_template():557 bp = flask.Blueprint('bp', __name__)558 def boolean(value):559 return isinstance(value, bool)560 bp.add_app_template_test(boolean)561 app = flask.Flask(__name__)562 app.register_blueprint(bp, url_prefix='/py')563 @app.route('/')564 def index():565 return flask.render_template('template_test.html', value=False)566 rv = app.test_client().get('/')567 assert b'Success!' in rv.data568569def test_template_test_with_name_and_template():570 bp = flask.Blueprint('bp', __name__)571 @bp.app_template_test('boolean')572 def is_boolean(value):573 return isinstance(value, bool)574 app = flask.Flask(__name__)575 app.register_blueprint(bp, url_prefix='/py')576 @app.route('/')577 def index():578 return flask.render_template('template_test.html', value=False)579 rv = app.test_client().get('/')580 assert b'Success!' in rv.data581582def test_add_template_test_with_name_and_template():583 bp = flask.Blueprint('bp', __name__)584 def is_boolean(value):585 return isinstance(value, bool)586 bp.add_app_template_test(is_boolean, 'boolean')587 app = flask.Flask(__name__)588 app.register_blueprint(bp, url_prefix='/py')589 @app.route('/')590 def index():591 return flask.render_template('template_test.html', value=False)592 rv = app.test_client().get('/')593 assert b'Success!' in rv.data
added:tests/test_cli.py+270 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 class Module:43 app = Flask('appname')44 assert find_best_app(Module) == Module.app4546 class Module:47 application = Flask('appname')48 assert find_best_app(Module) == Module.application4950 class Module:51 myapp = Flask('appname')52 assert find_best_app(Module) == Module.myapp5354 class Module:55 pass56 pytest.raises(NoAppException, find_best_app, Module)5758 class Module:59 myapp1 = Flask('appname1')60 myapp2 = Flask('appname2')61 pytest.raises(NoAppException, find_best_app, Module)626364def test_prepare_exec_for_file(test_apps):65 """Expect the correct path to be set and the correct module name to be returned.6667 :func:`prepare_exec_for_file` has a side effect, where68 the parent directory of given file is added to `sys.path`.69 """70 realpath = os.path.realpath('/tmp/share/test.py')71 dirname = os.path.dirname(realpath)72 assert prepare_exec_for_file('/tmp/share/test.py') == 'test'73 assert dirname in sys.path7475 realpath = os.path.realpath('/tmp/share/__init__.py')76 dirname = os.path.dirname(os.path.dirname(realpath))77 assert prepare_exec_for_file('/tmp/share/__init__.py') == 'share'78 assert dirname in sys.path7980 with pytest.raises(NoAppException):81 prepare_exec_for_file('/tmp/share/test.txt')828384def test_locate_app(test_apps):85 """Test of locate_app."""86 assert locate_app("cliapp.app").name == "testapp"87 assert locate_app("cliapp.app:testapp").name == "testapp"88 assert locate_app("cliapp.multiapp:app1").name == "app1"89 pytest.raises(NoAppException, locate_app, "notanpp.py")90 pytest.raises(NoAppException, locate_app, "cliapp/app")91 pytest.raises(RuntimeError, locate_app, "cliapp.app:notanapp")92 pytest.raises(NoAppException, locate_app, "cliapp.importerrorapp")939495def test_find_default_import_path(test_apps, monkeypatch, tmpdir):96 """Test of find_default_import_path."""97 monkeypatch.delitem(os.environ, 'FLASK_APP', raising=False)98 assert find_default_import_path() == None99 monkeypatch.setitem(os.environ, 'FLASK_APP', 'notanapp')100 assert find_default_import_path() == 'notanapp'101 tmpfile = tmpdir.join('testapp.py')102 tmpfile.write('')103 monkeypatch.setitem(os.environ, 'FLASK_APP', str(tmpfile))104 expect_rv = prepare_exec_for_file(str(tmpfile))105 assert find_default_import_path() == expect_rv106107108def test_get_version(test_apps, capsys):109 """Test of get_version."""110 from flask import __version__ as flask_ver111 from sys import version as py_ver112 class MockCtx(object):113 resilient_parsing = False114 color = None115 def exit(self): return116 ctx = MockCtx()117 get_version(ctx, None, "test")118 out, err = capsys.readouterr()119 assert flask_ver in out120 assert py_ver in out121122123def test_scriptinfo(test_apps):124 """Test of ScriptInfo."""125 obj = ScriptInfo(app_import_path="cliapp.app:testapp")126 assert obj.load_app().name == "testapp"127 assert obj.load_app().name == "testapp"128129 def create_app(info):130 return Flask("createapp")131132 obj = ScriptInfo(create_app=create_app)133 app = obj.load_app()134 assert app.name == "createapp"135 assert obj.load_app() == app136137138def test_with_appcontext(runner):139 """Test of with_appcontext."""140 @click.command()141 @with_appcontext142 def testcmd():143 click.echo(current_app.name)144145 obj = ScriptInfo(create_app=lambda info: Flask("testapp"))146147 result = runner.invoke(testcmd, obj=obj)148 assert result.exit_code == 0149 assert result.output == 'testapp\n'150151152def test_appgroup(runner):153 """Test of with_appcontext."""154 @click.group(cls=AppGroup)155 def cli():156 pass157158 @cli.command(with_appcontext=True)159 def test():160 click.echo(current_app.name)161162 @cli.group()163 def subgroup():164 pass165166 @subgroup.command(with_appcontext=True)167 def test2():168 click.echo(current_app.name)169170 obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))171172 result = runner.invoke(cli, ['test'], obj=obj)173 assert result.exit_code == 0174 assert result.output == 'testappgroup\n'175176 result = runner.invoke(cli, ['subgroup', 'test2'], obj=obj)177 assert result.exit_code == 0178 assert result.output == 'testappgroup\n'179180181def test_flaskgroup(runner):182 """Test FlaskGroup."""183 def create_app(info):184 return Flask("flaskgroup")185186 @click.group(cls=FlaskGroup, create_app=create_app)187 def cli(**params):188 pass189190 @cli.command()191 def test():192 click.echo(current_app.name)193194 result = runner.invoke(cli, ['test'])195 assert result.exit_code == 0196 assert result.output == 'flaskgroup\n'197198199def test_print_exceptions(runner):200 """Print the stacktrace if the CLI."""201 def create_app(info):202 raise Exception("oh no")203 return Flask("flaskgroup")204205 @click.group(cls=FlaskGroup, create_app=create_app)206 def cli(**params):207 pass208209 result = runner.invoke(cli, ['--help'])210 assert result.exit_code == 0211 assert 'Exception: oh no' in result.output212 assert 'Traceback' in result.output213214215class TestRoutes:216 @pytest.fixture217 def invoke(self, runner):218 def create_app(info):219 app = Flask(__name__)220 app.testing = True221222 @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])223 def yyy_get_post(x, y):224 pass225226 @app.route('/zzz_post', methods=['POST'])227 def aaa_post():228 pass229230 return app231232 cli = FlaskGroup(create_app=create_app)233 return partial(runner.invoke, cli)234235 def expect_order(self, order, output):236 # skip the header and match the start of each row237 for expect, line in zip(order, output.splitlines()[2:]):238 # do this instead of startswith for nicer pytest output239 assert line[:len(expect)] == expect240241 def test_simple(self, invoke):242 result = invoke(['routes'])243 assert result.exit_code == 0244 self.expect_order(245 ['aaa_post', 'static', 'yyy_get_post'],246 result.output247 )248249 def test_sort(self, invoke):250 default_output = invoke(['routes']).output251 endpoint_output = invoke(['routes', '-s', 'endpoint']).output252 assert default_output == endpoint_output253 self.expect_order(254 ['static', 'yyy_get_post', 'aaa_post'],255 invoke(['routes', '-s', 'methods']).output256 )257 self.expect_order(258 ['yyy_get_post', 'static', 'aaa_post'],259 invoke(['routes', '-s', 'rule']).output260 )261 self.expect_order(262 ['aaa_post', 'yyy_get_post', 'static'],263 invoke(['routes', '-s', 'match']).output264 )265266 def test_all_methods(self, invoke):267 output = invoke(['routes']).output268 assert 'GET, HEAD, OPTIONS, POST' not in output269 output = invoke(['routes', '--all-methods']).output270 assert 'GET, HEAD, OPTIONS, POST' in output
added:tests/test_config.py+207 added
1# -*- coding: utf-8 -*-2"""3 tests.test_config4 ~~~~~~~~~~~~~~~~~56 :copyright: (c) 2015 by the Flask Team, see AUTHORS for more details.7 :license: BSD, see LICENSE for more details.8"""91011from datetime import timedelta12import os13import textwrap1415import flask16from flask._compat import PY217import pytest181920# config keys used for the TestConfig21TEST_KEY = 'foo'22SECRET_KEY = 'devkey'232425def common_object_test(app):26 assert app.secret_key == 'devkey'27 assert app.config['TEST_KEY'] == 'foo'28 assert 'TestConfig' not in app.config293031def test_config_from_file():32 app = flask.Flask(__name__)33 app.config.from_pyfile(__file__.rsplit('.', 1)[0] + '.py')34 common_object_test(app)353637def test_config_from_object():38 app = flask.Flask(__name__)39 app.config.from_object(__name__)40 common_object_test(app)414243def test_config_from_json():44 app = flask.Flask(__name__)45 current_dir = os.path.dirname(os.path.abspath(__file__))46 app.config.from_json(os.path.join(current_dir, 'static', 'config.json'))47 common_object_test(app)484950def test_config_from_mapping():51 app = flask.Flask(__name__)52 app.config.from_mapping({53 'SECRET_KEY': 'devkey',54 'TEST_KEY': 'foo'55 })56 common_object_test(app)5758 app = flask.Flask(__name__)59 app.config.from_mapping([60 ('SECRET_KEY', 'devkey'),61 ('TEST_KEY', 'foo')62 ])63 common_object_test(app)6465 app = flask.Flask(__name__)66 app.config.from_mapping(67 SECRET_KEY='devkey',68 TEST_KEY='foo'69 )70 common_object_test(app)7172 app = flask.Flask(__name__)73 with pytest.raises(TypeError):74 app.config.from_mapping(75 {}, {}76 )777879def test_config_from_class():80 class Base(object):81 TEST_KEY = 'foo'8283 class Test(Base):84 SECRET_KEY = 'devkey'85 app = flask.Flask(__name__)86 app.config.from_object(Test)87 common_object_test(app)888990def test_config_from_envvar():91 env = os.environ92 try:93 os.environ = {}94 app = flask.Flask(__name__)95 with pytest.raises(RuntimeError) as e:96 app.config.from_envvar('FOO_SETTINGS')97 assert "'FOO_SETTINGS' is not set" in str(e.value)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')102 common_object_test(app)103 finally:104 os.environ = env105106107def test_config_from_envvar_missing():108 env = os.environ109 try:110 os.environ = {'FOO_SETTINGS': 'missing.cfg'}111 with pytest.raises(IOError) as e:112 app = flask.Flask(__name__)113 app.config.from_envvar('FOO_SETTINGS')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 assert not app.config.from_envvar('FOO_SETTINGS', silent=True)119 finally:120 os.environ = env121122123def test_config_missing():124 app = flask.Flask(__name__)125 with pytest.raises(IOError) as e:126 app.config.from_pyfile('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'")131 assert not app.config.from_pyfile('missing.cfg', silent=True)132133134def test_config_missing_json():135 app = flask.Flask(__name__)136 with pytest.raises(IOError) as e:137 app.config.from_json('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'")142 assert not app.config.from_json('missing.json', silent=True)143144145def test_custom_config_class():146 class Config(flask.Config):147 pass148149 class Flask(flask.Flask):150 config_class = Config151 app = Flask(__name__)152 assert isinstance(app.config, Config)153 app.config.from_object(__name__)154 common_object_test(app)155156157def test_session_lifetime():158 app = flask.Flask(__name__)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'175 app.config['BAR_STUFF_1'] = 'bar stuff 1'176 app.config['BAR_STUFF_2'] = 'bar stuff 2'177 foo_options = app.config.get_namespace('FOO_')178 assert 2 == len(foo_options)179 assert 'foo option 1' == foo_options['option_1']180 assert 'foo option 2' == foo_options['option_2']181 bar_options = app.config.get_namespace('BAR_', lowercase=False)182 assert 2 == len(bar_options)183 assert 'bar stuff 1' == bar_options['STUFF_1']184 assert 'bar stuff 2' == bar_options['STUFF_2']185 foo_options = app.config.get_namespace('FOO_', trim_namespace=False)186 assert 2 == len(foo_options)187 assert 'foo option 1' == foo_options['foo_option_1']188 assert 'foo option 2' == foo_options['foo_option_2']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öö'
added:tests/test_deprecations.py+46 added
1# -*- coding: utf-8 -*-2"""3 tests.deprecations4 ~~~~~~~~~~~~~~~~~~56 Tests deprecation support. Not used currently.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1314import flask151617class TestRequestDeprecation(object):1819 def test_request_json(self, recwarn):20 """Request.json is deprecated"""21 app = flask.Flask(__name__)22 app.testing = True2324 @app.route('/', methods=['POST'])25 def index():26 assert flask.request.json == {'spam': 42}27 print(flask.request.json)28 return 'OK'2930 c = app.test_client()31 c.post('/', data='{"spam": 42}', content_type='application/json')32 recwarn.pop(DeprecationWarning)3334 def test_request_module(self, recwarn):35 """Request.module is deprecated"""36 app = flask.Flask(__name__)37 app.testing = True3839 @app.route('/')40 def index():41 assert flask.request.module is None42 return 'OK'4344 c = app.test_client()45 c.get('/')46 recwarn.pop(DeprecationWarning)
added:tests/test_ext.py+199 added
1# -*- coding: utf-8 -*-2"""3 tests.ext4 ~~~~~~~~~~~~~~~~~~~56 Tests the extension import thing.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import sys13import pytest1415try:16 from imp import reload as reload_module17except ImportError:18 reload_module = reload1920from flask._compat import PY2212223@pytest.fixture(autouse=True)24def disable_extwarnings(request, recwarn):25 from flask.exthook import ExtDeprecationWarning2627 def inner():28 assert set(w.category for w in recwarn.list) \29 <= set([ExtDeprecationWarning])30 recwarn.clear()3132 request.addfinalizer(inner)333435@pytest.fixture(autouse=True)36def importhook_setup(monkeypatch, request):37 # we clear this out for various reasons. The most important one is38 # that a real flaskext could be in there which would disable our39 # fake package. Secondly we want to make sure that the flaskext40 # import hook does not break on reloading.41 for entry, value in list(sys.modules.items()):42 if (43 entry.startswith('flask.ext.') or44 entry.startswith('flask_') or45 entry.startswith('flaskext.') or46 entry == 'flaskext'47 ) and value is not None:48 monkeypatch.delitem(sys.modules, entry)49 from flask import ext50 reload_module(ext)5152 # reloading must not add more hooks53 import_hooks = 054 for item in sys.meta_path:55 cls = type(item)56 if cls.__module__ == 'flask.exthook' and \57 cls.__name__ == 'ExtensionImporter':58 import_hooks += 159 assert import_hooks == 16061 def teardown():62 from flask import ext63 for key in ext.__dict__:64 assert '.' not in key6566 request.addfinalizer(teardown)676869@pytest.fixture70def newext_simple(modules_tmpdir):71 x = modules_tmpdir.join('flask_newext_simple.py')72 x.write('ext_id = "newext_simple"')737475@pytest.fixture76def oldext_simple(modules_tmpdir):77 flaskext = modules_tmpdir.mkdir('flaskext')78 flaskext.join('__init__.py').write('\n')79 flaskext.join('oldext_simple.py').write('ext_id = "oldext_simple"')808182@pytest.fixture83def newext_package(modules_tmpdir):84 pkg = modules_tmpdir.mkdir('flask_newext_package')85 pkg.join('__init__.py').write('ext_id = "newext_package"')86 pkg.join('submodule.py').write('def test_function():\n return 42\n')878889@pytest.fixture90def oldext_package(modules_tmpdir):91 flaskext = modules_tmpdir.mkdir('flaskext')92 flaskext.join('__init__.py').write('\n')93 oldext = flaskext.mkdir('oldext_package')94 oldext.join('__init__.py').write('ext_id = "oldext_package"')95 oldext.join('submodule.py').write('def test_function():\n'96 ' return 42')979899@pytest.fixture100def flaskext_broken(modules_tmpdir):101 ext = modules_tmpdir.mkdir('flask_broken')102 ext.join('b.py').write('\n')103 ext.join('__init__.py').write('import flask.ext.broken.b\n'104 'import missing_module')105106107def test_flaskext_new_simple_import_normal(newext_simple):108 from flask.ext.newext_simple import ext_id109 assert ext_id == 'newext_simple'110111112def test_flaskext_new_simple_import_module(newext_simple):113 from flask.ext import newext_simple114 assert newext_simple.ext_id == 'newext_simple'115 assert newext_simple.__name__ == 'flask_newext_simple'116117118def test_flaskext_new_package_import_normal(newext_package):119 from flask.ext.newext_package import ext_id120 assert ext_id == 'newext_package'121122123def test_flaskext_new_package_import_module(newext_package):124 from flask.ext import newext_package125 assert newext_package.ext_id == 'newext_package'126 assert newext_package.__name__ == 'flask_newext_package'127128129def test_flaskext_new_package_import_submodule_function(newext_package):130 from flask.ext.newext_package.submodule import test_function131 assert test_function() == 42132133134def test_flaskext_new_package_import_submodule(newext_package):135 from flask.ext.newext_package import submodule136 assert submodule.__name__ == 'flask_newext_package.submodule'137 assert submodule.test_function() == 42138139140def test_flaskext_old_simple_import_normal(oldext_simple):141 from flask.ext.oldext_simple import ext_id142 assert ext_id == 'oldext_simple'143144145def test_flaskext_old_simple_import_module(oldext_simple):146 from flask.ext import oldext_simple147 assert oldext_simple.ext_id == 'oldext_simple'148 assert oldext_simple.__name__ == 'flaskext.oldext_simple'149150151def test_flaskext_old_package_import_normal(oldext_package):152 from flask.ext.oldext_package import ext_id153 assert ext_id == 'oldext_package'154155156def test_flaskext_old_package_import_module(oldext_package):157 from flask.ext import oldext_package158 assert oldext_package.ext_id == 'oldext_package'159 assert oldext_package.__name__ == 'flaskext.oldext_package'160161162def test_flaskext_old_package_import_submodule(oldext_package):163 from flask.ext.oldext_package import submodule164 assert submodule.__name__ == 'flaskext.oldext_package.submodule'165 assert submodule.test_function() == 42166167168def test_flaskext_old_package_import_submodule_function(oldext_package):169 from flask.ext.oldext_package.submodule import test_function170 assert test_function() == 42171172173def test_flaskext_broken_package_no_module_caching(flaskext_broken):174 for x in range(2):175 with pytest.raises(ImportError):176 import flask.ext.broken177178179def test_no_error_swallowing(flaskext_broken):180 with pytest.raises(ImportError) as excinfo:181 import flask.ext.broken182 # python3.6 raises a subclass of ImportError: 'ModuleNotFoundError'183 assert issubclass(excinfo.type, ImportError)184 if PY2:185 message = 'No module named missing_module'186 else:187 message = 'No module named \'missing_module\''188 assert str(excinfo.value) == message189 assert excinfo.tb.tb_frame.f_globals is globals()190191 # reraise() adds a second frame so we need to skip that one too.192 # On PY3 we even have another one :(193 next = excinfo.tb.tb_next.tb_next194 if not PY2:195 next = next.tb_next196197 import os.path198 assert os.path.join('flask_broken', '__init__.py') in \199 next.tb_frame.f_code.co_filename
added:tests/test_helpers.py+943 added
1# -*- coding: utf-8 -*-2"""3 tests.helpers4 ~~~~~~~~~~~~~~~~~~~~~~~56 Various helpers.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""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_type252627def has_encoding(name):28 try:29 import codecs30 codecs.lookup(name)31 return True32 except LookupError:33 return False343536class TestJSON(object):3738 def test_ignore_cached_json(self):39 app = flask.Flask(__name__)40 with app.test_request_context('/', method='POST', data='malformed',41 content_type='application/json'):42 assert flask.request.get_json(silent=True, cache=True) is None43 with pytest.raises(BadRequest):44 flask.request.get_json(silent=False, cache=False)4546 def test_post_empty_json_adds_exception_to_response_content_in_debug(self):47 app = flask.Flask(__name__)48 app.config['DEBUG'] = True49 @app.route('/json', methods=['POST'])50 def post_json():51 flask.request.get_json()52 return None53 c = app.test_client()54 rv = c.post('/json', data=None, content_type='application/json')55 assert rv.status_code == 40056 assert b'Failed to decode JSON object' in rv.data5758 def test_post_empty_json_wont_add_exception_to_response_if_no_debug(self):59 app = flask.Flask(__name__)60 app.config['DEBUG'] = False61 @app.route('/json', methods=['POST'])62 def post_json():63 flask.request.get_json()64 return None65 c = app.test_client()66 rv = c.post('/json', data=None, content_type='application/json')67 assert rv.status_code == 40068 assert b'Failed to decode JSON object' not in rv.data6970 def test_json_bad_requests(self):71 app = flask.Flask(__name__)72 @app.route('/json', methods=['POST'])73 def return_json():74 return flask.jsonify(foo=text_type(flask.request.get_json()))75 c = app.test_client()76 rv = c.post('/json', data='malformed', content_type='application/json')77 assert rv.status_code == 4007879 def test_json_custom_mimetypes(self):80 app = flask.Flask(__name__)81 @app.route('/json', methods=['POST'])82 def return_json():83 return flask.request.get_json()84 c = app.test_client()85 rv = c.post('/json', data='"foo"', content_type='application/x+json')86 assert rv.data == b'foo'8788 def test_json_body_encoding(self):89 app = flask.Flask(__name__)90 app.testing = True91 @app.route('/')92 def index():93 return flask.request.get_json()9495 c = app.test_client()96 resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),97 content_type='application/json; charset=iso-8859-15')98 assert resp.data == u'Hällo Wörld'.encode('utf-8')99100 def test_json_as_unicode(self):101 app = flask.Flask(__name__)102103 app.config['JSON_AS_ASCII'] = True104 with app.app_context():105 rv = flask.json.dumps(u'\N{SNOWMAN}')106 assert rv == '"\\u2603"'107108 app.config['JSON_AS_ASCII'] = False109 with app.app_context():110 rv = flask.json.dumps(u'\N{SNOWMAN}')111 assert rv == u'"\u2603"'112113 def test_json_dump_to_file(self):114 app = flask.Flask(__name__)115 test_data = {'name': 'Flask'}116 out = StringIO()117118 with app.app_context():119 flask.json.dump(test_data, out)120 out.seek(0)121 rv = flask.json.load(out)122 assert rv == test_data123124 @pytest.mark.parametrize('test_value', [0, -1, 1, 23, 3.14, 's', "longer string", True, False, None])125 def test_jsonify_basic_types(self, test_value):126 """Test jsonify with basic types."""127 app = flask.Flask(__name__)128 c = app.test_client()129130 url = '/jsonify_basic_types'131 app.add_url_rule(url, url, lambda x=test_value: flask.jsonify(x))132 rv = c.get(url)133 assert rv.mimetype == 'application/json'134 assert flask.json.loads(rv.data) == test_value135136 def test_jsonify_dicts(self):137 """Test jsonify with dicts and kwargs unpacking."""138 d = dict(139 a=0, b=23, c=3.14, d='t', e='Hi', f=True, g=False,140 h=['test list', 10, False],141 i={'test':'dict'}142 )143 app = flask.Flask(__name__)144 @app.route('/kw')145 def return_kwargs():146 return flask.jsonify(**d)147 @app.route('/dict')148 def return_dict():149 return flask.jsonify(d)150 c = app.test_client()151 for url in '/kw', '/dict':152 rv = c.get(url)153 assert rv.mimetype == 'application/json'154 assert flask.json.loads(rv.data) == d155156 def test_jsonify_arrays(self):157 """Test jsonify of lists and args unpacking."""158 l = [159 0, 42, 3.14, 't', 'hello', True, False,160 ['test list', 2, False],161 {'test':'dict'}162 ]163 app = flask.Flask(__name__)164 @app.route('/args_unpack')165 def return_args_unpack():166 return flask.jsonify(*l)167 @app.route('/array')168 def return_array():169 return flask.jsonify(l)170 c = app.test_client()171 for url in '/args_unpack', '/array':172 rv = c.get(url)173 assert rv.mimetype == 'application/json'174 assert flask.json.loads(rv.data) == l175176 def test_jsonify_date_types(self):177 """Test jsonify with datetime.date and datetime.datetime types."""178 test_dates = (179 datetime.datetime(1973, 3, 11, 6, 30, 45),180 datetime.date(1975, 1, 5)181 )182 app = flask.Flask(__name__)183 c = app.test_client()184185 for i, d in enumerate(test_dates):186 url = '/datetest{0}'.format(i)187 app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val))188 rv = c.get(url)189 assert rv.mimetype == 'application/json'190 assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple())191192 def test_jsonify_uuid_types(self):193 """Test jsonify with uuid.UUID types"""194195 test_uuid = uuid.UUID(bytes=b'\xDE\xAD\xBE\xEF' * 4)196 app = flask.Flask(__name__)197 url = '/uuid_test'198 app.add_url_rule(url, url, lambda: flask.jsonify(x=test_uuid))199200 c = app.test_client()201 rv = c.get(url)202203 rv_x = flask.json.loads(rv.data)['x']204 assert rv_x == str(test_uuid)205 rv_uuid = uuid.UUID(rv_x)206 assert rv_uuid == test_uuid207208 def test_json_attr(self):209 app = flask.Flask(__name__)210 @app.route('/add', methods=['POST'])211 def add():212 json = flask.request.get_json()213 return text_type(json['a'] + json['b'])214 c = app.test_client()215 rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),216 content_type='application/json')217 assert rv.data == b'3'218219 def test_template_escaping(self):220 app = flask.Flask(__name__)221 render = flask.render_template_string222 with app.test_request_context():223 rv = flask.json.htmlsafe_dumps('</script>')224 assert rv == u'"\\u003c/script\\u003e"'225 assert type(rv) == text_type226 rv = render('{{ "</script>"|tojson }}')227 assert rv == '"\\u003c/script\\u003e"'228 rv = render('{{ "<\0/script>"|tojson }}')229 assert rv == '"\\u003c\\u0000/script\\u003e"'230 rv = render('{{ "<!--<script>"|tojson }}')231 assert rv == '"\\u003c!--\\u003cscript\\u003e"'232 rv = render('{{ "&"|tojson }}')233 assert rv == '"\\u0026"'234 rv = render('{{ "\'"|tojson }}')235 assert rv == '"\\u0027"'236 rv = render("<a ng-data='{{ data|tojson }}'></a>",237 data={'x': ["foo", "bar", "baz'"]})238 assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'239240 def test_json_customization(self):241 class X(object):242 def __init__(self, val):243 self.val = val244 class MyEncoder(flask.json.JSONEncoder):245 def default(self, o):246 if isinstance(o, X):247 return '<%d>' % o.val248 return flask.json.JSONEncoder.default(self, o)249 class MyDecoder(flask.json.JSONDecoder):250 def __init__(self, *args, **kwargs):251 kwargs.setdefault('object_hook', self.object_hook)252 flask.json.JSONDecoder.__init__(self, *args, **kwargs)253 def object_hook(self, obj):254 if len(obj) == 1 and '_foo' in obj:255 return X(obj['_foo'])256 return obj257 app = flask.Flask(__name__)258 app.testing = True259 app.json_encoder = MyEncoder260 app.json_decoder = MyDecoder261 @app.route('/', methods=['POST'])262 def index():263 return flask.json.dumps(flask.request.get_json()['x'])264 c = app.test_client()265 rv = c.post('/', data=flask.json.dumps({266 'x': {'_foo': 42}267 }), content_type='application/json')268 assert rv.data == b'"<42>"'269270 def test_blueprint_json_customization(self):271 class X(object):272 def __init__(self, val):273 self.val = val274275 class MyEncoder(flask.json.JSONEncoder):276 def default(self, o):277 if isinstance(o, X):278 return '<%d>' % o.val279280 return flask.json.JSONEncoder.default(self, o)281282 class MyDecoder(flask.json.JSONDecoder):283 def __init__(self, *args, **kwargs):284 kwargs.setdefault('object_hook', self.object_hook)285 flask.json.JSONDecoder.__init__(self, *args, **kwargs)286287 def object_hook(self, obj):288 if len(obj) == 1 and '_foo' in obj:289 return X(obj['_foo'])290291 return obj292293 bp = flask.Blueprint('bp', __name__)294 bp.json_encoder = MyEncoder295 bp.json_decoder = MyDecoder296297 @bp.route('/bp', methods=['POST'])298 def index():299 return flask.json.dumps(flask.request.get_json()['x'])300301 app = flask.Flask(__name__)302 app.testing = True303 app.register_blueprint(bp)304305 c = app.test_client()306 rv = c.post('/bp', data=flask.json.dumps({307 'x': {'_foo': 42}308 }), content_type='application/json')309 assert rv.data == b'"<42>"'310311 def test_modified_url_encoding(self):312 class ModifiedRequest(flask.Request):313 url_charset = 'euc-kr'314 app = flask.Flask(__name__)315 app.testing = True316 app.request_class = ModifiedRequest317 app.url_map.charset = 'euc-kr'318319 @app.route('/')320 def index():321 return flask.request.args['foo']322323 rv = app.test_client().get(u'/?foo=정상처리'.encode('euc-kr'))324 assert rv.status_code == 200325 assert rv.data == u'정상처리'.encode('utf-8')326327 if not has_encoding('euc-kr'):328 test_modified_url_encoding = None329330 def test_json_key_sorting(self):331 app = flask.Flask(__name__)332 app.testing = True333 app.debug = True334335 assert app.config['JSON_SORT_KEYS'] == True336 d = dict.fromkeys(range(20), 'foo')337338 @app.route('/')339 def index():340 return flask.jsonify(values=d)341342 c = app.test_client()343 rv = c.get('/')344 lines = [x.strip() for x in rv.data.strip().decode('utf-8').splitlines()]345 sorted_by_str = [346 '{',347 '"values": {',348 '"0": "foo",',349 '"1": "foo",',350 '"10": "foo",',351 '"11": "foo",',352 '"12": "foo",',353 '"13": "foo",',354 '"14": "foo",',355 '"15": "foo",',356 '"16": "foo",',357 '"17": "foo",',358 '"18": "foo",',359 '"19": "foo",',360 '"2": "foo",',361 '"3": "foo",',362 '"4": "foo",',363 '"5": "foo",',364 '"6": "foo",',365 '"7": "foo",',366 '"8": "foo",',367 '"9": "foo"',368 '}',369 '}'370 ]371 sorted_by_int = [372 '{',373 '"values": {',374 '"0": "foo",',375 '"1": "foo",',376 '"2": "foo",',377 '"3": "foo",',378 '"4": "foo",',379 '"5": "foo",',380 '"6": "foo",',381 '"7": "foo",',382 '"8": "foo",',383 '"9": "foo",',384 '"10": "foo",',385 '"11": "foo",',386 '"12": "foo",',387 '"13": "foo",',388 '"14": "foo",',389 '"15": "foo",',390 '"16": "foo",',391 '"17": "foo",',392 '"18": "foo",',393 '"19": "foo"',394 '}',395 '}'396 ]397398 try:399 assert lines == sorted_by_int400 except AssertionError:401 assert lines == sorted_by_str402403class TestSendfile(object):404405 def test_send_file_regular(self):406 app = flask.Flask(__name__)407 with app.test_request_context():408 rv = flask.send_file('static/index.html')409 assert rv.direct_passthrough410 assert rv.mimetype == 'text/html'411 with app.open_resource('static/index.html') as f:412 rv.direct_passthrough = False413 assert rv.data == f.read()414 rv.close()415416 def test_send_file_xsendfile(self, catch_deprecation_warnings):417 app = flask.Flask(__name__)418 app.use_x_sendfile = True419 with app.test_request_context():420 rv = flask.send_file('static/index.html')421 assert rv.direct_passthrough422 assert 'x-sendfile' in rv.headers423 assert rv.headers['x-sendfile'] == \424 os.path.join(app.root_path, 'static/index.html')425 assert rv.mimetype == 'text/html'426 rv.close()427428 def test_send_file_last_modified(self):429 app = flask.Flask(__name__)430 last_modified = datetime.datetime(1999, 1, 1)431432 @app.route('/')433 def index():434 return flask.send_file(StringIO("party like it's"),435 last_modified=last_modified,436 mimetype='text/plain')437438 c = app.test_client()439 rv = c.get('/')440 assert rv.last_modified == last_modified441442 def test_send_file_object_without_mimetype(self):443 app = flask.Flask(__name__)444445 with app.test_request_context():446 with pytest.raises(ValueError) as excinfo:447 flask.send_file(StringIO("LOL"))448 assert 'Unable to infer MIME-type' in str(excinfo)449 assert 'no filename is available' in str(excinfo)450451 with app.test_request_context():452 flask.send_file(StringIO("LOL"), attachment_filename='filename')453454 def test_send_file_object(self):455 app = flask.Flask(__name__)456457 with app.test_request_context():458 with open(os.path.join(app.root_path, 'static/index.html'), mode='rb') as f:459 rv = flask.send_file(f, mimetype='text/html')460 rv.direct_passthrough = False461 with app.open_resource('static/index.html') as f:462 assert rv.data == f.read()463 assert rv.mimetype == 'text/html'464 rv.close()465466 app.use_x_sendfile = True467468 with app.test_request_context():469 with open(os.path.join(app.root_path, 'static/index.html')) as f:470 rv = flask.send_file(f, mimetype='text/html')471 assert rv.mimetype == 'text/html'472 assert 'x-sendfile' not in rv.headers473 rv.close()474475 app.use_x_sendfile = False476 with app.test_request_context():477 f = StringIO('Test')478 rv = flask.send_file(f, mimetype='application/octet-stream')479 rv.direct_passthrough = False480 assert rv.data == b'Test'481 assert rv.mimetype == 'application/octet-stream'482 rv.close()483484 class PyStringIO(object):485 def __init__(self, *args, **kwargs):486 self._io = StringIO(*args, **kwargs)487 def __getattr__(self, name):488 return getattr(self._io, name)489 f = PyStringIO('Test')490 f.name = 'test.txt'491 rv = flask.send_file(f, attachment_filename=f.name)492 rv.direct_passthrough = False493 assert rv.data == b'Test'494 assert rv.mimetype == 'text/plain'495 rv.close()496497 f = StringIO('Test')498 rv = flask.send_file(f, mimetype='text/plain')499 rv.direct_passthrough = False500 assert rv.data == b'Test'501 assert rv.mimetype == 'text/plain'502 rv.close()503504 app.use_x_sendfile = True505506 with app.test_request_context():507 f = StringIO('Test')508 rv = flask.send_file(f, mimetype='text/html')509 assert 'x-sendfile' not in rv.headers510 rv.close()511512 @pytest.mark.skipif(513 not callable(getattr(Range, 'to_content_range_header', None)),514 reason="not implement within werkzeug"515 )516 def test_send_file_range_request(self):517 app = flask.Flask(__name__)518519 @app.route('/')520 def index():521 return flask.send_file('static/index.html', conditional=True)522523 c = app.test_client()524525 rv = c.get('/', headers={'Range': 'bytes=4-15'})526 assert rv.status_code == 206527 with app.open_resource('static/index.html') as f:528 assert rv.data == f.read()[4:16]529 rv.close()530531 rv = c.get('/', headers={'Range': 'bytes=4-'})532 assert rv.status_code == 206533 with app.open_resource('static/index.html') as f:534 assert rv.data == f.read()[4:]535 rv.close()536537 rv = c.get('/', headers={'Range': 'bytes=4-1000'})538 assert rv.status_code == 206539 with app.open_resource('static/index.html') as f:540 assert rv.data == f.read()[4:]541 rv.close()542543 rv = c.get('/', headers={'Range': 'bytes=-10'})544 assert rv.status_code == 206545 with app.open_resource('static/index.html') as f:546 assert rv.data == f.read()[-10:]547 rv.close()548549 rv = c.get('/', headers={'Range': 'bytes=1000-'})550 assert rv.status_code == 416551 rv.close()552553 rv = c.get('/', headers={'Range': 'bytes=-'})554 assert rv.status_code == 416555 rv.close()556557 rv = c.get('/', headers={'Range': 'somethingsomething'})558 assert rv.status_code == 416559 rv.close()560561 last_modified = datetime.datetime.utcfromtimestamp(os.path.getmtime(562 os.path.join(app.root_path, 'static/index.html'))).replace(563 microsecond=0)564565 rv = c.get('/', headers={'Range': 'bytes=4-15',566 'If-Range': http_date(last_modified)})567 assert rv.status_code == 206568 rv.close()569570 rv = c.get('/', headers={'Range': 'bytes=4-15', 'If-Range': http_date(571 datetime.datetime(1999, 1, 1))})572 assert rv.status_code == 200573 rv.close()574575 def test_attachment(self):576 app = flask.Flask(__name__)577 with app.test_request_context():578 with open(os.path.join(app.root_path, 'static/index.html')) as f:579 rv = flask.send_file(f, as_attachment=True,580 attachment_filename='index.html')581 value, options = \582 parse_options_header(rv.headers['Content-Disposition'])583 assert value == 'attachment'584 assert options['filename'] == 'index.html'585 assert 'filename*' not in rv.headers['Content-Disposition']586 rv.close()587588 with app.test_request_context():589 rv = flask.send_file('static/index.html', as_attachment=True)590 value, options = parse_options_header(rv.headers['Content-Disposition'])591 assert value == 'attachment'592 assert options['filename'] == 'index.html'593 rv.close()594595 with app.test_request_context():596 rv = flask.send_file(StringIO('Test'), as_attachment=True,597 attachment_filename='index.txt',598 add_etags=False)599 assert rv.mimetype == 'text/plain'600 value, options = parse_options_header(rv.headers['Content-Disposition'])601 assert value == 'attachment'602 assert options['filename'] == 'index.txt'603 rv.close()604605 def test_attachment_with_utf8_filename(self):606 app = flask.Flask(__name__)607608 with app.test_request_context():609 rv = flask.send_file('static/index.html', as_attachment=True, attachment_filename=u'Ñandú/pingüino.txt')610 content_disposition = set(rv.headers['Content-Disposition'].split('; '))611 assert content_disposition == set((612 'attachment',613 'filename="Nandu/pinguino.txt"',614 "filename*=UTF-8''%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt"615 ))616 rv.close()617618 def test_static_file(self):619 app = flask.Flask(__name__)620 # default cache timeout is 12 hours621 with app.test_request_context():622 # Test with static file handler.623 rv = app.send_static_file('index.html')624 cc = parse_cache_control_header(rv.headers['Cache-Control'])625 assert cc.max_age == 12 * 60 * 60626 rv.close()627 # Test again with direct use of send_file utility.628 rv = flask.send_file('static/index.html')629 cc = parse_cache_control_header(rv.headers['Cache-Control'])630 assert cc.max_age == 12 * 60 * 60631 rv.close()632 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600633 with app.test_request_context():634 # Test with static file handler.635 rv = app.send_static_file('index.html')636 cc = parse_cache_control_header(rv.headers['Cache-Control'])637 assert cc.max_age == 3600638 rv.close()639 # Test again with direct use of send_file utility.640 rv = flask.send_file('static/index.html')641 cc = parse_cache_control_header(rv.headers['Cache-Control'])642 assert cc.max_age == 3600643 rv.close()644 class StaticFileApp(flask.Flask):645 def get_send_file_max_age(self, filename):646 return 10647 app = StaticFileApp(__name__)648 with app.test_request_context():649 # Test with static file handler.650 rv = app.send_static_file('index.html')651 cc = parse_cache_control_header(rv.headers['Cache-Control'])652 assert cc.max_age == 10653 rv.close()654 # Test again with direct use of send_file utility.655 rv = flask.send_file('static/index.html')656 cc = parse_cache_control_header(rv.headers['Cache-Control'])657 assert cc.max_age == 10658 rv.close()659660 def test_send_from_directory(self):661 app = flask.Flask(__name__)662 app.testing = True663 app.root_path = os.path.join(os.path.dirname(__file__),664 'test_apps', 'subdomaintestmodule')665 with app.test_request_context():666 rv = flask.send_from_directory('static', 'hello.txt')667 rv.direct_passthrough = False668 assert rv.data.strip() == b'Hello Subdomain'669 rv.close()670671 def test_send_from_directory_bad_request(self):672 app = flask.Flask(__name__)673 app.testing = True674 app.root_path = os.path.join(os.path.dirname(__file__),675 'test_apps', 'subdomaintestmodule')676 with app.test_request_context():677 with pytest.raises(BadRequest):678 flask.send_from_directory('static', 'bad\x00')679680class TestLogging(object):681682 def test_logger_cache(self):683 app = flask.Flask(__name__)684 logger1 = app.logger685 assert app.logger is logger1686 assert logger1.name == __name__687 app.logger_name = __name__ + '/test_logger_cache'688 assert app.logger is not logger1689690 def test_debug_log(self, capsys):691 app = flask.Flask(__name__)692 app.debug = True693694 @app.route('/')695 def index():696 app.logger.warning('the standard library is dead')697 app.logger.debug('this is a debug statement')698 return ''699700 @app.route('/exc')701 def exc():702 1 // 0703704 with app.test_client() as c:705 c.get('/')706 out, err = capsys.readouterr()707 assert 'WARNING in test_helpers [' in err708 assert os.path.basename(__file__.rsplit('.', 1)[0] + '.py') in err709 assert 'the standard library is dead' in err710 assert 'this is a debug statement' in err711712 with pytest.raises(ZeroDivisionError):713 c.get('/exc')714715 def test_debug_log_override(self):716 app = flask.Flask(__name__)717 app.debug = True718 app.logger_name = 'flask_tests/test_debug_log_override'719 app.logger.level = 10720 assert app.logger.level == 10721722 def test_exception_logging(self):723 out = StringIO()724 app = flask.Flask(__name__)725 app.config['LOGGER_HANDLER_POLICY'] = 'never'726 app.logger_name = 'flask_tests/test_exception_logging'727 app.logger.addHandler(StreamHandler(out))728729 @app.route('/')730 def index():731 1 // 0732733 rv = app.test_client().get('/')734 assert rv.status_code == 500735 assert b'Internal Server Error' in rv.data736737 err = out.getvalue()738 assert 'Exception on / [GET]' in err739 assert 'Traceback (most recent call last):' in err740 assert '1 // 0' in err741 assert 'ZeroDivisionError:' in err742743 def test_processor_exceptions(self):744 app = flask.Flask(__name__)745 app.config['LOGGER_HANDLER_POLICY'] = 'never'746 @app.before_request747 def before_request():748 if trigger == 'before':749 1 // 0750 @app.after_request751 def after_request(response):752 if trigger == 'after':753 1 // 0754 return response755 @app.route('/')756 def index():757 return 'Foo'758 @app.errorhandler(500)759 def internal_server_error(e):760 return 'Hello Server Error', 500761 for trigger in 'before', 'after':762 rv = app.test_client().get('/')763 assert rv.status_code == 500764 assert rv.data == b'Hello Server Error'765766 def test_url_for_with_anchor(self):767 app = flask.Flask(__name__)768 @app.route('/')769 def index():770 return '42'771 with app.test_request_context():772 assert flask.url_for('index', _anchor='x y') == '/#x%20y'773774 def test_url_for_with_scheme(self):775 app = flask.Flask(__name__)776 @app.route('/')777 def index():778 return '42'779 with app.test_request_context():780 assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'781782 def test_url_for_with_scheme_not_external(self):783 app = flask.Flask(__name__)784 @app.route('/')785 def index():786 return '42'787 with app.test_request_context():788 pytest.raises(ValueError,789 flask.url_for,790 'index',791 _scheme='https')792793 def test_url_for_with_alternating_schemes(self):794 app = flask.Flask(__name__)795 @app.route('/')796 def index():797 return '42'798 with app.test_request_context():799 assert flask.url_for('index', _external=True) == 'http://localhost/'800 assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'801 assert flask.url_for('index', _external=True) == 'http://localhost/'802803 def test_url_with_method(self):804 from flask.views import MethodView805 app = flask.Flask(__name__)806 class MyView(MethodView):807 def get(self, id=None):808 if id is None:809 return 'List'810 return 'Get %d' % id811 def post(self):812 return 'Create'813 myview = MyView.as_view('myview')814 app.add_url_rule('/myview/', methods=['GET'],815 view_func=myview)816 app.add_url_rule('/myview/<int:id>', methods=['GET'],817 view_func=myview)818 app.add_url_rule('/myview/create', methods=['POST'],819 view_func=myview)820821 with app.test_request_context():822 assert flask.url_for('myview', _method='GET') == '/myview/'823 assert flask.url_for('myview', id=42, _method='GET') == '/myview/42'824 assert flask.url_for('myview', _method='POST') == '/myview/create'825826827class TestNoImports(object):828 """Test Flasks are created without import.829830 Avoiding ``__import__`` helps create Flask instances where there are errors831 at import time. Those runtime errors will be apparent to the user soon832 enough, but tools which build Flask instances meta-programmatically benefit833 from a Flask which does not ``__import__``. Instead of importing to834 retrieve file paths or metadata on a module or package, use the pkgutil and835 imp modules in the Python standard library.836 """837838 def test_name_with_import_error(self, modules_tmpdir):839 modules_tmpdir.join('importerror.py').write('raise NotImplementedError()')840 try:841 flask.Flask('importerror')842 except NotImplementedError:843 assert False, 'Flask(import_name) is importing import_name.'844845846class TestStreaming(object):847848 def test_streaming_with_context(self):849 app = flask.Flask(__name__)850 app.testing = True851 @app.route('/')852 def index():853 def generate():854 yield 'Hello '855 yield flask.request.args['name']856 yield '!'857 return flask.Response(flask.stream_with_context(generate()))858 c = app.test_client()859 rv = c.get('/?name=World')860 assert rv.data == b'Hello World!'861862 def test_streaming_with_context_as_decorator(self):863 app = flask.Flask(__name__)864 app.testing = True865 @app.route('/')866 def index():867 @flask.stream_with_context868 def generate(hello):869 yield hello870 yield flask.request.args['name']871 yield '!'872 return flask.Response(generate('Hello '))873 c = app.test_client()874 rv = c.get('/?name=World')875 assert rv.data == b'Hello World!'876877 def test_streaming_with_context_and_custom_close(self):878 app = flask.Flask(__name__)879 app.testing = True880 called = []881 class Wrapper(object):882 def __init__(self, gen):883 self._gen = gen884 def __iter__(self):885 return self886 def close(self):887 called.append(42)888 def __next__(self):889 return next(self._gen)890 next = __next__891 @app.route('/')892 def index():893 def generate():894 yield 'Hello '895 yield flask.request.args['name']896 yield '!'897 return flask.Response(flask.stream_with_context(898 Wrapper(generate())))899 c = app.test_client()900 rv = c.get('/?name=World')901 assert rv.data == b'Hello World!'902 assert called == [42]903904905class TestSafeJoin(object):906 def test_safe_join(self):907 # Valid combinations of *args and expected joined paths.908 passing = (909 (('a/b/c',), 'a/b/c'),910 (('/', 'a/', 'b/', 'c/'), '/a/b/c'),911 (('a', 'b', 'c'), 'a/b/c'),912 (('/a', 'b/c'), '/a/b/c'),913 (('a/b', 'X/../c'), 'a/b/c'),914 (('/a/b', 'c/X/..'), '/a/b/c'),915 # If last path is '' add a slash916 (('/a/b/c', ''), '/a/b/c/'),917 # Preserve dot slash918 (('/a/b/c', './'), '/a/b/c/.'),919 (('a/b/c', 'X/..'), 'a/b/c/.'),920 # Base directory is always considered safe921 (('../', 'a/b/c'), '../a/b/c'),922 (('/..', ), '/..'),923 )924925 for args, expected in passing:926 assert flask.safe_join(*args) == expected927928 def test_safe_join_exceptions(self):929 # Should raise werkzeug.exceptions.NotFound on unsafe joins.930 failing = (931 # path.isabs and ``..'' checks932 ('/a', 'b', '/c'),933 ('/a', '../b/c'),934 ('/a', '..', 'b/c'),935 # Boundaries violations after path normalization936 ('/a', 'b/../b/../../c'),937 ('/a', 'b', 'c/../..'),938 ('/a', 'b/../../c'),939 )940941 for args in failing:942 with pytest.raises(NotFound):943 print(flask.safe_join(*args))
added:tests/test_instance_config.py+134 added
1# -*- coding: utf-8 -*-2"""3 tests.test_instance4 ~~~~~~~~~~~~~~~~~~~56 :copyright: (c) 2015 by the Flask Team, see AUTHORS for more details.7 :license: BSD, see LICENSE for more details.8"""9import os10import sys1112import pytest13import flask14from flask._compat import PY2151617def test_explicit_instance_paths(modules_tmpdir):18 with pytest.raises(ValueError) as excinfo:19 flask.Flask(__name__, instance_path='instance')20 assert 'must be absolute' in str(excinfo.value)2122 app = flask.Flask(__name__, instance_path=str(modules_tmpdir))23 assert app.instance_path == str(modules_tmpdir)242526def test_main_module_paths(modules_tmpdir, purge_module):27 app = modules_tmpdir.join('main_app.py')28 app.write('import flask\n\napp = flask.Flask("__main__")')29 purge_module('main_app')3031 from main_app import app32 here = os.path.abspath(os.getcwd())33 assert app.instance_path == os.path.join(here, 'instance')343536def test_uninstalled_module_paths(modules_tmpdir, purge_module):37 app = modules_tmpdir.join('config_module_app.py').write(38 'import os\n'39 'import flask\n'40 'here = os.path.abspath(os.path.dirname(__file__))\n'41 'app = flask.Flask(__name__)\n'42 )43 purge_module('config_module_app')4445 from config_module_app import app46 assert app.instance_path == str(modules_tmpdir.join('instance'))474849def test_uninstalled_package_paths(modules_tmpdir, purge_module):50 app = modules_tmpdir.mkdir('config_package_app')51 init = app.join('__init__.py')52 init.write(53 'import os\n'54 'import flask\n'55 'here = os.path.abspath(os.path.dirname(__file__))\n'56 'app = flask.Flask(__name__)\n'57 )58 purge_module('config_package_app')5960 from config_package_app import app61 assert app.instance_path == str(modules_tmpdir.join('instance'))626364def test_installed_module_paths(modules_tmpdir, modules_tmpdir_prefix,65 purge_module, site_packages, limit_loader):66 site_packages.join('site_app.py').write(67 'import flask\n'68 'app = flask.Flask(__name__)\n'69 )70 purge_module('site_app')7172 from site_app import app73 assert app.instance_path == \74 modules_tmpdir.join('var').join('site_app-instance')757677def test_installed_package_paths(limit_loader, modules_tmpdir,78 modules_tmpdir_prefix, purge_module,79 monkeypatch):80 installed_path = modules_tmpdir.mkdir('path')81 monkeypatch.syspath_prepend(installed_path)8283 app = installed_path.mkdir('installed_package')84 init = app.join('__init__.py')85 init.write('import flask\napp = flask.Flask(__name__)')86 purge_module('installed_package')8788 from installed_package import app89 assert app.instance_path == \90 modules_tmpdir.join('var').join('installed_package-instance')919293def test_prefix_package_paths(limit_loader, modules_tmpdir,94 modules_tmpdir_prefix, purge_module,95 site_packages):96 app = site_packages.mkdir('site_package')97 init = app.join('__init__.py')98 init.write('import flask\napp = flask.Flask(__name__)')99 purge_module('site_package')100101 import site_package102 assert site_package.app.instance_path == \103 modules_tmpdir.join('var').join('site_package-instance')104105106def test_egg_installed_paths(install_egg, modules_tmpdir,107 modules_tmpdir_prefix):108 modules_tmpdir.mkdir('site_egg').join('__init__.py').write(109 'import flask\n\napp = flask.Flask(__name__)'110 )111 install_egg('site_egg')112 try:113 import site_egg114 assert site_egg.app.instance_path == \115 str(modules_tmpdir.join('var/').join('site_egg-instance'))116 finally:117 if 'site_egg' in sys.modules:118 del sys.modules['site_egg']119120121@pytest.mark.skipif(not PY2, reason='This only works under Python 2.')122def test_meta_path_loader_without_is_package(request, modules_tmpdir):123 app = modules_tmpdir.join('unimportable.py')124 app.write('import flask\napp = flask.Flask(__name__)')125126 class Loader(object):127 def find_module(self, name, path=None):128 return self129130 sys.meta_path.append(Loader())131 request.addfinalizer(sys.meta_path.pop)132133 with pytest.raises(AttributeError):134 import unimportable
added:tests/test_regression.py+102 added
1# -*- coding: utf-8 -*-2"""3 tests.regression4 ~~~~~~~~~~~~~~~~~~~~~~~~~~56 Tests regressions.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1314import os15import gc16import sys17import flask18import threading19from werkzeug.exceptions import NotFound202122_gc_lock = threading.Lock()232425class assert_no_leak(object):2627 def __enter__(self):28 gc.disable()29 _gc_lock.acquire()30 loc = flask._request_ctx_stack._local3132 # Force Python to track this dictionary at all times.33 # This is necessary since Python only starts tracking34 # dicts if they contain mutable objects. It's a horrible,35 # horrible hack but makes this kinda testable.36 loc.__storage__['FOOO'] = [1, 2, 3]3738 gc.collect()39 self.old_objects = len(gc.get_objects())4041 def __exit__(self, exc_type, exc_value, tb):42 gc.collect()43 new_objects = len(gc.get_objects())44 if new_objects > self.old_objects:45 pytest.fail('Example code leaked')46 _gc_lock.release()47 gc.enable()484950def test_memory_consumption():51 app = flask.Flask(__name__)5253 @app.route('/')54 def index():55 return flask.render_template('simple_template.html', whiskey=42)5657 def fire():58 with app.test_client() as c:59 rv = c.get('/')60 assert rv.status_code == 20061 assert rv.data == b'<h1>42</h1>'6263 # Trigger caches64 fire()6566 # This test only works on CPython 2.7.67 if sys.version_info >= (2, 7) and \68 not hasattr(sys, 'pypy_translation_info'):69 with assert_no_leak():70 for x in range(10):71 fire()727374def test_safe_join_toplevel_pardir():75 from flask.helpers import safe_join76 with pytest.raises(NotFound):77 safe_join('/foo', '..')787980def test_aborting():81 class Foo(Exception):82 whatever = 4283 app = flask.Flask(__name__)84 app.testing = True8586 @app.errorhandler(Foo)87 def handle_foo(e):88 return str(e.whatever)8990 @app.route('/')91 def index():92 raise flask.abort(flask.redirect(flask.url_for('test')))9394 @app.route('/test')95 def test():96 raise Foo()9798 with app.test_client() as c:99 rv = c.get('/')100 assert rv.headers['Location'] == 'http://localhost/test'101 rv = c.get('/test')102 assert rv.data == b'42'
added:tests/test_reqctx.py+220 added
1# -*- coding: utf-8 -*-2"""3 tests.reqctx4 ~~~~~~~~~~~~56 Tests the request context.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1314import flask15from flask.sessions import SessionInterface1617try:18 from greenlet import greenlet19except ImportError:20 greenlet = None212223def test_teardown_on_pop():24 buffer = []25 app = flask.Flask(__name__)26 @app.teardown_request27 def end_of_request(exception):28 buffer.append(exception)2930 ctx = app.test_request_context()31 ctx.push()32 assert buffer == []33 ctx.pop()34 assert buffer == [None]3536def test_teardown_with_previous_exception():37 buffer = []38 app = flask.Flask(__name__)39 @app.teardown_request40 def end_of_request(exception):41 buffer.append(exception)4243 try:44 raise Exception('dummy')45 except Exception:46 pass4748 with app.test_request_context():49 assert buffer == []50 assert buffer == [None]5152def test_teardown_with_handled_exception():53 buffer = []54 app = flask.Flask(__name__)55 @app.teardown_request56 def end_of_request(exception):57 buffer.append(exception)5859 with app.test_request_context():60 assert buffer == []61 try:62 raise Exception('dummy')63 except Exception:64 pass65 assert buffer == [None]6667def test_proper_test_request_context():68 app = flask.Flask(__name__)69 app.config.update(70 SERVER_NAME='localhost.localdomain:5000'71 )7273 @app.route('/')74 def index():75 return None7677 @app.route('/', subdomain='foo')78 def sub():79 return None8081 with app.test_request_context('/'):82 assert flask.url_for('index', _external=True) == \83 'http://localhost.localdomain:5000/'8485 with app.test_request_context('/'):86 assert flask.url_for('sub', _external=True) == \87 'http://foo.localhost.localdomain:5000/'8889 try:90 with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}):91 pass92 except ValueError as e:93 assert str(e) == (94 "the server name provided "95 "('localhost.localdomain:5000') does not match the "96 "server name from the WSGI environment ('localhost')"97 )9899 app.config.update(SERVER_NAME='localhost')100 with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}):101 pass102103 app.config.update(SERVER_NAME='localhost:80')104 with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}):105 pass106107def test_context_binding():108 app = flask.Flask(__name__)109 @app.route('/')110 def index():111 return 'Hello %s!' % flask.request.args['name']112 @app.route('/meh')113 def meh():114 return flask.request.url115116 with app.test_request_context('/?name=World'):117 assert index() == 'Hello World!'118 with app.test_request_context('/meh'):119 assert meh() == 'http://localhost/meh'120 assert flask._request_ctx_stack.top is None121122def test_context_test():123 app = flask.Flask(__name__)124 assert not flask.request125 assert not flask.has_request_context()126 ctx = app.test_request_context()127 ctx.push()128 try:129 assert flask.request130 assert flask.has_request_context()131 finally:132 ctx.pop()133134def test_manual_context_binding():135 app = flask.Flask(__name__)136 @app.route('/')137 def index():138 return 'Hello %s!' % flask.request.args['name']139140 ctx = app.test_request_context('/?name=World')141 ctx.push()142 assert index() == 'Hello World!'143 ctx.pop()144 with pytest.raises(RuntimeError):145 index()146147@pytest.mark.skipif(greenlet is None, reason='greenlet not installed')148def test_greenlet_context_copying():149 app = flask.Flask(__name__)150 greenlets = []151152 @app.route('/')153 def index():154 reqctx = flask._request_ctx_stack.top.copy()155 def g():156 assert not flask.request157 assert not flask.current_app158 with reqctx:159 assert flask.request160 assert flask.current_app == app161 assert flask.request.path == '/'162 assert flask.request.args['foo'] == 'bar'163 assert not flask.request164 return 42165 greenlets.append(greenlet(g))166 return 'Hello World!'167168 rv = app.test_client().get('/?foo=bar')169 assert rv.data == b'Hello World!'170171 result = greenlets[0].run()172 assert result == 42173174@pytest.mark.skipif(greenlet is None, reason='greenlet not installed')175def test_greenlet_context_copying_api():176 app = flask.Flask(__name__)177 greenlets = []178179 @app.route('/')180 def index():181 reqctx = flask._request_ctx_stack.top.copy()182 @flask.copy_current_request_context183 def g():184 assert flask.request185 assert flask.current_app == app186 assert flask.request.path == '/'187 assert flask.request.args['foo'] == 'bar'188 return 42189 greenlets.append(greenlet(g))190 return 'Hello World!'191192 rv = app.test_client().get('/?foo=bar')193 assert rv.data == b'Hello World!'194195 result = greenlets[0].run()196 assert result == 42197198199def test_session_error_pops_context():200 class SessionError(Exception):201 pass202203 class FailingSessionInterface(SessionInterface):204 def open_session(self, app, request):205 raise SessionError()206207 class CustomFlask(flask.Flask):208 session_interface = FailingSessionInterface()209210 app = CustomFlask(__name__)211212 @app.route('/')213 def index():214 # shouldn't get here215 assert False216217 response = app.test_client().get('/')218 assert response.status_code == 500219 assert not flask.request220 assert not flask.current_app
added:tests/test_signals.py+202 added
1# -*- coding: utf-8 -*-2"""3 tests.signals4 ~~~~~~~~~~~~~~~~~~~~~~~56 Signalling.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1314try:15 import blinker16except ImportError:17 blinker = None1819import flask202122pytestmark = pytest.mark.skipif(23 blinker is None,24 reason='Signals require the blinker library.'25)2627def test_template_rendered():28 app = flask.Flask(__name__)2930 @app.route('/')31 def index():32 return flask.render_template('simple_template.html', whiskey=42)3334 recorded = []3536 def record(sender, template, context):37 recorded.append((template, context))3839 flask.template_rendered.connect(record, app)40 try:41 app.test_client().get('/')42 assert len(recorded) == 143 template, context = recorded[0]44 assert template.name == 'simple_template.html'45 assert context['whiskey'] == 4246 finally:47 flask.template_rendered.disconnect(record, app)4849def test_before_render_template():50 app = flask.Flask(__name__)5152 @app.route('/')53 def index():54 return flask.render_template('simple_template.html', whiskey=42)5556 recorded = []5758 def record(sender, template, context):59 context['whiskey'] = 4360 recorded.append((template, context))6162 flask.before_render_template.connect(record, app)63 try:64 rv = app.test_client().get('/')65 assert len(recorded) == 166 template, context = recorded[0]67 assert template.name == 'simple_template.html'68 assert context['whiskey'] == 4369 assert rv.data == b'<h1>43</h1>'70 finally:71 flask.before_render_template.disconnect(record, app)7273def test_request_signals():74 app = flask.Flask(__name__)75 calls = []7677 def before_request_signal(sender):78 calls.append('before-signal')7980 def after_request_signal(sender, response):81 assert response.data == b'stuff'82 calls.append('after-signal')8384 @app.before_request85 def before_request_handler():86 calls.append('before-handler')8788 @app.after_request89 def after_request_handler(response):90 calls.append('after-handler')91 response.data = 'stuff'92 return response9394 @app.route('/')95 def index():96 calls.append('handler')97 return 'ignored anyway'9899 flask.request_started.connect(before_request_signal, app)100 flask.request_finished.connect(after_request_signal, app)101102 try:103 rv = app.test_client().get('/')104 assert rv.data == b'stuff'105106 assert calls == ['before-signal', 'before-handler', 'handler',107 'after-handler', 'after-signal']108 finally:109 flask.request_started.disconnect(before_request_signal, app)110 flask.request_finished.disconnect(after_request_signal, app)111112def test_request_exception_signal():113 app = flask.Flask(__name__)114 recorded = []115116 @app.route('/')117 def index():118 1 // 0119120 def record(sender, exception):121 recorded.append(exception)122123 flask.got_request_exception.connect(record, app)124 try:125 assert app.test_client().get('/').status_code == 500126 assert len(recorded) == 1127 assert isinstance(recorded[0], ZeroDivisionError)128 finally:129 flask.got_request_exception.disconnect(record, app)130131def test_appcontext_signals():132 app = flask.Flask(__name__)133 recorded = []134135 def record_push(sender, **kwargs):136 recorded.append('push')137138 def record_pop(sender, **kwargs):139 recorded.append('pop')140141 @app.route('/')142 def index():143 return 'Hello'144145 flask.appcontext_pushed.connect(record_push, app)146 flask.appcontext_popped.connect(record_pop, app)147 try:148 with app.test_client() as c:149 rv = c.get('/')150 assert rv.data == b'Hello'151 assert recorded == ['push']152 assert recorded == ['push', 'pop']153 finally:154 flask.appcontext_pushed.disconnect(record_push, app)155 flask.appcontext_popped.disconnect(record_pop, app)156157def test_flash_signal():158 app = flask.Flask(__name__)159 app.config['SECRET_KEY'] = 'secret'160161 @app.route('/')162 def index():163 flask.flash('This is a flash message', category='notice')164 return flask.redirect('/other')165166 recorded = []167168 def record(sender, message, category):169 recorded.append((message, category))170171 flask.message_flashed.connect(record, app)172 try:173 client = app.test_client()174 with client.session_transaction():175 client.get('/')176 assert len(recorded) == 1177 message, category = recorded[0]178 assert message == 'This is a flash message'179 assert category == 'notice'180 finally:181 flask.message_flashed.disconnect(record, app)182183def test_appcontext_tearing_down_signal():184 app = flask.Flask(__name__)185 recorded = []186187 def record_teardown(sender, **kwargs):188 recorded.append(('tear_down', kwargs))189190 @app.route('/')191 def index():192 1 // 0193194 flask.appcontext_tearing_down.connect(record_teardown, app)195 try:196 with app.test_client() as c:197 rv = c.get('/')198 assert rv.status_code == 500199 assert recorded == []200 assert recorded == [('tear_down', {'exc': None})]201 finally:202 flask.appcontext_tearing_down.disconnect(record_teardown, app)
added:tests/test_subclassing.py+37 added
1# -*- coding: utf-8 -*-2"""3 tests.subclassing4 ~~~~~~~~~~~~~~~~~56 Test that certain behavior of flask can be customized by7 subclasses.89 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""12import flask13from logging import StreamHandler1415from flask._compat import StringIO161718def test_suppressed_exception_logging():19 class SuppressedFlask(flask.Flask):20 def log_exception(self, exc_info):21 pass2223 out = StringIO()24 app = SuppressedFlask(__name__)25 app.logger_name = 'flask_tests/test_suppressed_exception_logging'26 app.logger.addHandler(StreamHandler(out))2728 @app.route('/')29 def index():30 1 // 03132 rv = app.test_client().get('/')33 assert rv.status_code == 50034 assert b'Internal Server Error' in rv.data3536 err = out.getvalue()37 assert err == ''
added:tests/test_templating.py+392 added
1# -*- coding: utf-8 -*-2"""3 tests.templating4 ~~~~~~~~~~~~~~~~56 Template functionality78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1314import flask15import logging16from jinja2 import TemplateNotFound171819def test_context_processing():20 app = flask.Flask(__name__)21 @app.context_processor22 def context_processor():23 return {'injected_value': 42}24 @app.route('/')25 def index():26 return flask.render_template('context_template.html', value=23)27 rv = app.test_client().get('/')28 assert rv.data == b'<p>23|42'2930def test_original_win():31 app = flask.Flask(__name__)32 @app.route('/')33 def index():34 return flask.render_template_string('{{ config }}', config=42)35 rv = app.test_client().get('/')36 assert rv.data == b'42'3738def test_request_less_rendering():39 app = flask.Flask(__name__)40 app.config['WORLD_NAME'] = 'Special World'41 @app.context_processor42 def context_processor():43 return dict(foo=42)4445 with app.app_context():46 rv = flask.render_template_string('Hello {{ config.WORLD_NAME }} '47 '{{ foo }}')48 assert rv == 'Hello Special World 42'4950def test_standard_context():51 app = flask.Flask(__name__)52 app.secret_key = 'development key'53 @app.route('/')54 def index():55 flask.g.foo = 2356 flask.session['test'] = 'aha'57 return flask.render_template_string('''58 {{ request.args.foo }}59 {{ g.foo }}60 {{ config.DEBUG }}61 {{ session.test }}62 ''')63 rv = app.test_client().get('/?foo=42')64 assert rv.data.split() == [b'42', b'23', b'False', b'aha']6566def test_escaping():67 text = '<p>Hello World!'68 app = flask.Flask(__name__)69 @app.route('/')70 def index():71 return flask.render_template('escaping_template.html', text=text,72 html=flask.Markup(text))73 lines = app.test_client().get('/').data.splitlines()74 assert lines == [75 b'&lt;p&gt;Hello World!',76 b'<p>Hello World!',77 b'<p>Hello World!',78 b'<p>Hello World!',79 b'&lt;p&gt;Hello World!',80 b'<p>Hello World!'81 ]8283def test_no_escaping():84 text = '<p>Hello World!'85 app = flask.Flask(__name__)86 @app.route('/')87 def index():88 return flask.render_template('non_escaping_template.txt', text=text,89 html=flask.Markup(text))90 lines = app.test_client().get('/').data.splitlines()91 assert lines == [92 b'<p>Hello World!',93 b'<p>Hello World!',94 b'<p>Hello World!',95 b'<p>Hello World!',96 b'&lt;p&gt;Hello World!',97 b'<p>Hello World!',98 b'<p>Hello World!',99 b'<p>Hello World!'100 ]101102def test_escaping_without_template_filename():103 app = flask.Flask(__name__)104 with app.test_request_context():105 assert flask.render_template_string(106 '{{ foo }}', foo='<test>') == '&lt;test&gt;'107 assert flask.render_template('mail.txt', foo='<test>') == \108 '<test> Mail'109110def test_macros():111 app = flask.Flask(__name__)112 with app.test_request_context():113 macro = flask.get_template_attribute('_macro.html', 'hello')114 assert macro('World') == 'Hello World!'115116def test_template_filter():117 app = flask.Flask(__name__)118 @app.template_filter()119 def my_reverse(s):120 return s[::-1]121 assert 'my_reverse' in app.jinja_env.filters.keys()122 assert app.jinja_env.filters['my_reverse'] == my_reverse123 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'124125def test_add_template_filter():126 app = flask.Flask(__name__)127 def my_reverse(s):128 return s[::-1]129 app.add_template_filter(my_reverse)130 assert 'my_reverse' in app.jinja_env.filters.keys()131 assert app.jinja_env.filters['my_reverse'] == my_reverse132 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'133134def test_template_filter_with_name():135 app = flask.Flask(__name__)136 @app.template_filter('strrev')137 def my_reverse(s):138 return s[::-1]139 assert 'strrev' in app.jinja_env.filters.keys()140 assert app.jinja_env.filters['strrev'] == my_reverse141 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'142143def test_add_template_filter_with_name():144 app = flask.Flask(__name__)145 def my_reverse(s):146 return s[::-1]147 app.add_template_filter(my_reverse, 'strrev')148 assert 'strrev' in app.jinja_env.filters.keys()149 assert app.jinja_env.filters['strrev'] == my_reverse150 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'151152def test_template_filter_with_template():153 app = flask.Flask(__name__)154 @app.template_filter()155 def super_reverse(s):156 return s[::-1]157 @app.route('/')158 def index():159 return flask.render_template('template_filter.html', value='abcd')160 rv = app.test_client().get('/')161 assert rv.data == b'dcba'162163def test_add_template_filter_with_template():164 app = flask.Flask(__name__)165 def super_reverse(s):166 return s[::-1]167 app.add_template_filter(super_reverse)168 @app.route('/')169 def index():170 return flask.render_template('template_filter.html', value='abcd')171 rv = app.test_client().get('/')172 assert rv.data == b'dcba'173174def test_template_filter_with_name_and_template():175 app = flask.Flask(__name__)176 @app.template_filter('super_reverse')177 def my_reverse(s):178 return s[::-1]179 @app.route('/')180 def index():181 return flask.render_template('template_filter.html', value='abcd')182 rv = app.test_client().get('/')183 assert rv.data == b'dcba'184185def test_add_template_filter_with_name_and_template():186 app = flask.Flask(__name__)187 def my_reverse(s):188 return s[::-1]189 app.add_template_filter(my_reverse, 'super_reverse')190 @app.route('/')191 def index():192 return flask.render_template('template_filter.html', value='abcd')193 rv = app.test_client().get('/')194 assert rv.data == b'dcba'195196def test_template_test():197 app = flask.Flask(__name__)198 @app.template_test()199 def boolean(value):200 return isinstance(value, bool)201 assert 'boolean' in app.jinja_env.tests.keys()202 assert app.jinja_env.tests['boolean'] == boolean203 assert app.jinja_env.tests['boolean'](False)204205def test_add_template_test():206 app = flask.Flask(__name__)207 def boolean(value):208 return isinstance(value, bool)209 app.add_template_test(boolean)210 assert 'boolean' in app.jinja_env.tests.keys()211 assert app.jinja_env.tests['boolean'] == boolean212 assert app.jinja_env.tests['boolean'](False)213214def test_template_test_with_name():215 app = flask.Flask(__name__)216 @app.template_test('boolean')217 def is_boolean(value):218 return isinstance(value, bool)219 assert 'boolean' in app.jinja_env.tests.keys()220 assert app.jinja_env.tests['boolean'] == is_boolean221 assert app.jinja_env.tests['boolean'](False)222223def test_add_template_test_with_name():224 app = flask.Flask(__name__)225 def is_boolean(value):226 return isinstance(value, bool)227 app.add_template_test(is_boolean, 'boolean')228 assert 'boolean' in app.jinja_env.tests.keys()229 assert app.jinja_env.tests['boolean'] == is_boolean230 assert app.jinja_env.tests['boolean'](False)231232def test_template_test_with_template():233 app = flask.Flask(__name__)234 @app.template_test()235 def boolean(value):236 return isinstance(value, bool)237 @app.route('/')238 def index():239 return flask.render_template('template_test.html', value=False)240 rv = app.test_client().get('/')241 assert b'Success!' in rv.data242243def test_add_template_test_with_template():244 app = flask.Flask(__name__)245 def boolean(value):246 return isinstance(value, bool)247 app.add_template_test(boolean)248 @app.route('/')249 def index():250 return flask.render_template('template_test.html', value=False)251 rv = app.test_client().get('/')252 assert b'Success!' in rv.data253254def test_template_test_with_name_and_template():255 app = flask.Flask(__name__)256 @app.template_test('boolean')257 def is_boolean(value):258 return isinstance(value, bool)259 @app.route('/')260 def index():261 return flask.render_template('template_test.html', value=False)262 rv = app.test_client().get('/')263 assert b'Success!' in rv.data264265def test_add_template_test_with_name_and_template():266 app = flask.Flask(__name__)267 def is_boolean(value):268 return isinstance(value, bool)269 app.add_template_test(is_boolean, 'boolean')270 @app.route('/')271 def index():272 return flask.render_template('template_test.html', value=False)273 rv = app.test_client().get('/')274 assert b'Success!' in rv.data275276def test_add_template_global():277 app = flask.Flask(__name__)278 @app.template_global()279 def get_stuff():280 return 42281 assert 'get_stuff' in app.jinja_env.globals.keys()282 assert app.jinja_env.globals['get_stuff'] == get_stuff283 assert app.jinja_env.globals['get_stuff'](), 42284 with app.app_context():285 rv = flask.render_template_string('{{ get_stuff() }}')286 assert rv == '42'287288def test_custom_template_loader():289 class MyFlask(flask.Flask):290 def create_global_jinja_loader(self):291 from jinja2 import DictLoader292 return DictLoader({'index.html': 'Hello Custom World!'})293 app = MyFlask(__name__)294 @app.route('/')295 def index():296 return flask.render_template('index.html')297 c = app.test_client()298 rv = c.get('/')299 assert rv.data == b'Hello Custom World!'300301def test_iterable_loader():302 app = flask.Flask(__name__)303 @app.context_processor304 def context_processor():305 return {'whiskey': 'Jameson'}306 @app.route('/')307 def index():308 return flask.render_template(309 ['no_template.xml', # should skip this one310 'simple_template.html', # should render this311 'context_template.html'],312 value=23)313314 rv = app.test_client().get('/')315 assert rv.data == b'<h1>Jameson</h1>'316317def test_templates_auto_reload():318 # debug is False, config option is None319 app = flask.Flask(__name__)320 assert app.debug is False321 assert app.config['TEMPLATES_AUTO_RELOAD'] is None322 assert app.jinja_env.auto_reload is False323 # debug is False, config option is False324 app = flask.Flask(__name__)325 app.config['TEMPLATES_AUTO_RELOAD'] = False326 assert app.debug is False327 assert app.jinja_env.auto_reload is False328 # debug is False, config option is True329 app = flask.Flask(__name__)330 app.config['TEMPLATES_AUTO_RELOAD'] = True331 assert app.debug is False332 assert app.jinja_env.auto_reload is True333 # debug is True, config option is None334 app = flask.Flask(__name__)335 app.config['DEBUG'] = True336 assert app.config['TEMPLATES_AUTO_RELOAD'] is None337 assert app.jinja_env.auto_reload is True338 # debug is True, config option is False339 app = flask.Flask(__name__)340 app.config['DEBUG'] = True341 app.config['TEMPLATES_AUTO_RELOAD'] = False342 assert app.jinja_env.auto_reload is False343 # debug is True, config option is True344 app = flask.Flask(__name__)345 app.config['DEBUG'] = True346 app.config['TEMPLATES_AUTO_RELOAD'] = True347 assert app.jinja_env.auto_reload is True348349def test_template_loader_debugging(test_apps):350 from blueprintapp import app351352 called = []353 class _TestHandler(logging.Handler):354 def handle(x, record):355 called.append(True)356 text = str(record.msg)357 assert '1: trying loader of application "blueprintapp"' in text358 assert ('2: trying loader of blueprint "admin" '359 '(blueprintapp.apps.admin)') in text360 assert ('trying loader of blueprint "frontend" '361 '(blueprintapp.apps.frontend)') in text362 assert 'Error: the template could not be found' in text363 assert ('looked up from an endpoint that belongs to '364 'the blueprint "frontend"') in text365 assert 'See http://flask.pocoo.org/docs/blueprints/#templates' in text366367 with app.test_client() as c:368 try:369 old_load_setting = app.config['EXPLAIN_TEMPLATE_LOADING']370 old_handlers = app.logger.handlers[:]371 app.logger.handlers = [_TestHandler()]372 app.config['EXPLAIN_TEMPLATE_LOADING'] = True373374 with pytest.raises(TemplateNotFound) as excinfo:375 c.get('/missing')376377 assert 'missing_template.html' in str(excinfo.value)378 finally:379 app.logger.handlers[:] = old_handlers380 app.config['EXPLAIN_TEMPLATE_LOADING'] = old_load_setting381382 assert len(called) == 1383384def test_custom_jinja_env():385 class CustomEnvironment(flask.templating.Environment):386 pass387388 class CustomFlask(flask.Flask):389 jinja_environment = CustomEnvironment390391 app = CustomFlask(__name__)392 assert isinstance(app.jinja_env, CustomEnvironment)
added:tests/test_testing.py+271 added
1# -*- coding: utf-8 -*-2"""3 tests.testing4 ~~~~~~~~~~~~~56 Test client and more.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import pytest1213import flask14import werkzeug1516from flask._compat import text_type171819def test_environ_defaults_from_config():20 app = flask.Flask(__name__)21 app.testing = True22 app.config['SERVER_NAME'] = 'example.com:1234'23 app.config['APPLICATION_ROOT'] = '/foo'24 @app.route('/')25 def index():26 return flask.request.url2728 ctx = app.test_request_context()29 assert ctx.request.url == 'http://example.com:1234/foo/'30 with app.test_client() as c:31 rv = c.get('/')32 assert rv.data == b'http://example.com:1234/foo/'3334def test_environ_defaults():35 app = flask.Flask(__name__)36 app.testing = True37 @app.route('/')38 def index():39 return flask.request.url4041 ctx = app.test_request_context()42 assert ctx.request.url == 'http://localhost/'43 with app.test_client() as c:44 rv = c.get('/')45 assert rv.data == b'http://localhost/'4647def test_environ_base_default():48 app = flask.Flask(__name__)49 app.testing = True50 @app.route('/')51 def index():52 flask.g.user_agent = flask.request.headers["User-Agent"]53 return flask.request.remote_addr5455 with app.test_client() as c:56 rv = c.get('/')57 assert rv.data == b'127.0.0.1'58 assert flask.g.user_agent == 'werkzeug/' + werkzeug.__version__5960def test_environ_base_modified():61 app = flask.Flask(__name__)62 app.testing = True63 @app.route('/')64 def index():65 flask.g.user_agent = flask.request.headers["User-Agent"]66 return flask.request.remote_addr6768 with app.test_client() as c:69 c.environ_base['REMOTE_ADDR'] = '0.0.0.0'70 c.environ_base['HTTP_USER_AGENT'] = 'Foo'71 rv = c.get('/')72 assert rv.data == b'0.0.0.0'73 assert flask.g.user_agent == 'Foo'7475 c.environ_base['REMOTE_ADDR'] = '0.0.0.1'76 c.environ_base['HTTP_USER_AGENT'] = 'Bar'77 rv = c.get('/')78 assert rv.data == b'0.0.0.1'79 assert flask.g.user_agent == 'Bar'8081def test_redirect_keep_session():82 app = flask.Flask(__name__)83 app.secret_key = 'testing'8485 @app.route('/', methods=['GET', 'POST'])86 def index():87 if flask.request.method == 'POST':88 return flask.redirect('/getsession')89 flask.session['data'] = 'foo'90 return 'index'9192 @app.route('/getsession')93 def get_session():94 return flask.session.get('data', '<missing>')9596 with app.test_client() as c:97 rv = c.get('/getsession')98 assert rv.data == b'<missing>'99100 rv = c.get('/')101 assert rv.data == b'index'102 assert flask.session.get('data') == 'foo'103 rv = c.post('/', data={}, follow_redirects=True)104 assert rv.data == b'foo'105106 # This support requires a new Werkzeug version107 if not hasattr(c, 'redirect_client'):108 assert flask.session.get('data') == 'foo'109110 rv = c.get('/getsession')111 assert rv.data == b'foo'112113def test_session_transactions():114 app = flask.Flask(__name__)115 app.testing = True116 app.secret_key = 'testing'117118 @app.route('/')119 def index():120 return text_type(flask.session['foo'])121122 with app.test_client() as c:123 with c.session_transaction() as sess:124 assert len(sess) == 0125 sess['foo'] = [42]126 assert len(sess) == 1127 rv = c.get('/')128 assert rv.data == b'[42]'129 with c.session_transaction() as sess:130 assert len(sess) == 1131 assert sess['foo'] == [42]132133def test_session_transactions_no_null_sessions():134 app = flask.Flask(__name__)135 app.testing = True136137 with app.test_client() as c:138 with pytest.raises(RuntimeError) as e:139 with c.session_transaction() as sess:140 pass141 assert 'Session backend did not open a session' in str(e.value)142143def test_session_transactions_keep_context():144 app = flask.Flask(__name__)145 app.testing = True146 app.secret_key = 'testing'147148 with app.test_client() as c:149 rv = c.get('/')150 req = flask.request._get_current_object()151 assert req is not None152 with c.session_transaction():153 assert req is flask.request._get_current_object()154155def test_session_transaction_needs_cookies():156 app = flask.Flask(__name__)157 app.testing = True158 c = app.test_client(use_cookies=False)159 with pytest.raises(RuntimeError) as e:160 with c.session_transaction() as s:161 pass162 assert 'cookies' in str(e.value)163164def test_test_client_context_binding():165 app = flask.Flask(__name__)166 app.config['LOGGER_HANDLER_POLICY'] = 'never'167 @app.route('/')168 def index():169 flask.g.value = 42170 return 'Hello World!'171172 @app.route('/other')173 def other():174 1 // 0175176 with app.test_client() as c:177 resp = c.get('/')178 assert flask.g.value == 42179 assert resp.data == b'Hello World!'180 assert resp.status_code == 200181182 resp = c.get('/other')183 assert not hasattr(flask.g, 'value')184 assert b'Internal Server Error' in resp.data185 assert resp.status_code == 500186 flask.g.value = 23187188 try:189 flask.g.value190 except (AttributeError, RuntimeError):191 pass192 else:193 raise AssertionError('some kind of exception expected')194195def test_reuse_client():196 app = flask.Flask(__name__)197 c = app.test_client()198199 with c:200 assert c.get('/').status_code == 404201202 with c:203 assert c.get('/').status_code == 404204205def test_test_client_calls_teardown_handlers():206 app = flask.Flask(__name__)207 called = []208 @app.teardown_request209 def remember(error):210 called.append(error)211212 with app.test_client() as c:213 assert called == []214 c.get('/')215 assert called == []216 assert called == [None]217218 del called[:]219 with app.test_client() as c:220 assert called == []221 c.get('/')222 assert called == []223 c.get('/')224 assert called == [None]225 assert called == [None, None]226227def test_full_url_request():228 app = flask.Flask(__name__)229 app.testing = True230231 @app.route('/action', methods=['POST'])232 def action():233 return 'x'234235 with app.test_client() as c:236 rv = c.post('http://domain.com/action?vodka=42', data={'gin': 43})237 assert rv.status_code == 200238 assert 'gin' in flask.request.form239 assert 'vodka' in flask.request.args240241def test_subdomain():242 app = flask.Flask(__name__)243 app.config['SERVER_NAME'] = 'example.com'244 @app.route('/', subdomain='<company_id>')245 def view(company_id):246 return company_id247248 with app.test_request_context():249 url = flask.url_for('view', company_id='xxx')250251 with app.test_client() as c:252 response = c.get(url)253254 assert 200 == response.status_code255 assert b'xxx' == response.data256257def test_nosubdomain():258 app = flask.Flask(__name__)259 app.config['SERVER_NAME'] = 'example.com'260 @app.route('/<company_id>')261 def view(company_id):262 return company_id263264 with app.test_request_context():265 url = flask.url_for('view', company_id='xxx')266267 with app.test_client() as c:268 response = c.get(url)269270 assert 200 == response.status_code271 assert b'xxx' == response.data
added:tests/test_user_error_handler.py+140 added
1# -*- coding: utf-8 -*-2from werkzeug.exceptions import Forbidden, InternalServerError3import flask456def test_error_handler_no_match():7 app = flask.Flask(__name__)89 class CustomException(Exception):10 pass1112 @app.errorhandler(CustomException)13 def custom_exception_handler(e):14 assert isinstance(e, CustomException)15 return 'custom'1617 @app.errorhandler(500)18 def handle_500(e):19 return type(e).__name__2021 @app.route('/custom')22 def custom_test():23 raise CustomException()2425 @app.route('/keyerror')26 def key_error():27 raise KeyError()2829 c = app.test_client()3031 assert c.get('/custom').data == b'custom'32 assert c.get('/keyerror').data == b'KeyError'333435def test_error_handler_subclass():36 app = flask.Flask(__name__)3738 class ParentException(Exception):39 pass4041 class ChildExceptionUnregistered(ParentException):42 pass4344 class ChildExceptionRegistered(ParentException):45 pass4647 @app.errorhandler(ParentException)48 def parent_exception_handler(e):49 assert isinstance(e, ParentException)50 return 'parent'5152 @app.errorhandler(ChildExceptionRegistered)53 def child_exception_handler(e):54 assert isinstance(e, ChildExceptionRegistered)55 return 'child-registered'5657 @app.route('/parent')58 def parent_test():59 raise ParentException()6061 @app.route('/child-unregistered')62 def unregistered_test():63 raise ChildExceptionUnregistered()6465 @app.route('/child-registered')66 def registered_test():67 raise ChildExceptionRegistered()6869 c = app.test_client()7071 assert c.get('/parent').data == b'parent'72 assert c.get('/child-unregistered').data == b'parent'73 assert c.get('/child-registered').data == b'child-registered'747576def test_error_handler_http_subclass():77 app = flask.Flask(__name__)7879 class ForbiddenSubclassRegistered(Forbidden):80 pass8182 class ForbiddenSubclassUnregistered(Forbidden):83 pass8485 @app.errorhandler(403)86 def code_exception_handler(e):87 assert isinstance(e, Forbidden)88 return 'forbidden'8990 @app.errorhandler(ForbiddenSubclassRegistered)91 def subclass_exception_handler(e):92 assert isinstance(e, ForbiddenSubclassRegistered)93 return 'forbidden-registered'9495 @app.route('/forbidden')96 def forbidden_test():97 raise Forbidden()9899 @app.route('/forbidden-registered')100 def registered_test():101 raise ForbiddenSubclassRegistered()102103 @app.route('/forbidden-unregistered')104 def unregistered_test():105 raise ForbiddenSubclassUnregistered()106107 c = app.test_client()108109 assert c.get('/forbidden').data == b'forbidden'110 assert c.get('/forbidden-unregistered').data == b'forbidden'111 assert c.get('/forbidden-registered').data == b'forbidden-registered'112113114def test_error_handler_blueprint():115 bp = flask.Blueprint('bp', __name__)116117 @bp.errorhandler(500)118 def bp_exception_handler(e):119 return 'bp-error'120121 @bp.route('/error')122 def bp_test():123 raise InternalServerError()124125 app = flask.Flask(__name__)126127 @app.errorhandler(500)128 def app_exception_handler(e):129 return 'app-error'130131 @app.route('/error')132 def app_test():133 raise InternalServerError()134135 app.register_blueprint(bp, url_prefix='/bp')136137 c = app.test_client()138139 assert c.get('/error').data == b'app-error'140 assert c.get('/bp/error').data == b'bp-error'
added:tests/test_views.py+204 added
1# -*- coding: utf-8 -*-2"""3 tests.views4 ~~~~~~~~~~~56 Pluggable views.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1314import flask15import flask.views1617from werkzeug.http import parse_set_header1819def common_test(app):20 c = app.test_client()2122 assert c.get('/').data == b'GET'23 assert c.post('/').data == b'POST'24 assert c.put('/').status_code == 40525 meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])26 assert sorted(meths) == ['GET', 'HEAD', 'OPTIONS', 'POST']2728def test_basic_view():29 app = flask.Flask(__name__)3031 class Index(flask.views.View):32 methods = ['GET', 'POST']33 def dispatch_request(self):34 return flask.request.method3536 app.add_url_rule('/', view_func=Index.as_view('index'))37 common_test(app)3839def test_method_based_view():40 app = flask.Flask(__name__)4142 class Index(flask.views.MethodView):43 def get(self):44 return 'GET'45 def post(self):46 return 'POST'4748 app.add_url_rule('/', view_func=Index.as_view('index'))4950 common_test(app)5152def test_view_patching():53 app = flask.Flask(__name__)5455 class Index(flask.views.MethodView):56 def get(self):57 1 // 058 def post(self):59 1 // 06061 class Other(Index):62 def get(self):63 return 'GET'64 def post(self):65 return 'POST'6667 view = Index.as_view('index')68 view.view_class = Other69 app.add_url_rule('/', view_func=view)70 common_test(app)7172def test_view_inheritance():73 app = flask.Flask(__name__)7475 class Index(flask.views.MethodView):76 def get(self):77 return 'GET'78 def post(self):79 return 'POST'8081 class BetterIndex(Index):82 def delete(self):83 return 'DELETE'8485 app.add_url_rule('/', view_func=BetterIndex.as_view('index'))86 c = app.test_client()8788 meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])89 assert sorted(meths) == ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST']9091def test_view_decorators():92 app = flask.Flask(__name__)9394 def add_x_parachute(f):95 def new_function(*args, **kwargs):96 resp = flask.make_response(f(*args, **kwargs))97 resp.headers['X-Parachute'] = 'awesome'98 return resp99 return new_function100101 class Index(flask.views.View):102 decorators = [add_x_parachute]103 def dispatch_request(self):104 return 'Awesome'105106 app.add_url_rule('/', view_func=Index.as_view('index'))107 c = app.test_client()108 rv = c.get('/')109 assert rv.headers['X-Parachute'] == 'awesome'110 assert rv.data == b'Awesome'111112def test_implicit_head():113 app = flask.Flask(__name__)114115 class Index(flask.views.MethodView):116 def get(self):117 return flask.Response('Blub', headers={118 'X-Method': flask.request.method119 })120121 app.add_url_rule('/', view_func=Index.as_view('index'))122 c = app.test_client()123 rv = c.get('/')124 assert rv.data == b'Blub'125 assert rv.headers['X-Method'] == 'GET'126 rv = c.head('/')127 assert rv.data == b''128 assert rv.headers['X-Method'] == 'HEAD'129130def test_explicit_head():131 app = flask.Flask(__name__)132133 class Index(flask.views.MethodView):134 def get(self):135 return 'GET'136 def head(self):137 return flask.Response('', headers={'X-Method': 'HEAD'})138139 app.add_url_rule('/', view_func=Index.as_view('index'))140 c = app.test_client()141 rv = c.get('/')142 assert rv.data == b'GET'143 rv = c.head('/')144 assert rv.data == b''145 assert rv.headers['X-Method'] == 'HEAD'146147def test_endpoint_override():148 app = flask.Flask(__name__)149 app.debug = True150151 class Index(flask.views.View):152 methods = ['GET', 'POST']153 def dispatch_request(self):154 return flask.request.method155156 app.add_url_rule('/', view_func=Index.as_view('index'))157158 with pytest.raises(AssertionError):159 app.add_url_rule('/', view_func=Index.as_view('index'))160161 # But these tests should still pass. We just log a warning.162 common_test(app)163164def test_multiple_inheritance():165 app = flask.Flask(__name__)166167 class GetView(flask.views.MethodView):168 def get(self):169 return 'GET'170171 class DeleteView(flask.views.MethodView):172 def delete(self):173 return 'DELETE'174175 class GetDeleteView(GetView, DeleteView):176 pass177178 app.add_url_rule('/', view_func=GetDeleteView.as_view('index'))179180 c = app.test_client()181 assert c.get('/').data == b'GET'182 assert c.delete('/').data == b'DELETE'183 assert sorted(GetDeleteView.methods) == ['DELETE', 'GET']184185def test_remove_method_from_parent():186 app = flask.Flask(__name__)187188 class GetView(flask.views.MethodView):189 def get(self):190 return 'GET'191192 class OtherView(flask.views.MethodView):193 def post(self):194 return 'POST'195196 class View(GetView, OtherView):197 methods = ['GET']198199 app.add_url_rule('/', view_func=View.as_view('index'))200201 c = app.test_client()202 assert c.get('/').data == b'GET'203 assert c.post('/').status_code == 405204 assert sorted(View.methods) == ['GET']
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
deleted:.travis-devel-requirements.txt-6 removed
1git+git://github.com/mitsuhiko/werkzeug.git#egg=Werkzeug2git+git://github.com/mitsuhiko/jinja2.git#egg=Jinja23git+git://github.com/mitsuhiko/itsdangerous.git#egg=itsdangerous45# extra dependencies6git+git://github.com/jek/blinker.git#egg=blinker
deleted:.travis-lowest-requirements.txt-6 removed
1Werkzeug==0.72Jinja2==2.43itsdangerous==0.2145# extra dependencies6blinker==1.0
deleted:.travis-release-requirements.txt-2 removed
1# extra dependencies2blinker
modified:.travis.yml+24 added-3 removed
1sudo: false2language: python34python:5 - "2.6"6 - "2.7"7 - "pypy"8 - "3.3"9 - "3.4"10 - "3.5"11 - "3.6"1213env:14 - REQUIREMENTS=lowest15 - REQUIREMENTS=lowest-simplejson16 - REQUIREMENTS=release17 - REQUIREMENTS=release-simplejson18 - REQUIREMENTS=devel19 - REQUIREMENTS=devel-simplejson2021matrix:22 exclude:23 # Python 3 support currently does not work with lowest requirements24 - python: "3.3"25 env: REQUIREMENTS=lowest26 - python: "3.3"27 env: REQUIREMENTS=lowest-simplejson28 - python: "3.4"29 env: REQUIREMENTS=lowest30 - python: "3.4"31 env: REQUIREMENTS=lowest-simplejson32 - python: "3.5"33 env: REQUIREMENTS=lowest34 - python: "3.5"35 env: REQUIREMENTS=lowest-simplejson36 - python: "3.6"37 env: REQUIREMENTS=lowest38 - python: "3.6"39 env: REQUIREMENTS=lowest-simplejson4041install:21 - pip install -r .travis-$REQUIREMENTS-requirements.txt22 - pip install --editable .42 - pip install tox4324script: make test44script:45 - tox -e py-$REQUIREMENTS4647branches:48 except:49 - website
10 unmodified lines
modified:AUTHORS+7 added-1 removed
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 Sigler29- Martijn Pieters30- Matt Campell31- Matthew Frazier32- Michael van Tellingen33- Ron DuPlain
1 unmodified line
35- Simon Sapin36- Stephane Wirtel37- Thomas Schranz38- Zhao Xiaohong32- Edmond Burnett
modified:CHANGES+185 added-24 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`_)4344.. _#1489: https://github.com/pallets/flask/pull/148945.. _#1898: https://github.com/pallets/flask/pull/189846.. _#1936: https://github.com/pallets/flask/pull/193647.. _#2017: https://github.com/pallets/flask/pull/201748.. _#2223: https://github.com/pallets/flask/pull/222349.. _#2254: https://github.com/pallets/flask/pull/225450.. _#2256: https://github.com/pallets/flask/pull/225651.. _#2259: https://github.com/pallets/flask/pull/225952.. _#2282: https://github.com/pallets/flask/pull/22825354Version 0.12.255--------------5657Released on May 16 20175859- Fix a bug in `safe_join` on Windows.6061Version 0.12.162--------------6364Bugfix release, released on March 31st 20176566- Prevent `flask run` from showing a NoAppException when an ImportError occurs67 within the imported application module.68- Fix encoding behavior of ``app.config.from_pyfile`` for Python 3. Fix69 ``#2118``.70- Use the ``SERVER_NAME`` config if it is present as default values for71 ``app.run``. ``#2109``, ``#2152``72- Call `ctx.auto_pop` with the exception object instead of `None`, in the73 event that a `BaseException` such as `KeyboardInterrupt` is raised in a74 request handler.7576Version 0.1277------------7879Released on December 21st 2016, codename Punsch.8081- the cli command now responds to `--version`.82- Mimetype guessing and ETag generation for file-like objects in ``send_file``83 has been removed, as per issue ``#104``. See pull request ``#1849``.84- Mimetype guessing in ``send_file`` now fails loudly and doesn't fall back to85 ``application/octet-stream``. See pull request ``#1988``.86- Make ``flask.safe_join`` able to join multiple paths like ``os.path.join``87 (pull request ``#1730``).88- Revert a behavior change that made the dev server crash instead of returning89 a Internal Server Error (pull request ``#2006``).90- Correctly invoke response handlers for both regular request dispatching as91 well as error handlers.92- Disable logger propagation by default for the app logger.93- Add support for range requests in ``send_file``.94- ``app.test_client`` includes preset default environment, which can now be95 directly set, instead of per ``client.get``.9697Version 0.11.298--------------99100Bugfix release, unreleased101102- Fix crash when running under PyPy3, see pull request ``#1814``.103104Version 0.11.1105--------------106107Bugfix release, released on June 7th 2016.108109- Fixed a bug that prevented ``FLASK_APP=foobar/__init__.py`` from working. See110 pull request ``#1872``.111112Version 0.11113------------114115Released on May 29th 2016, codename Absinthe.116117- Added support to serializing top-level arrays to :func:`flask.jsonify`. This118 introduces a security risk in ancient browsers. See119 :ref:`json-security` for details.120- Added before_render_template signal.121- Added `**kwargs` to :meth:`flask.Test.test_client` to support passing122 additional keyword arguments to the constructor of123 :attr:`flask.Flask.test_client_class`.124- Added ``SESSION_REFRESH_EACH_REQUEST`` config key that controls the12 set-cookie behavior. If set to `True` a permanent session will be125 set-cookie behavior. If set to ``True`` a permanent session will be126 refreshed each request and get their lifetime extended, if set to14 `False` it will only be modified if the session actually modifies.127 ``False`` it will only be modified if the session actually modifies.128 Non permanent sessions are not affected by this and will always129 expire if the browser window closes.130- Made Flask support custom JSON mimetypes for incoming data.131- Added support for returning tuples in the form ``(response, headers)``132 from a view function.133- Added :meth:`flask.Config.from_json`.134- Added :attr:`flask.Flask.config_class`.22- Added :meth:`flask.config.Config.get_namespace`.23- Added ``TEMPLATES_AUTO_RELOAD`` config key. If disabled the 24 templates will be reloaded only if the application is running in 25 debug mode. For higher performance it’s possible to disable that.135- Added :meth:`flask.Config.get_namespace`.136- Templates are no longer automatically reloaded outside of debug mode. This137 can be configured with the new ``TEMPLATES_AUTO_RELOAD`` config key.138- Added a workaround for a limitation in Python 3.3's namespace loader.139- Added support for explicit root paths when using Python 3.3's namespace140 packages.141- Added :command:`flask` and the ``flask.cli`` module to start the local142 debug server through the click CLI system. This is recommended over the old143 ``flask.run()`` method as it works faster and more reliable due to a144 different design and also replaces ``Flask-Script``.145- Error handlers that match specific classes are now checked first,146 thereby allowing catching exceptions that are subclasses of HTTP147 exceptions (in ``werkzeug.exceptions``). This makes it possible148 for an extension author to create exceptions that will by default149 result in the HTTP error of their choosing, but may be caught with150 a custom error handler if desired.151- Added :meth:`flask.Config.from_mapping`.152- Flask will now log by default even if debug is disabled. The log format is153 now hardcoded but the default log handling can be disabled through the154 ``LOGGER_HANDLER_POLICY`` configuration key.155- Removed deprecated module functionality.156- Added the ``EXPLAIN_TEMPLATE_LOADING`` config flag which when enabled will157 instruct Flask to explain how it locates templates. This should help158 users debug when the wrong templates are loaded.159- Enforce blueprint handling in the order they were registered for template160 loading.161- Ported test suite to py.test.162- Deprecated ``request.json`` in favour of ``request.get_json()``.163- Add "pretty" and "compressed" separators definitions in jsonify() method.164 Reduces JSON response size when JSONIFY_PRETTYPRINT_REGULAR=False by removing165 unnecessary white space included by default after separators.166- JSON responses are now terminated with a newline character, because it is a167 convention that UNIX text files end with a newline and some clients don't168 deal well when this newline is missing. See169 https://github.com/pallets/flask/pull/1262 -- this came up originally as a170 part of https://github.com/kennethreitz/httpbin/issues/168171- The automatically provided ``OPTIONS`` method is now correctly disabled if172 the user registered an overriding rule with the lowercase-version173 ``options`` (issue ``#1288``).174- ``flask.json.jsonify`` now supports the ``datetime.date`` type (pull request175 ``#1326``).176- Don't leak exception info of already catched exceptions to context teardown177 handlers (pull request ``#1393``).178- Allow custom Jinja environment subclasses (pull request ``#1422``).179- ``flask.g`` now has ``pop()`` and ``setdefault`` methods.180- Turn on autoescape for ``flask.templating.render_template_string`` by default181 (pull request ``#1515``).182- ``flask.ext`` is now deprecated (pull request ``#1484``).183- ``send_from_directory`` now raises BadRequest if the filename is invalid on184 the server OS (pull request ``#1763``).185- Added the ``JSONIFY_MIMETYPE`` configuration variable (pull request ``#1728``).186- Exceptions during teardown handling will no longer leave bad application187 contexts lingering around.188189Version 0.10.2190--------------191
13 unmodified lines
205 correctly.206- Changed logic of before first request handlers to flip the flag after207 invoking. This will allow some uses that are potentially dangerous but208 should probably be permitted.209- Fixed Python 3 bug when a handler from `app.url_build_error_handlers`210 reraises the `BuildError`.211212Version 0.10.1213--------------214
11 unmodified lines
226227Version 0.10228------------22969Released on June 13nd 2013, codename Limoncello.230Released on June 13th 2013, codename Limoncello.231232- Changed default cookie serialization format from pickle to JSON to233 limit the impact an attacker can do if the secret key leaks. See234 :ref:`upgrading-to-010` for more information.
80 unmodified lines
315- Logger now only returns the debug log setting if it was not set316 explicitly.317- Unregister a circular dependency between the WSGI environment and318 the request object when shutting down the request. This means that158 environ ``werkzeug.request`` will be `None` after the response was319 environ ``werkzeug.request`` will be ``None`` after the response was320 returned to the WSGI server but has the advantage that the garbage321 collector is not needed on CPython to tear down the request unless322 the user created circular dependencies themselves.323- Session is now stored after callbacks so that if the session payload
12 unmodified lines
336 :meth:`flask.Blueprint.add_app_template_filter`.337- The :func:`flask.get_flashed_messages` function now allows rendering flashed338 message categories in separate blocks, through a ``category_filter``339 argument.179- The :meth:`flask.Flask.run` method now accepts `None` for `host` and `port`180 arguments, using default values when `None`. This allows for calling run340- The :meth:`flask.Flask.run` method now accepts ``None`` for `host` and `port`341 arguments, using default values when ``None``. This allows for calling run342 using configuration values, e.g. ``app.run(app.config.get('MYHOST'),343 app.config.get('MYPORT'))``, with proper behavior whether or not a config344 file is provided.345- The :meth:`flask.render_template` method now accepts a either an iterable of
60 unmodified lines
406 error if not handled. This is a backwards incompatible change.407- Applications now not only have a root path where the resources and modules408 are located but also an instance path which is the designated place to409 drop files that are modified at runtime (uploads etc.). Also this is249 conceptionally only instance depending and outside version control so it's410 conceptually only instance depending and outside version control so it's411 the perfect place to put configuration files etc. For more information412 see :ref:`instance-folders`.413- Added the ``APPLICATION_ROOT`` configuration variable.414- Implemented :meth:`~flask.testing.TestClient.session_transaction` to
43 unmodified lines
458Released on June 28th 2011, codename Grappa459460- Added :meth:`~flask.Flask.make_default_options_response`461 which can be used by subclasses to alter the default301 behavior for `OPTIONS` responses.462 behavior for ``OPTIONS`` responses.463- Unbound locals now raise a proper :exc:`RuntimeError` instead464 of an :exc:`AttributeError`.465- Mimetype guessing and etag support based on file objects is now466 deprecated for :func:`flask.send_file` because it was unreliable.
4 unmodified lines
471 was not reliable and caused issues on Google's App Engine. Until472 1.0 the old behavior will continue to work but issue dependency473 warnings.474- fixed a problem for Flask to run on jython.314- added a `PROPAGATE_EXCEPTIONS` configuration variable that can be475- added a ``PROPAGATE_EXCEPTIONS`` configuration variable that can be476 used to flip the setting of exception propagation which previously316 was linked to `DEBUG` alone and is now linked to either `DEBUG` or317 `TESTING`.477 was linked to ``DEBUG`` alone and is now linked to either ``DEBUG`` or478 ``TESTING``.479- Flask no longer internally depends on rules being added through the480 `add_url_rule` function and can now also accept regular werkzeug481 rules added to the url map.482- Added an `endpoint` method to the flask application object which
28 unmodified lines
511-------------512513Bugfix release, released on December 31st 2010514354- Fixed an issue where the default `OPTIONS` response was355 not exposing all valid methods in the `Allow` header.515- Fixed an issue where the default ``OPTIONS`` response was516 not exposing all valid methods in the ``Allow`` header.517- Jinja2 template loading syntax now allows "./" in front of518 a template load path. Previously this caused issues with519 module setups.520- Fixed an issue where the subdomain setting for modules was
36 unmodified lines
557- modules can now register for a subdomain instead of just an URL558 prefix. This makes it possible to bind a whole module to a559 configurable subdomain.560400.. _blinker: http://pypi.python.org/pypi/blinker561.. _blinker: https://pypi.python.org/pypi/blinker562563Version 0.5.2564-------------565
16 unmodified lines
582Released on July 6th 2010, codename Calvados583584- fixed a bug with subdomains that was caused by the inability to585 specify the server name. The server name can now be set with425 the `SERVER_NAME` config key. This key is now also used to set586 the ``SERVER_NAME`` config key. This key is now also used to set587 the session cookie cross-subdomain wide.588- autoescaping is no longer active for all templates. Instead it589 is only active for ``.html``, ``.htm``, ``.xml`` and ``.xhtml``.590 Inside templates this behavior can be changed with the
23 unmodified lines
614 for a little longer. This can also be used to trigger custom615 requests that do not pop the request stack for testing.616- because the Python standard library caches loggers, the name of617 the logger is configurable now to better support unittests.457- added `TESTING` switch that can activate unittesting helpers.458- the logger switches to `DEBUG` mode now if debug is enabled.618- added ``TESTING`` switch that can activate unittesting helpers.619- the logger switches to ``DEBUG`` mode now if debug is enabled.620621Version 0.3.1622-------------623
48 unmodified lines
added:CONTRIBUTING.rst+114 added
1==========================2How to contribute to Flask3==========================45Thanks 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`Stack Overflow <https://stackoverflow.com/>`_ is also worth considering.1415Reporting issues16================1718- Under which versions of Python does this happen? This is even more important19 if your issue is encoding related.2021- Under which versions of Werkzeug does this happen? Check if this issue is22 fixed in the repository.2324Submitting patches25==================2627- 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 <https://www.python.org/dev/peps/pep-0008/>`_, but you32 may ignore the line-length-limit if following it would make the code uglier.333435Running the testsuite36---------------------3738You probably want to set up a `virtualenv39<https://virtualenv.readthedocs.io/en/latest/index.html>`_.4041The minimal requirement for running the testsuite is ``pytest``. You can42install it with::4344 pip install pytest4546Clone this repository::4748 git clone https://github.com/pallets/flask.git4950Install Flask as an editable package using the current source::5152 cd flask53 pip install --editable .5455Then you can run the testsuite with::5657 pytest tests/5859With only pytest installed, a large part of the testsuite will get skipped60though. Whether this is relevant depends on which part of Flask you're working61on. Travis is set up to run the full testsuite when you submit your pull62request anyways.6364If you really want to test everything, you will have to install ``tox`` instead65of ``pytest``. You can install it with::6667 pip install tox6869The ``tox`` command will then run all tests against multiple combinations70Python versions and dependency versions.7172Running test coverage73---------------------74Generating a report of lines that do not have unit test coverage can indicate where75to start contributing. ``pytest`` integrates with ``coverage.py``, using the ``pytest-cov``76plugin. This assumes you have already run the testsuite (see previous section)::7778 pip install pytest-cov7980After this has been installed, you can output a report to the command line using this command::8182 pytest --cov=flask tests/8384Generate a HTML report can be done using this command::8586 pytest --cov-report html --cov=flask tests/8788Full docs on ``coverage.py`` are here: https://coverage.readthedocs.io8990Caution91=======92pushing93-------94This repository contains several zero-padded file modes that may cause issues when pushing this repository to git hosts other than github. Fixing this is destructive to the commit history, so we suggest ignoring these warnings. If it fails to push and you're using a self-hosted git service like Gitlab, you can turn off repository checks in the admin panel.959697cloning98-------99The zero-padded file modes files above can cause issues while cloning, too. If you have100101::102103 [fetch]104 fsckobjects = true105106or107108::109110 [receive]111 fsckObjects = true112113114set in your git configuration file, cloning this repository will fail. The only solution is to set both of the above settings to false while cloning, and then setting them back to true after the cloning is finished.
modified:LICENSE+1 added-1 removed
1Copyright (c) 2014 by Armin Ronacher and contributors. See AUTHORS1Copyright (c) 2015 by Armin Ronacher and contributors. See AUTHORS2for more details.34Some rights reserved.5
28 unmodified lines
modified:Makefile+2 added-7 removed
1 unmodified line
23all: clean-pyc test45test:6 python run-tests.py6 pip install -r test-requirements.txt7 tox -e py-release88tox-test:9 tox1011test-with-mem:12 RUN_FLASK_MEMORY_TESTS=1 python run-tests.py139audit:10 python setup.py audit1112release:
29 unmodified lines
modified:MANIFEST.in+10 added-15 removed
1include Makefile CHANGES LICENSE AUTHORS run-tests.py2recursive-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 *.pyo12recursive-include flask/testsuite/static *13recursive-include flask/testsuite/templates *14recursive-include flask/testsuite/test_apps *1include Makefile CHANGES LICENSE AUTHORS23graft artwork4graft tests5graft examples6graft docs78global-exclude *.py[co]910prune docs/_build16prune docs/_themes/.git11prune docs/_themes
modified:README+7 added-17 removed
17 unmodified lines
18 improve over time but we don't plan on breaking it.1920 ~ What do I need?2122 Jinja 2.4 and Werkzeug 0.7 or later.23 `pip` or `easy_install` will install them for you if you do24 `pip install Flask`. I encourage you to use a virtualenv.25 Check the docs for complete installation and usage26 instructions.22 All dependencies are installed by using `pip install Flask`.23 We encourage you to use a virtualenv. Check the docs for24 complete installation and usage instructions.2526 ~ Where are the docs?2728 Go to http://flask.pocoo.org/docs/ for a prebuilt version
2 unmodified lines
3132 ~ Where are the tests?3334 Good that you're asking. The tests are in the37 flask/testsuite package. To run the tests use the38 `run-tests.py` file:35 tests/ folder. To run the tests use the36 `pytest` testing tool:3740 $ python run-tests.py38 $ pytest3942 If it's not enough output for you, you can use the43 `--verbose` flag:40 Details on contributing can be found in CONTRIBUTING.rst4145 $ python run-tests.py --verbose4647 If you just want one particular testcase to run you can48 provide it on the command line:4950 $ python run-tests.py test_to_run5142 ~ 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
deleted:run-tests.py-5 removed
1#!/usr/bin/env python2import sys, os3sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))4from flask.testsuite import main5main()
modified:setup.cfg+7 added-4 removed
1[egg_info]2tag_date = true31[aliases]2release = egg_info -RDb ''37[wheel]4[bdist_wheel]5universal = 167[metadata]8license_file = LICENSE910[tool:pytest]11norecursedirs = .* *.egg *.egg-info env* artwork docs
modified:setup.py+29 added-40 removed
6 unmodified lines
78Flask is Fun9````````````1011Save in a hello.py:1213.. code:: python1415 from flask import Flask16 app = Flask(__name__)
7 unmodified lines
2425And Easy to Setup26`````````````````2728And run it:2930.. code:: bash3132 $ 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 version38 <http://github.com/mitsuhiko/flask/zipball/master#egg=Flask-dev>`_44 <https://github.com/pallets/flask/zipball/master#egg=Flask-dev>`_4546"""41from __future__ import print_function42from setuptools import Command, setup47import re48import ast49from setuptools import setup5044class run_audit(Command):45 """Audits source code using PyFlakes for following issues:46 - Names which are used but not defined or used before they are defined.47 - Names which are redefined without having been used.48 """49 description = "Audit source code with PyFlakes"50 user_options = []5152 def initialize_options(self):53 pass52_version_re = re.compile(r'__version__\s+=\s+(.*)')5355 def finalize_options(self):56 pass54with open('flask/__init__.py', 'rb') as f:55 version = str(ast.literal_eval(_version_re.search(56 f.read().decode('utf-8')).group(1)))5758 def run(self):59 import os, sys60 try:61 import pyflakes.scripts.pyflakes as flakes62 except ImportError:63 print("Audit requires PyFlakes installed in your system.")64 sys.exit(-1)5866 warns = 067 # Define top-level directories68 dirs = ('flask', 'examples', 'scripts')69 for dir in dirs:70 for root, _, files in os.walk(dir):71 for file in files:72 if file != '__init__.py' and file.endswith('.py') :73 warns += flakes.checkPath(os.path.join(root, file))74 if warns > 0:75 print("Audit finished with total %d warnings." % warns)76 else:77 print("No problems found in sourcecode.")7859setup(60 name='Flask',81 version='0.11-dev',82 url='http://github.com/mitsuhiko/flask/',61 version=version,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 '67 'and good intentions',68 long_description=__doc__,89 packages=['flask', 'flask.ext', 'flask.testsuite'],69 packages=['flask', 'flask.ext'],70 include_package_data=True,71 zip_safe=False,72 platforms='any',73 install_requires=[74 'Werkzeug>=0.7',75 'Jinja2>=2.4',96 'itsdangerous>=0.21'76 'itsdangerous>=0.21',77 'click>=2.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 ],109 cmdclass={'audit': run_audit},110 test_suite='flask.testsuite.suite'96 entry_points='''97 [console_scripts]98 flask=flask.cli:main99 '''100)
added:test-requirements.txt+1 added
1tox
modified:tox.ini+30 added-3 removed
1[tox]2envlist = py26, py27, pypy, py332envlist = {py26,py27,pypy}-{lowest,release,devel}{,-simplejson}, {py33,py34,py35,py36}-{release,devel}{,-simplejson}3456[testenv]5deps = blinker6commands = python run-tests.py []7passenv = LANG8usedevelop=true9commands =10 # We need to install those after Flask is installed.11 pip install -e examples/flaskr12 pip install -e examples/minitwit13 pip install -e examples/patterns/largerapp14 pytest --cov=flask --cov-report html []15deps=16 pytest17 pytest-cov18 greenlet1920 lowest: Werkzeug==0.721 lowest: Jinja2==2.422 lowest: itsdangerous==0.2123 lowest: blinker==1.024 release: blinker25 devel: git+https://github.com/pallets/werkzeug.git26 devel: git+https://github.com/pallets/jinja.git27 devel: git+https://github.com/pallets/itsdangerous.git28 devel: git+https://github.com/jek/blinker.git29 simplejson: simplejson3031[testenv:docs]32deps = sphinx33commands = sphinx-build -W -b linkcheck -d {envtmpdir}/doctrees docs docs/_build/linkcheck