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
Provenance
- Commit
e2f4c0a- Tree
8e6c047- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
5935ee4- Parent 2
a558d47
288 files changed+12758 added−9447 removed
added:.github/ISSUE_TEMPLATE.rst+2 added
1+The issue tracker is a tool to address bugs.2+Please use the #pocoo IRC channel on freenode or Stack Overflow for questions.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/) -->3+4+<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
14 unmodified lines151617181920211920212214 unmodified lines</ul><h3>Useful Links</h3><ul> <li><a href="http://flask.pocoo.org/">The Flask Website</a></li> <li><a href="http://pypi.python.org/pypi/Flask">Flask @ PyPI</a></li> <li><a href="http://github.com/mitsuhiko/flask">Flask @ github</a></li> <li><a href="http://github.com/mitsuhiko/flask/issues">Issue Tracker</a></li> <li><a href="https://pypi.python.org/pypi/Flask">Flask @ PyPI</a></li> <li><a href="https://github.com/pallets/flask">Flask @ GitHub</a></li> <li><a href="https://github.com/pallets/flask/issues">Issue Tracker</a></li></ul>modified:docs/deploying/cgi.rst+6 added-6 removed
22 unmodified lines23 Creating a `.cgi` file24 ----------------------25 26 First you need to create the CGI application file. Let's call it27-`yourapplication.cgi`::27+:file:`yourapplication.cgi`::28 29 #!/usr/bin/python30 from wsgiref.handlers import CGIHandler31 from yourapplication import app3 unmodified lines35 Server Setup36 ------------37 38 Usually 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 to40 rewrite the URL) or let the server point to the file directly.41 42 In Apache for example you can put something like this into the config:43 1 unmodified line45 46 ScriptAlias /app /path/to/the/application.cgi47 48 On shared webhosting, though, you might not have access to your Apache config.49-In this case, a file called `.htaccess`, sitting in the public directory you want50-your app to be available, works too but the `ScriptAlias` directive won't49+In this case, a file called ``.htaccess``, sitting in the public directory you want50+your app to be available, works too but the ``ScriptAlias`` directive won't51 work in that case:52 53 .. sourcecode:: apache54- 54+55 RewriteEngine On56 RewriteCond %{REQUEST_FILENAME} !-f # Don't interfere with static files57 RewriteRule ^(.*)$ /path/to/the/application.cgi/$1 [L]58 59 For more information consult the documentation of your webserver.60 61-.. _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 lines39 40 The path has to be the exact same path you define in the server41 config.42 43-Save the `yourapplication.fcgi` file somewhere you will find it again.44-It makes sense to have that in `/var/www/yourapplication` or something43+Save the :file:`yourapplication.fcgi` file somewhere you will find it again.44+It makes sense to have that in :file:`/var/www/yourapplication` or something45 similar.46 47 Make sure to set the executable bit on that file so that the servers48 can execute it:6 unmodified lines55 ------------------56 57 The example above is good enough for a basic Apache deployment but your58 `.fcgi` file will appear in your application URL e.g.59-example.com/yourapplication.fcgi/news/. There are few ways to configure59+``example.com/yourapplication.fcgi/news/``. There are few ways to configure60 your application so that yourapplication.fcgi does not appear in the URL.61 A preferable way is to use the ScriptAlias and SetHandler configuration62 directives to route requests to the FastCGI server. The following example63 uses FastCgiServer to start 5 instances of the application which will14 unmodified lines78 SetHandler fastcgi-script79 </Location>80 </VirtualHost>81 82-These processes will be managed by Apache. If you're using an standalone82+These processes will be managed by Apache. If you're using a standalone83 FastCGI server, you can use the FastCgiExternalServer directive instead.84 Note that in the following the path is not real, it's simply used as an85 identifier to other86 directives such as AliasMatch::87 88 FastCgiServer /var/www/html/yourapplication -host 127.0.0.1:300089 90-If you cannot set ScriptAlias, for example on an shared web host, you can use90+If you cannot set ScriptAlias, for example on a shared web host, you can use91 WSGI middleware to remove yourapplication.fcgi from the URLs. Set .htaccess::92 93 <IfModule mod_fcgid.c>94 AddHandler fcgid-script .fcgi48 unmodified lines143 ))144 )145 146 alias.url = (147- "/static/" => "/path/to/your/static"147+ "/static/" => "/path/to/your/static/"148 )149 150 url.rewrite-once = (151 "^(/static($|/.*))$" => "$1",152 "^(/.*)$" => "/yourapplication.fcgi$1"153 )154 155 Remember to enable the FastCGI, alias and rewrite modules. This configuration156-binds the application to `/yourapplication`. If you want the application to156+binds the application to ``/yourapplication``. If you want the application to157 work in the URL root you have to work around a lighttpd bug with the158 :class:`~werkzeug.contrib.fixers.LighttpdCGIRootFix` middleware.159 160 Make sure to apply it only if you are mounting the application the URL161 root. Also, see the Lighty docs for more information on `FastCGI and Python162-<http://redmine.lighttpd.net/wiki/lighttpd/Docs:ModFastCGI>`_ (note that162+<https://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModFastCGI>`_ (note that163 explicitly passing a socket to run() is no longer necessary).164 165 Configuring nginx166 -----------------167 168 Installing FastCGI applications on nginx is a bit different because by169 default no FastCGI parameters are forwarded.170 171-A basic flask FastCGI configuration for nginx looks like this::171+A basic Flask FastCGI configuration for nginx looks like this::172 173 location = /yourapplication { rewrite ^ /yourapplication/ last; }174 location /yourapplication { try_files $uri @yourapplication; }175 location @yourapplication {3 unmodified lines179 fastcgi_param SCRIPT_NAME $fastcgi_script_name;180 fastcgi_pass unix:/tmp/yourapplication-fcgi.sock;181 }182 183-This configuration binds the application to `/yourapplication`. If you183+This configuration binds the application to ``/yourapplication``. If you184 want to have it in the URL root it's a bit simpler because you don't185-have to figure out how to calculate `PATH_INFO` and `SCRIPT_NAME`::185+have to figure out how to calculate ``PATH_INFO`` and ``SCRIPT_NAME``::186 187 location / { try_files $uri @yourapplication; }188 location @yourapplication {189 include fastcgi_params;4 unmodified lines194 195 Running FastCGI Processes196 -------------------------197 198-Since Nginx and others do not load FastCGI apps, you have to do it by198+Since nginx and others do not load FastCGI apps, you have to do it by199 yourself. `Supervisor can manage FastCGI processes.200 <http://supervisord.org/configuration.html#fcgi-program-x-section-settings>`_201 You can look around for other FastCGI process managers or write a script202 to run your `.fcgi` file at boot, e.g. using a SysV ``init.d`` script.6 unmodified lines209 210 Debugging211 ---------212 213-FastCGI deployments tend to be hard to debug on most webservers. Very213+FastCGI deployments tend to be hard to debug on most web servers. Very214 often the only thing the server log tells you is something along the215 lines of "premature end of headers". In order to debug the application216 the only thing that can really give you ideas why it breaks is switching217 to the correct user and executing the application by hand.218 219 This example assumes your application is called `application.fcgi` and220-that your webserver user is `www-data`::220+that your web server user is `www-data`::221 222 $ su www-data223 $ cd /var/www/yourapplication224 $ python application.fcgi3 unmodified lines228 229 In this case the error seems to be "yourapplication" not being on the230 python path. Common problems are:231 232-- 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.236 237-.. _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/flupmodified:docs/deploying/index.rst+23 added-10 removed
1 unmodified line2 3 Deployment Options4 ==================5 6-Depending on what you have available there are multiple ways to run7-Flask applications. You can use the builtin server during development,8-but you should use a full deployment option for production applications.9-(Do not use the builtin development server in production.) Several10-options are available and documented here.6+While lightweight and easy to use, **Flask's built-in server is not suitable7+for production** as it doesn't scale well and by default serves only one8+request at a time. Some of the options available for properly running Flask in9+production are documented here.10 12-If you have a different WSGI server look up the server documentation13-about how to use a WSGI app with it. Just remember that your14-:class:`Flask` application object is the actual WSGI application.11+If you want to deploy your Flask application to a WSGI server not listed here,12+look up the server documentation about how to use a WSGI app with it. Just13+remember that your :class:`Flask` application object is the actual WSGI14+application.15 16-For hosted options to get up and running quickly, see17-:ref:`quickstart_deployment` in the Quickstart.16 17+Hosted options18+--------------19+20+- `Deploying Flask on Heroku <https://devcenter.heroku.com/articles/getting-started-with-python>`_21+- `Deploying Flask on OpenShift <https://developers.openshift.com/en/python-flask.html>`_22+- `Deploying Flask on Webfaction <http://flask.pocoo.org/snippets/65/>`_23+- `Deploying Flask on Google App Engine <https://github.com/kamalgill/flask-appengine-template>`_24+- `Deploying Flask on AWS Elastic Beanstalk <https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-flask.html>`_25+- `Sharing your Localhost Server with Localtunnel <http://flask.pocoo.org/snippets/89/>`_26+- `Deploying on Azure (IIS) <https://azure.microsoft.com/documentation/articles/web-sites-python-configure/>`_27+- `Deploying on PythonAnywhere <https://help.pythonanywhere.com/pages/Flask/>`_28+29+Self-hosted options30+-------------------31+32 .. toctree::33 :maxdepth: 234 35 mod_wsgi4 unmodified linesmodified:docs/deploying/mod_wsgi.rst+47 added-16 removed
11 unmodified lines12 '__main__':`` block or moved to a separate file. Just make sure it's13 not called because this will always start a local WSGI server which14 we do not want if we deploy that application to mod_wsgi.15 16-.. _Apache: http://httpd.apache.org/16+.. _Apache: https://httpd.apache.org/17 18 Installing `mod_wsgi`19 ---------------------20 7 unmodified lines28 .. sourcecode:: text29 30 # apt-get install libapache2-mod-wsgi31 32+If you are using a yum based distribution (Fedora, OpenSUSE, etc..) you33+can install it as follows:34+35+.. sourcecode:: text36+37+ # yum install mod_wsgi38+39 On FreeBSD install `mod_wsgi` by compiling the `www/mod_wsgi` port or by40 using pkg_add:41 42 .. sourcecode:: text43 37- # pkg_add -r mod_wsgi44+ # pkg install ap22-mod_wsgi245 46 If you are using pkgsrc you can install `mod_wsgi` by compiling the47 `www/ap2-wsgi` package.48 2 unmodified lines51 52 Creating a `.wsgi` file53 -----------------------54 48-To run your application you need a `yourapplication.wsgi` file. This file55+To run your application you need a :file:`yourapplication.wsgi` file. This file56 contains the code `mod_wsgi` is executing on startup to get the application57 object. The object called `application` in that file is then used as58 application.59 4 unmodified lines64 If you don't have a factory function for application creation but a singleton65 instance you can directly import that one as `application`.66 67 Store 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 all69 the libraries that are in use are on the python load path. If you don't70 want to install it system wide consider using a `virtual python`_71 instance. Keep in mind that you will have to actually install your72 application into the virtualenv as well. Alternatively there is the66-option to just patch the path in the `.wsgi` file before the import::73+option to just patch the path in the ``.wsgi`` file before the import::74 75 import sys76 sys.path.insert(0, '/path/to/the/application')77 19 unmodified lines97 Allow from all98 </Directory>99 </VirtualHost>100 94-Note: WSGIDaemonProcess isn't implemented in Windows and Apache will 101+Note: WSGIDaemonProcess isn't implemented in Windows and Apache will102 refuse to run with the above configuration. On a Windows system, eliminate those lines:103 104 .. sourcecode:: apache105 5 unmodified lines111 Allow from all112 </Directory>113 </VirtualHost>114 108-For more information consult the `mod_wsgi wiki`_.115+Note: There have been some changes in access control configuration for `Apache 2.4`_.116 110-.. _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.html118 119+Most notably, the syntax for directory permissions has changed from httpd 2.2120+121+.. sourcecode:: apache122+123+ Order allow,deny124+ Allow from all125+126+to httpd 2.4 syntax127+128+.. sourcecode:: apache129+130+ Require all granted131+132+133+For more information consult the `mod_wsgi documentation`_.134+135+.. _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.html139+140 Troubleshooting141 ---------------142 143 If your application does not run, follow this guide to troubleshoot:144 145 **Problem:** application does not run, errorlog shows SystemExit 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.150 151 **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 proper30 unmodified lines184 Support for Automatic Reloading185 -------------------------------186 187 To help deployment tools you can activate support for automatic163-reloading. Whenever something changes the `.wsgi` file, `mod_wsgi` will188+reloading. Whenever something changes the ``.wsgi`` file, `mod_wsgi` will189 reload all the daemon processes for us.190 191 For that, just add the following directive to your `Directory` section:192 6 unmodified lines199 200 Virtual environments have the advantage that they never install the201 required dependencies system wide so you have a better control over what202 is used where. If you want to use a virtual environment with mod_wsgi178-you have to modify your `.wsgi` file slightly.203+you have to modify your ``.wsgi`` file slightly.204 180-Add the following lines to the top of your `.wsgi` file::205+Add the following lines to the top of your ``.wsgi`` file::206 207 activate_this = '/path/to/env/bin/activate_this.py'208 execfile(activate_this, dict(__file__=activate_this))209 210+For Python 3 add the following lines to the top of your ``.wsgi`` file::211+212+ activate_this = '/path/to/env/bin/activate_this.py'213+ with open(activate_this) as file_:214+ exec(file_.read(), dict(__file__=activate_this))215+216 This sets up the load paths according to the settings of the virtual217 environment. Keep in mind that the path has to be absolute.modified:docs/deploying/uwsgi.rst+21 added-16 removed
27 unmodified lines28 Given a flask application in myapp.py, use the following command:29 30 .. sourcecode:: text31 32- $ uwsgi -s /tmp/uwsgi.sock --module myapp --callable app32+ $ uwsgi -s /tmp/yourapplication.sock --manage-script-name --mount /yourapplication=myapp:app33 34-Or, if you prefer:34+The ``--manage-script-name`` will move the handling of ``SCRIPT_NAME`` to uwsgi,35+since its smarter about that. It is used together with the ``--mount`` directive36+which will make requests to ``/yourapplication`` be directed to ``myapp:app``.37+If your application is accessible at root level, you can use a single ``/``38+instead of ``/yourapplication``. ``myapp`` refers to the name of the file of39+your flask application (without extension) or the module which provides ``app``.40+``app`` is the callable inside of your application (usually the line reads41+``app = Flask(__name__)``.42 36-.. sourcecode:: text43+If you want to deploy your flask application inside of a virtual environment,44+you need to also add ``--virtualenv /path/to/virtual/environment``. You might45+also need to add ``--plugin python`` or ``--plugin python3`` depending on which46+python version you use for your project.47 38- $ uwsgi -s /tmp/uwsgi.sock -w myapp:app39-48 Configuring nginx49 -----------------50 43-A basic flask uWSGI configuration for nginx looks like this::51+A basic flask nginx configuration looks like this::52 53 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 }59 54-This configuration binds the application to `/yourapplication`. If you want55-to have it in the URL root it's a bit simpler because you don't have to tell56-it the WSGI `SCRIPT_NAME` or set the uwsgi modifier to make use of it::60+This configuration binds the application to ``/yourapplication``. If you want61+to have it in the URL root its a bit simpler::62 63 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 }68 64-.. _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 lines24 gunicorn -w 4 -b 127.0.0.1:4000 myproject:app25 26 .. _Gunicorn: http://gunicorn.org/27 .. _eventlet: http://eventlet.net/28-.. _greenlet: http://greenlet.readthedocs.org/en/latest/28+.. _greenlet: https://greenlet.readthedocs.io/en/latest/29 30-Tornado31---------32-33-`Tornado`_ is an open source version of the scalable, non-blocking web34-server and tools that power `FriendFeed`_. Because it is non-blocking and35-uses epoll, it can handle thousands of simultaneous standing connections,36-which means it is ideal for real-time web services. Integrating this37-service with Flask is straightforward::38-39- from tornado.wsgi import WSGIContainer40- from tornado.httpserver import HTTPServer41- from tornado.ioloop import IOLoop42- from yourapplication import app43-44- http_server = HTTPServer(WSGIContainer(app))45- http_server.listen(5000)46- IOLoop.instance().start()47-48-49-.. _Tornado: http://www.tornadoweb.org/50-.. _FriendFeed: http://friendfeed.com/51-30 Gevent31 -------32 33 `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`_35 event loop::36 37 from gevent.wsgi import WSGIServer38 from yourapplication import app1 unmodified line40 http_server = WSGIServer(('', 5000), app)41 http_server.serve_forever()42 43 .. _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.html46 47 Twisted Web48 -----------49 23 unmodified lines73 ------------74 75 If you deploy your application using one of these servers behind an HTTP proxy76 you will need to rewrite a few headers in order for the application to work.99-The two problematic values in the WSGI environment usually are `REMOTE_ADDR`100-and `HTTP_HOST`. You can configure your httpd to pass these headers, or you77+The two problematic values in the WSGI environment usually are ``REMOTE_ADDR``78+and ``HTTP_HOST``. You can configure your httpd to pass these headers, or you79 can fix them in middleware. Werkzeug ships a fixer that will solve some common80 setups, but you might want to write your own WSGI middleware for specific81 setups.82 13 unmodified lines96 location / {97 proxy_pass http://127.0.0.1:8000/;98 proxy_redirect off;99 122- 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 }106 107 If your httpd is not providing these headers, the most common setup invokes the129-host being set from `X-Forwarded-Host` and the remote address from130-`X-Forwarded-For`::108+host being set from ``X-Forwarded-Host`` and the remote address from109+``X-Forwarded-For``::110 111 from werkzeug.contrib.fixers import ProxyFix112 app.wsgi_app = ProxyFix(app.wsgi_app)113 21 unmodified linesmodified:docs/patterns/apierrors.rst+2 added-2 removed
1 Implementing API Exceptions2 ===========================3 4 It's very common to implement RESTful APIs on top of Flask. One of the5-first thing that developers run into is the realization that the builtin5+first things that developers run into is the realization that the builtin6 exceptions are not expressive enough for APIs and that the content type of7-``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.8 9 The better solution than using ``abort`` to signal errors for invalid API10 usage is to implement your own exception type and install an error handler11 for it that produces the errors in the format the user is expecting.52 unmodified linesmodified:docs/patterns/appdispatch.rst+12 added-12 removed
2 unmodified lines3 Application Dispatching4 =======================5 6 Application dispatching is the process of combining multiple Flask7-applications on the WSGI level. You can not only combine Flask8-applications into something larger but any WSGI application. This would9-even allow you to run a Django and a Flask application in the same10-interpreter side by side if you want. The usefulness of this depends on11-how the applications work internally.7+applications on the WSGI level. You can combine not only Flask8+applications but any WSGI application. This would allow you to run a9+Django and a Flask application in the same interpreter side by side if10+you want. The usefulness of this depends on how the applications work11+internally.12 13 The fundamental difference from the :ref:`module approach14 <larger-applications>` is that in this case you are running the same or15 different Flask applications that are entirely isolated from each other.13 unmodified lines29 30 Note that :func:`run_simple <werkzeug.serving.run_simple>` is not intended for31 use in production. Use a :ref:`full-blown WSGI server <deployment>`.32 33-In order to use the interactive debuggger, debugging must be enabled both on34-the application and the simple server, here is the "hello world" example with33+In order to use the interactive debugger, debugging must be enabled both on34+the application and the simple server. Here is the "hello world" example with35 debugging and :func:`run_simple <werkzeug.serving.run_simple>`::36 37 from flask import Flask38 from werkzeug.serving import run_simple16 unmodified lines55 If you have entirely separated applications and you want them to work next56 to each other in the same Python interpreter process you can take57 advantage of the :class:`werkzeug.wsgi.DispatcherMiddleware`. The idea58 here is that each Flask application is a valid WSGI application and they59-are combined by the dispatcher middleware into a larger one that59+are combined by the dispatcher middleware into a larger one that is60 dispatched based on prefix.61 62-For example you could have your main application run on `/` and your63-backend interface on `/backend`::62+For example you could have your main application run on ``/`` and your63+backend interface on ``/backend``::64 65 from werkzeug.wsgi import DispatcherMiddleware66 from frontend_app import application as frontend67 from backend_app import application as backend75 unmodified lines143 Dispatch by Path144 ----------------145 146 Dispatching by a path on the URL is very similar. Instead of looking at147-the `Host` header to figure out the subdomain one simply looks at the147+the ``Host`` header to figure out the subdomain one simply looks at the148 request path up to the first slash::149 150 from threading import Lock151 from werkzeug.wsgi import pop_path_info, peek_path_info23 unmodified lines175 app = self.default_app176 return app(environ, start_response)177 178 The big difference between this and the subdomain one is that this one179-falls back to another application if the creator function returns `None`::179+falls back to another application if the creator function returns ``None``::180 181 from myapplication import create_app, default_app, get_user_for_prefix182 183 def make_app(prefix):5 unmodified linesmodified:docs/patterns/appfactories.rst+14 added-8 removed
4 unmodified lines5 6 If you are already using packages and blueprints for your application7 (:ref:`blueprints`) there are a couple of really nice ways to further improve8 the experience. A common pattern is creating the application object when9-the blueprint is imported. But if you move the creation of this object,10-into a function, you can then create multiple instances of this and later.9+the blueprint is imported. But if you move the creation of this object10+into a function, you can then create multiple instances of this app later.11 12 So why would you want to do this?13 14 1. Testing. You can have instances of the application with different44 unmodified lines59 60 It's preferable to create your extensions and app factories so that the61 extension object does not initially get bound to the application.62 63-Using `Flask-SQLAlchemy <http://pythonhosted.org/Flask-SQLAlchemy/>`_, 63+Using `Flask-SQLAlchemy <http://flask-sqlalchemy.pocoo.org/>`_,64 as an example, you should not do something along those lines::65- 65+66 def create_app(config_filename):67 app = Flask(__name__)68 app.config.from_pyfile(config_filename)69 1 unmodified line71 72 But, rather, in model.py (or equivalent)::73 74 db = SQLAlchemy()75- 75+76 and in your application.py (or equivalent)::77 78 def create_app(config_filename):79 app = Flask(__name__)2 unmodified lines82 from yourapplication.model import db83 db.init_app(app)84 85 Using this design pattern, no application-specific state is stored on the86-extension object, so one extension object can be used for multiple apps. 86+extension object, so one extension object can be used for multiple apps.87 For more information about the design of extensions refer to :doc:`/extensiondev`.88 89 Using Applications90 ------------------91 92 So to use such an application you then have to create the application93-first. Here an example `run.py` file that runs such an application::93+first in a separate file otherwise the :command:`flask` command won't be able94+to find it. Here an example :file:`exampleapp.py` file that creates such95+an application::96 97 from yourapplication import create_app98 app = create_app('/path/to/config.cfg')97- app.run()99 100+It can then be used with the :command:`flask` command::101+102+ export FLASK_APP=exampleapp103+ flask run104+105 Factory Improvements106 --------------------107 108 The factory function from above is not very clever so far, you can improve8 unmodified linesmodified:docs/patterns/caching.rst+3 added-3 removed
25 unmodified lines26 from werkzeug.contrib.cache import SimpleCache27 cache = SimpleCache()28 29 If you want to use memcached, make sure to have one of the memcache modules30-supported (you get them from `PyPI <http://pypi.python.org/>`_) and a30+supported (you get them from `PyPI <https://pypi.python.org/pypi>`_) and a31 memcached server running somewhere. This is how you connect to such an32 memcached server then::33 34 from werkzeug.contrib.cache import MemcachedCache8 unmodified lines43 Using a Cache44 -------------45 46 Now how can one use such a cache? There are two very important47-operations: :meth:`~werkzeug.contrib.cache.BaseCache.get` and 47+operations: :meth:`~werkzeug.contrib.cache.BaseCache.get` and48 :meth:`~werkzeug.contrib.cache.BaseCache.set`. This is how to use them:49 50 To get an item from the cache call51 :meth:`~werkzeug.contrib.cache.BaseCache.get` with a string as key name.52 If something is in the cache, it is returned. Otherwise that function53-will return `None`::53+will return ``None``::54 55 rv = cache.get('my-item')56 57 To add items to the cache, use the :meth:`~werkzeug.contrib.cache.BaseCache.set`12 unmodified linesmodified:docs/patterns/celery.rst+44 added-35 removed
1-Celery Based Background Tasks2-=============================1+Celery Background Tasks2+=======================3 4-Celery is a task queue for Python with batteries included. It used to5-have a Flask integration but it became unnecessary after some6-restructuring of the internals of Celery with Version 3. This guide fills7-in the blanks in how to properly use Celery with Flask but assumes that8-you generally already read the `First Steps with Celery9-<http://docs.celeryproject.org/en/master/getting-started/first-steps-with-celery.html>`_10-guide in the official Celery documentation.4+If your application has a long running task, such as processing some uploaded5+data or sending email, you don't want to wait for it to finish during a6+request. Instead, use a task queue to send the necessary data to another7+process that will run the task in the background while the request returns8+immediately.9 12-Installing Celery13------------------10+Celery is a powerful task queue that can be used for simple background tasks11+as well as complex multi-stage programs and schedules. This guide will show you12+how to configure Celery using Flask, but assumes you've already read the13+`First Steps with Celery <http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html>`_14+guide in the Celery documentation.15 15-Celery is on the Python Package Index (PyPI), so it can be installed with16-standard Python tools like ``pip`` or ``easy_install``::16+Install17+-------18 19+Celery is a separate Python package. Install it from PyPI using pip::20+21 $ pip install celery22 20-Configuring Celery21-------------------23+Configure24+---------25 26 The first thing you need is a Celery instance, this is called the celery27 application. It serves the same purpose as the :class:`~flask.Flask`28 object in Flask, just for Celery. Since this instance is used as the9 unmodified lines38 39 from celery import Celery40 41 def make_celery(app):39- celery = Celery(app.import_name, 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 = True48+49+ 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)53+54 celery.Task = ContextTask55 return celery56 57 The function creates a new Celery object, configures it with the broker58 from the application config, updates the rest of the Celery config from59 the Flask config and then creates a subclass of the task that wraps the60 task execution in an application context.61 55-Minimal Example62+An example task63 ---------------64 58-With what we have above this is the minimal example of using Celery with59-Flask::65+Let's write a task that adds two numbers together and returns the result. We66+configure Celery's broker and backend to use Redis, create a ``celery``67+application using the factor from above, and then use it to define the task. ::68 69 from flask import Flask70 71 flask_app = Flask(__name__)2 unmodified lines74 CELERY_RESULT_BACKEND='redis://localhost:6379'75 )76 celery = make_celery(flask_app)77 70-78 @celery.task()79 def add_together(a, b):80 return a + b81 75-This task can now be called in the background:82+This task can now be called in the background::83 77->>> result = add_together.delay(23, 42)78->>> result.wait()79-6584+ result = add_together.delay(23, 42)85+ result.wait() # 6586 81-Running the Celery Worker82--------------------------87+Run a worker88+------------89 84-Now if you jumped in and already executed the above code you will be85-disappointed to learn that your ``.wait()`` will never actually return.86-That's because you also need to run celery. You can do that by running87-celery as a worker::90+If you jumped in and already executed the above code you will be91+disappointed to learn that ``.wait()`` will never actually return.92+That's because you also need to run a Celery worker to receive and execute the93+task. ::94 95 $ celery -A your_application.celery worker96 97 The ``your_application`` string has to point to your application's package92-or module that creates the `celery` object.98+or module that creates the ``celery`` object.99+100+Now that the worker is running, ``wait`` will return the result once the task101+is finished.modified:docs/patterns/deferredcallbacks.rst+25 added-53 removed
1 unmodified line2 3 Deferred Request Callbacks4 ==========================5 6-One of the design principles of Flask is that response objects are created7-and passed down a chain of potential callbacks that can modify them or8-replace them. When the request handling starts, there is no response9-object yet. It is created as necessary either by a view function or by10-some other component in the system.6+One of the design principles of Flask is that response objects are created and7+passed down a chain of potential callbacks that can modify them or replace8+them. When the request handling starts, there is no response object yet. It is9+created as necessary either by a view function or by some other component in10+the system.11 12-But what happens if you want to modify the response at a point where the13-response does not exist yet? A common example for that would be a14-before-request function that wants to set a cookie on the response object.12+What happens if you want to modify the response at a point where the response13+does not exist yet? A common example for that would be a14+:meth:`~flask.Flask.before_request` callback that wants to set a cookie on the15+response object.16 16-One way is to avoid the situation. Very often that is possible. For17-instance you can try to move that logic into an after-request callback18-instead. Sometimes however moving that code there is just not a very19-pleasant experience or makes code look very awkward.17+One way is to avoid the situation. Very often that is possible. For instance18+you can try to move that logic into a :meth:`~flask.Flask.after_request`19+callback instead. However, sometimes moving code there makes it more20+more complicated or awkward to reason about.21 21-As an alternative possibility you can attach a bunch of callback functions22-to the :data:`~flask.g` object and call them at the end of the request.23-This way you can defer code execution from anywhere in the application.22+As an alternative, you can use :func:`~flask.after_this_request` to register23+callbacks that will execute after only the current request. This way you can24+defer code execution from anywhere in the application, based on the current25+request.26 27+At any time during a request, we can register a function to be called at the28+end of the request. For example you can remember the current language of the29+user in a cookie in a :meth:`~flask.Flask.before_request` callback::30 26-The Decorator27--------------31+ from flask import request, after_this_request32 29-The following decorator is the key. It registers a function on a list on30-the :data:`~flask.g` object::31-32- from flask import g33-34- def after_this_request(f):35- if not hasattr(g, 'after_request_callbacks'):36- g.after_request_callbacks = []37- g.after_request_callbacks.append(f)38- return f39-40-41-Calling the Deferred42---------------------43-44-Now you can use the `after_this_request` decorator to mark a function to45-be called at the end of the request. But we still need to call them. For46-this the following function needs to be registered as47-:meth:`~flask.Flask.after_request` callback::48-49- @app.after_request50- def call_after_request_callbacks(response):51- for callback in getattr(g, 'after_request_callbacks', ()):52- callback(response)53- return response54-55-56-A Practical Example57--------------------58-59-Now we can easily at any point in time register a function to be called at60-the end of this particular request. For example you can remember the61-current language of the user in a cookie in the before-request function::62-63- from flask import request64-33 @app.before_request34 def detect_user_language():35 language = request.cookies.get('user_lang')36+37 if language is None:38 language = guess_language_from_request()39+40+ # when the response exists, set a cookie with the language41 @after_this_request42 def remember_language(response):43 response.set_cookie('user_lang', language)44+45 g.language = languagemodified:docs/patterns/distribute.rst+64 added-53 removed
1 .. _distribute-deployment:2 3-Deploying with Distribute3+Deploying with Setuptools4 =========================5 6-`distribute`_, formerly setuptools, is an extension library that is7-commonly used to (like the name says) distribute Python libraries and8-extensions. It extends distutils, a basic module installation system9-shipped with Python to also support various more complex constructs that10-make larger applications easier to distribute:6+`Setuptools`_, is an extension library that is commonly used to7+distribute Python libraries and extensions. It extends distutils, a basic8+module installation system shipped with Python to also support various more9+complex constructs that make larger applications easier to distribute:10 11 - **support for dependencies**: a library or application can declare a12 list of other libraries it depends on which will be installed13 automatically for you.14 - **package registry**: setuptools registers your package with your15 Python installation. This makes it possible to query information16 provided by one package from another package. The best known feature of17 this system is the entry point support which allows one package to19- declare an "entry point" another package can hook into to extend the18+ declare an "entry point" that another package can hook into to extend the19 other package.21-- **installation manager**: `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.21 26-Flask itself, and all the libraries you can find on the cheeseshop27-are distributed with either distribute, the older setuptools or distutils.22+If you have Python 2 (>=2.7.9) or Python 3 (>=3.4) installed from python.org,23+you will already have pip and setuptools on your system. Otherwise, you24+will need to install them yourself.25 26+Flask itself, and all the libraries you can find on PyPI are distributed with27+either setuptools or distutils.28+29 In this case we assume your application is called30-`yourapplication.py` and you are not using a module, but a :ref:`package31-<larger-applications>`. Distributing resources with standard modules is32-not supported by `distribute`_ so we will not bother with it. If you have33-not yet converted your application into a package, head over to the34-:ref:`larger-applications` pattern to see how this can be done.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 into32+a package, head over to the :ref:`larger-applications` pattern to see33+how this can be done.34 36-A working deployment with distribute is the first step into more complex35+A working deployment with setuptools is the first step into more complex36 and more automated deployment scenarios. If you want to fully automate37 the process, also read the :ref:`fabric-deployment` chapter.38 39 Basic Setup Script40 ------------------41 43-Because you have Flask running, you either have setuptools or distribute44-available on your system anyways. If you do not, fear not, there is a45-script to install it for you: `distribute_setup.py`_. Just download and46-run with your Python interpreter.42+Because you have Flask installed, you have setuptools available on your system.43+Flask already depends upon setuptools.44 45 Standard disclaimer applies: :ref:`you better use a virtualenv46 <virtualenv>`.47 51-Your setup code always goes into a file named `setup.py` next to your48+Your setup code always goes into a file named :file:`setup.py` next to your49 application. The name of the file is only convention, but because50 everybody will look for a file with that name, you better not change it.51 55-Yes, even if you are using `distribute`, you are importing from a package56-called `setuptools`. `distribute` is fully backwards compatible with57-`setuptools`, so it also uses the same import name.52+A basic :file:`setup.py` file for a Flask application looks like this::53 59-A basic `setup.py` file for a Flask application looks like this::60-54 from setuptools import setup55 56 setup(57 name='Your Application',5 unmodified lines63 install_requires=['Flask']64 )65 66 Please keep in mind that you have to list subpackages explicitly. If you74-want distribute to lookup the packages for you automatically, you can use75-the `find_packages` function::67+want setuptools to lookup the packages for you automatically, you can use68+the ``find_packages`` function::69 70 from setuptools import setup, find_packages71 72 setup(73 ...74 packages=find_packages()75 )76 84-Most parameters to the `setup` function should be self explanatory,85-`include_package_data` and `zip_safe` might not be.86-`include_package_data` tells distribute to look for a `MANIFEST.in` file77+Most parameters to the ``setup`` function should be self explanatory,78+``include_package_data`` and ``zip_safe`` might not be.79+``include_package_data`` tells setuptools to look for a :file:`MANIFEST.in` file80 and install all the entries that match as package data. We will use this81 to distribute the static files and templates along with the Python module89-(see :ref:`distributing-resources`). The `zip_safe` flag can be used to82+(see :ref:`distributing-resources`). The ``zip_safe`` flag can be used to83 force or prevent zip Archive creation. In general you probably don't want84 your packages to be installed as zip files because some tools do not85 support them and they make debugging a lot harder.86 87 88+Tagging Builds89+--------------90+91+It is useful to distinguish between release and development builds. Add a92+:file:`setup.cfg` file to configure these options.93+94+ [egg_info]95+ tag_build = .dev96+ tag_date = 197+98+ [aliases]99+ release = egg_info -RDb ''100+101+Running ``python setup.py sdist`` will create a development package102+with ".dev" and the current date appended: ``flaskr-1.0.dev20160314.tar.gz``.103+Running ``python setup.py release sdist`` will create a release package104+with only the version: ``flaskr-1.0.tar.gz``.105+106+107 .. _distributing-resources:108 109 Distributing Resources110 ----------------------111 112 If you try to install the package you just created, you will notice that101-folders like `static` or `templates` are not installed for you. The102-reason for this is that distribute does not know which files to add for103-you. 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 to113+folders like :file:`static` or :file:`templates` are not installed for you. The114+reason for this is that setuptools does not know which files to add for115+you. What you should do, is to create a :file:`MANIFEST.in` file next to your116+:file:`setup.py` file. This file lists all the files that should be added to117 your tarball::118 119 recursive-include yourapplication/templates *120 recursive-include yourapplication/static *121 110-Don't forget that even if you enlist them in your `MANIFEST.in` file, they122+Don't forget that even if you enlist them in your :file:`MANIFEST.in` file, they123 won't be installed for you unless you set the `include_package_data`112-parameter of the `setup` function to `True`!124+parameter of the ``setup`` function to ``True``!125 126 127 Declaring Dependencies128 ----------------------129 118-Dependencies are declared in the `install_requires` parameter as list.130+Dependencies are declared in the ``install_requires`` parameter as a list.131 Each item in that list is the name of a package that should be pulled from132 PyPI on installation. By default it will always use the most recent133 version, but you can also provide minimum and maximum version134 requirements. Here some examples::3 unmodified lines138 'SQLAlchemy>=0.6',139 'BrokenPackage>=0.7,<=1.0'140 ]141 130-I mentioned earlier that dependencies are pulled from PyPI. What if you142+As mentioned earlier, dependencies are pulled from PyPI. What if you143 want to depend on a package that cannot be found on PyPI and won't be144 because it is an internal package you don't want to share with anyone?133-Just still do as if there was a PyPI entry for it and provide a list of134-alternative locations where distribute should look for tarballs::145+Just do it as if there was a PyPI entry and provide a list of146+alternative locations where setuptools should look for tarballs::147 148 dependency_links=['http://example.com/yourfiles']149 150 Make sure that page has a directory listing and the links on the page are151 pointing to the actual tarballs with their correct filenames as this is140-how distribute will find the files. If you have an internal company141-server that contains the packages, provide the URL to that server there.152+how setuptools will find the files. If you have an internal company153+server that contains the packages, provide the URL to that server.154 155 156 Installing / Developing157 -----------------------158 159 To install your application (ideally into a virtualenv) just run the148-`setup.py` script with the `install` parameter. It will install your160+:file:`setup.py` script with the ``install`` parameter. It will install your161 application into the virtualenv's site-packages folder and also download162 and install all dependencies::163 164 $ python setup.py install165 166 If you are developing on the package and also want the requirements to be155-installed, you can use the `develop` command instead::167+installed, you can use the ``develop`` command instead::168 169 $ python setup.py develop170 171 This has the advantage of just installing a link to the site-packages172 folder instead of copying the data over. You can then continue to work on161-the code without having to run `install` again after each change.173+the code without having to run ``install`` again after each change.174 175 164-.. _distribute: 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/setuptoolsmodified:docs/patterns/errorpages.rst+39 added-17 removed
1+.. _errorpages:2+3 Custom Error Pages4 ==================5 6 Flask comes with a handy :func:`~flask.abort` function that aborts a31 unmodified lines38 looking for was deleted for all eternity.39 40 *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`).45 46 47 Error Handlers48 --------------49 48-An error handler is a function, just like a view function, but it is49-called when an error happens and is passed that error. The error is most50-likely a :exc:`~werkzeug.exceptions.HTTPException`, but in one case it51-can be a different error: a handler for internal server errors will be52-passed other exception instances as well if they are uncaught.50+An error handler is a function that returns a response when a type of error is51+raised, similar to how a view is a function that returns a response when a52+request URL is matched. It is passed the instance of the error being handled,53+which is most likely a :exc:`~werkzeug.exceptions.HTTPException`. An error54+handler for "500 Internal Server Error" will be passed uncaught exceptions in55+addition to explicit 500 errors.56 57 An error handler is registered with the :meth:`~flask.Flask.errorhandler`55-decorator and the error code of the exception. Keep in mind that Flask56-will *not* set the error code for you, so make sure to also provide the57-HTTP status code when returning a response.58+decorator or the :meth:`~flask.Flask.register_error_handler` method. A handler59+can be registered for a status code, like 404, or for an exception class.60 59-Here an example implementation for a "404 Page Not Found" exception::61+The status code of the response will not be set to the handler's code. Make62+sure to provide the appropriate HTTP status code when returning a response from63+a handler.64 65+A handler for "500 Internal Server Error" will not be used when running in66+debug mode. Instead, the interactive debugger will be shown.67+68+Here is an example implementation for a "404 Page Not Found" exception::69+70 from flask import render_template71 72 @app.errorhandler(404)73 def page_not_found(e):74+ # note that we set the 404 status explicitly75 return render_template('404.html'), 40476 77+When using the :ref:`application factory pattern <app-factories>`::78+79+ from flask import Flask, render_template80+81+ def page_not_found(e):82+ return render_template('404.html'), 40483+84+ def create_app(config_filename):85+ app = Flask(__name__)86+ app.register_error_handler(404, page_not_found)87+ return app88+89 An example template might be this:90 91 .. sourcecode:: html+jinja92 71- {% 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 lines14 15 - 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 root1 unmodified line24 25 Creating the first Fabfile26 --------------------------27 28-A fabfile is what controls what Fabric executes. It is named `fabfile.py`28+A fabfile is what controls what Fabric executes. It is named :file:`fabfile.py`29 and executed by the `fab` command. All the functions defined in that file30 will show up as `fab` subcommands. They are executed on one or more31 hosts. These hosts can be defined either in the fabfile or on the command32 line. In this case we will add them to the fabfile.33 34 This is a basic first example that has the ability to upload the current35-sourcecode to the server and install it into a pre-existing35+source code to the server and install it into a pre-existing36 virtual environment::37 38 from fabric.api import *39 2 unmodified lines42 # the servers where the commands are executed43 env.hosts = ['server1.example.com', 'server2.example.com']44 45 def pack():46- # create a new source distribution as tarball46+ # build the package47 local('python setup.py sdist --formats=gztar', capture=False)48 49 def deploy():50- # figure out the release name and version50+ # figure out the package name and version51 dist = local('python setup.py --fullname', capture=True).strip()52- # upload the source tarball to the temporary folder on the server53- put('dist/%s.tar.gz' % dist, '/tmp/yourapplication.tar.gz')54- # create a place where we can unzip the tarball, then enter55- # that directory and unzip it56- run('mkdir /tmp/yourapplication')57- with cd('/tmp/yourapplication'):58- run('tar xzf /tmp/yourapplication.tar.gz')59- # now setup the package with our virtual environment's60- # python interpreter61- run('/var/www/yourapplication/env/bin/python setup.py install')62- # now that all is set up, delete the folder again63- run('rm -rf /tmp/yourapplication /tmp/yourapplication.tar.gz')64- # and finally touch the .wsgi file so that mod_wsgi triggers65- # a reload of the application66- run('touch /var/www/yourapplication.wsgi')52+ filename = '%s.tar.gz' % dist53 68-The example above is well documented and should be straightforward. Here69-a recap of the most common commands fabric provides:54+ # upload the package to the temporary folder on the server55+ put('dist/%s' % filename, '/tmp/%s' % filename)56 71-- `run` - executes a command on a remote server72-- `local` - executes a command on the local machine73-- `put` - uploads a file to the remote server74-- `cd` - changes the directory on the serverside. This has to be used75- in combination with the `with` statement.57+ # install the package in the application's virtualenv with pip58+ run('/var/www/yourapplication/env/bin/pip install /tmp/%s' % filename)59 60+ # remove the uploaded package61+ run('rm -r /tmp/%s' % filename)62+63+ # touch the .wsgi file to trigger a reload in mod_wsgi64+ run('touch /var/www/yourapplication.wsgi')65+66 Running Fabfiles67 ----------------68 69 Now how do you execute that fabfile? You use the `fab` command. To2 unmodified lines72 73 $ fab pack deploy74 75 However this requires that our server already has the87-``/var/www/yourapplication`` folder created and88-``/var/www/yourapplication/env`` to be a virtual environment. Furthermore89-are 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. Furthermore78+are we not creating the configuration or ``.wsgi`` file on the server. So79 how do we bootstrap a new server into our infrastructure?80 81 This now depends on the number of servers we want to set up. If we just82 have one application server (which the majority of applications will5 unmodified lines88 $ fab -H newserver.example.com bootstrap89 90 To setup a new server you would roughly do these steps:91 103-1. Create the directory structure in ``/var/www``::92+1. Create the directory structure in :file:`/var/www`::93 94 $ mkdir /var/www/yourapplication95 $ cd /var/www/yourapplication96 $ virtualenv --distribute env97 109-2. Upload a new `application.wsgi` file to the server and the110- configuration file for the application (eg: `application.cfg`)98+2. Upload a new :file:`application.wsgi` file to the server and the99+ configuration file for the application (eg: :file:`application.cfg`)100 112-3. Create a new Apache config for `yourapplication` and activate it.113- Make sure to activate watching for changes of the `.wsgi` file so101+3. 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)105 117-So now the question is, where do the `application.wsgi` and118-`application.cfg` files come from?106+So now the question is, where do the :file:`application.wsgi` and107+:file:`application.cfg` files come from?108 109 The WSGI File110 -------------111 18 unmodified lines130 The Configuration File131 ----------------------132 133 Now as mentioned above, the application will find the correct145-configuration file by looking up the `YOURAPPLICATION_CONFIG` environment134+configuration file by looking up the ``YOURAPPLICATION_CONFIG`` environment135 variable. So we have to put the configuration in a place where the136 application will able to find it. Configuration files have the unfriendly137 quality of being different on all computers, so you do not version them138 usually.139 140 A popular approach is to store configuration files for different servers141 in a separate version control repository and check them out on all142 servers. Then symlink the file that is active for the server into the154-location where it's expected (eg: ``/var/www/yourapplication``).143+location where it's expected (eg: :file:`/var/www/yourapplication`).144 145 Either way, in our case here we only expect one or two servers and we can146 upload them ahead of time by hand.147 148+149 First Deployment150 ----------------151 152 Now we can do our first deployment. We have set up the servers so that4 unmodified lines157 158 Fabric will now connect to all servers and run the commands as written159 down in the fabfile. First it will execute pack so that we have our160 tarball ready and then it will execute deploy and upload the source code171-to all servers and install it there. Thanks to the `setup.py` file we161+to all servers and install it there. Thanks to the :file:`setup.py` file we162 will automatically pull in the required libraries into our virtual163 environment.164 165 Next Steps9 unmodified lines175 - 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.180 181 Working with Fabric is fun and you will notice that it's quite magical to182 type ``fab deploy`` and see your application being deployed automatically183 to one or more remote servers.184 185 196-.. _Fabric: http://fabfile.org/186+.. _Fabric: http://www.fabfile.org/modified:docs/patterns/favicon.rst+4 added-4 removed
2 unmodified lines3 4 A "favicon" is an icon used by browsers for tabs and bookmarks. This helps5 to distinguish your website and to give it a unique brand.6 7-A common question is how to add a favicon to a flask application. First, of7+A common question is how to add a favicon to a Flask application. First, of8 course, you need an icon. It should be 16 × 16 pixels and in the ICO file9 format. This is not a requirement but a de-facto standard supported by all10 relevant browsers. Put the icon in your static directory as11 :file:`favicon.ico`.7 unmodified lines19 20 That's all you need for most browsers, however some really old ones do not21 support this standard. The old de-facto standard is to serve this file,22 with this name, at the website root. If your application is not mounted at23-the root path of the domain you either need to configure the webserver to23+the root path of the domain you either need to configure the web server to24 serve the icon at the root or if you can't do that you're out of luck. If25 however your application is the root you can simply route a redirect::26 27 app.add_url_rule('/favicon.ico',15 unmodified lines43 same.44 45 The above will serve the icon via your application and if possible it's46 better to configure your dedicated web server to serve it; refer to the47-webserver's documentation.47+web server's documentation.48 49 See also50 --------51 52-* The `Favicon <http://en.wikipedia.org/wiki/Favicon>`_ article on52+* The `Favicon <https://en.wikipedia.org/wiki/Favicon>`_ article on53 Wikipediamodified:docs/patterns/fileuploads.rst+33 added-30 removed
19 unmodified lines20 specific upload folder and displays a file to the user. Let's look at the21 bootstrapping code for our application::22 23 import os24- from flask import Flask, request, redirect, url_for24+ from flask import Flask, flash, request, redirect, url_for25 from werkzeug.utils import secure_filename26 27 UPLOAD_FOLDER = '/path/to/the/uploads'28 ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])2 unmodified lines31 app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER32 33 So 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 a37-URL rule by hand to the application. Now usually we're not doing that, so38-why here? The reasons is that we want the webserver (or our development39-server) to serve these files for us and so we only need a rule to generate40-the 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.37 38 Why do we limit the extensions that are allowed? You probably don't want39 your users to be able to upload everything there if the server is directly40 sending out the data to the client. That way you can make sure that users41 are not able to upload HTML files that would cause XSS problems (see46-:ref:`xss`). Also make sure to disallow `.php` files if the server47-executes them, but who has PHP installed on his server, right? :)42+:ref:`xss`). Also make sure to disallow ``.php`` files if the server43+executes them, but who has PHP installed on their server, right? :)44 45 Next the functions that check if an extension is valid and that uploads46 the file and redirects the user to the URL for the uploaded file::47 48 def allowed_file(filename):49 return '.' in filename and \54- filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS50+ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS51 52 @app.route('/', methods=['GET', 'POST'])53 def upload_file():54 if request.method == 'POST':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 line70 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 '''79 80 So what does that :func:`~werkzeug.utils.secure_filename` function actually do?12 unmodified lines93 94 filename = "../../../../home/username/.bashrc"95 96 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 line103 104 >>> secure_filename('../../../../home/username/.bashrc')105 'home_username_.bashrc'106 102-Now one last thing is missing: the serving of the uploaded files. As of103-Flask 0.5 we can use a function that does that for us::107+Now one last thing is missing: the serving of the uploaded files. In the108+:func:`upload_file()` we redirect the user to109+``url_for('uploaded_file', filename=filename)``, that is, ``/uploads/filename``.110+So we write the :func:`uploaded_file` function to return the file of that name. As111+of Flask 0.5 we can use a function that does that for us::112 113 from flask import send_from_directory114 115 @app.route('/uploads/<filename>')51 unmodified lines167 client asks the server every 5 seconds how much it has transmitted168 already. Do you realize the irony? The client is asking for something it169 should already know.170 163-Now there are better solutions to that work faster and more reliable. The164-web changed a lot lately and you can use HTML5, Java, Silverlight or Flash165-to get a nicer uploading experience on the client side. Look at the166-following libraries for some nice examples how to do that:167-168-- `Plupload <http://www.plupload.com/>`_ - HTML5, Java, Flash169-- `SWFUpload <http://www.swfupload.org/>`_ - Flash170-- `JumpLoader <http://jumploader.com/>`_ - Java171-172-171 An Easier Solution172 ------------------173 174+Now there are better solutions that work faster and are more reliable. There175+are JavaScript libraries like jQuery_ that have form plugins to ease the176+construction of progress bar.177+178 Because the common pattern for file uploads exists almost unchanged in all177-applications dealing with uploads, there is a Flask extension called178-`Flask-Uploads`_ that implements a full fledged upload mechanism with179-white and blacklisting of extensions and more.179+applications dealing with uploads, there is also a Flask extension called180+`Flask-Uploads`_ that implements a full fledged upload mechanism with white and181+blacklisting of extensions and more.182 183+.. _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 lines8 application. Flask provides a really simple way to give feedback to a9 user with the flashing system. The flashing system basically makes it10 possible to record a message at the end of a request and access it next11 request and only next request. This is usually combined with a layout12-template that does this.12+template that does this. Note that browsers and sometimes web servers enforce13+a limit on cookie sizes. This means that flashing messages that are too14+large for session cookies causes message flashing to fail silently.15 16 Simple Flashing17 ---------------18 20 unmodified lines39 flash('You were successfully logged in')40 return redirect(url_for('index'))41 return render_template('login.html', error=error)42 41- if __name__ == "__main__":42- app.run()43+And here is the :file:`layout.html` template which does the magic:44 44-45-And here the ``layout.html`` template which does the magic:46-45 .. sourcecode:: html+jinja46 47 <!doctype html>48 <title>My Application</title>7 unmodified lines56 {% endif %}57 {% endwith %}58 {% block body %}{% endblock %}59 62-And here the index.html template:60+Here is the :file:`index.html` template which inherits from :file:`layout.html`:61 62 .. sourcecode:: html+jinja63 64 {% extends "layout.html" %}1 unmodified line66 <h1>Overview</h1>67 <p>Do you want to <a href="{{ url_for('login') }}">log in?</a>68 {% endblock %}69 72-And of course the login template:70+And here is the :file:`login.html` template which also inherits from71+:file:`layout.html`:72 73 .. sourcecode:: html+jinja74 75 {% extends "layout.html" %}1 unmodified line77 <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 linesmodified:docs/patterns/index.rst+1 added
39 unmodified lines40 deferredcallbacks41 methodoverrides42 requestchecksum43 celery44+ subclassingmodified:docs/patterns/jquery.rst+8 added-8 removed
17 unmodified lines18 19 In order to use jQuery, you have to download it first and place it in the20 static folder of your application and then ensure it's loaded. Ideally21 you have a layout template that is used for all pages where you just have22-to add a script statement to the bottom of your `<body>` to load jQuery:22+to add a script statement to the bottom of your ``<body>`` to load jQuery:23 24 .. sourcecode:: html25 26 <script type=text/javascript src="{{37 unmodified lines64 </script>65 66 The ``|safe`` is necessary in Flask before 0.10 so that Jinja does not67 escape the JSON encoded string with HTML rules. Usually this would be68-necessary, but we are inside a `script` block here where different rules68+necessary, but we are inside a ``script`` block here where different rules69 apply.70 71 .. admonition:: Information for Pros72 73- 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 as40 unmodified lines118 119 The HTML120 --------121 122-Your index.html template either has to extend a `layout.html` template with122+Your index.html template either has to extend a :file:`layout.html` template with123 jQuery loaded and the `$SCRIPT_ROOT` variable set, or do that on the top.124-Here's the HTML code needed for our little application (`index.html`).124+Here's the HTML code needed for our little application (:file:`index.html`).125 Notice that we also drop the script directly into the HTML here. It is126 usually a better idea to have that in a separate script file:127 128 .. sourcecode:: html26 unmodified lines155 3. ``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).159-4. ``$.getJSON(url, data, func)`` sends a `GET` request to `url` and will159+4. ``$.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.164 165 If you don't get the whole picture, download the `sourcecode166 for this example167-<http://github.com/mitsuhiko/flask/tree/master/examples/jqueryexample>`_168-from github.167+<https://github.com/pallets/flask/tree/master/examples/jqueryexample>`_168+from GitHub.modified:docs/patterns/lazyloading.rst+13 added-8 removed
30 unmodified lines31 @app.route('/user/<username>')32 def user(username):33 pass34 35-Then the centralized approach you would have one file with the views36-(`views.py`) but without any decorator::35+Then, with the centralized approach you would have one file with the views36+(:file:`views.py`) but without any decorator::37 38 def index():39 pass40 12 unmodified lines53 Loading Late54 ------------55 56 So far we only split up the views and the routing, but the module is still57-loaded upfront. The trick to actually load the view function as needed.57+loaded upfront. The trick is to actually load the view function as needed.58 This can be accomplished with a helper class that behaves just like a59 function but internally imports the real function on first use::60 61 from werkzeug import import_string, cached_property27 unmodified lines89 90 You can further optimize this in terms of amount of keystrokes needed to91 write this by having a function that calls into92 :meth:`~flask.Flask.add_url_rule` by prefixing a string with the project93-name and a dot, and by wrapping `view_func` in a `LazyView` as needed::93+name and a dot, and by wrapping `view_func` in a `LazyView` as needed. ::94 95- def url(url_rule, import_name, **options):95+ def url(import_name, url_rules=[], **options):96 view = LazyView('yourapplication.' + import_name)97+ for url_rule in url_rules:97- app.add_url_rule(url_rule, view_func=view, **options)98+ app.add_url_rule(url_rule, view_func=view, **options)99 99- url('/', 'views.index')100- url('/user/<username>', 'views.user')100+ # add a single route to the index view101+ url('views.index', ['/'])102 103+ # add two routes to a single function endpoint104+ url_rules = ['/user/','/user/<username>']105+ url('views.user', url_rules)106+107 One thing to keep in mind is that before and after request handlers have108 to be in a file that is imported upfront to work properly on the first109 request. The same goes for any kind of remaining decorator.modified:docs/patterns/mongokit.rst+7 added-4 removed
18 unmodified lines19 20 The default behavior of MongoKit is the declarative one that is based on21 common ideas from Django or the SQLAlchemy declarative extension.22 23-Here an example `app.py` module for your application::23+Here an example :file:`app.py` module for your application::24 25 from flask import Flask26 from mongokit import Connection, Document27 18 unmodified lines46 MongoDB is schemaless. This means you can modify the data structure from one47 insert query to the next without any problem. MongoKit is just schemaless48 too, but implements some validation to ensure data integrity.49 50-Here is an example document (put this also into `app.py`, e.g.)::50+Here is an example document (put this also into :file:`app.py`, e.g.)::51 52+ from mongokit import ValidationError53+54 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 validate61 62 class User(Document):63 structure = {14 unmodified lines78 79 This example shows you how to define your schema (named structure), a80 validator for the maximum character length and uses a special MongoKit feature81 called `use_dot_notation`. Per default MongoKit behaves like a python79-dictionary but with `use_dot_notation` set to `True` you can use your82+dictionary but with `use_dot_notation` set to ``True`` you can use your83 documents like you use models in nearly any other ORM by using dots to84 separate between attributes.85 86 You can insert entries into the database like this:58 unmodified linesmodified:docs/patterns/packages.rst+51 added-21 removed
6 unmodified lines7 module. That is quite simple. Imagine a small application looks like8 this::9 10 /yourapplication11- /yourapplication.py11+ yourapplication.py12 /static13- /style.css13+ style.css14 /templates15 layout.html16 index.html17 login.html18 ...19 20+If you find yourself stuck on something, feel free21+to take a look at the source code for this example.22+You'll find `the full src for this example here`_.23+24 Simple Packages25 ---------------26 27 To convert that into a larger one, just create a new folder24-`yourapplication` inside the existing one and move everything below it.25-Then rename `yourapplication.py` to `__init__.py`. (Make sure to delete26-all `.pyc` files first, otherwise things would most likely break)28+:file:`yourapplication` inside the existing one and move everything below it.29+Then rename :file:`yourapplication.py` to :file:`__init__.py`. (Make sure to delete30+all ``.pyc`` files first, otherwise things would most likely break)31 32 You should then end up with something like that::33 34 /yourapplication35 /yourapplication32- /__init__.py36+ __init__.py37 /static34- /style.css38+ style.css39 /templates40 layout.html41 index.html42 login.html1 unmodified line44 45 But how do you run your application now? The naive ``python46 yourapplication/__init__.py`` will not work. Let's just say that Python47 does not want modules in packages to be the startup file. But that is not44-a big problem, just add a new file called `runserver.py` next to the inner45-`yourapplication` folder with the following contents::48+a big problem, just add a new file called :file:`setup.py` next to the inner49+:file:`yourapplication` folder with the following contents::50 47- from yourapplication import app48- app.run(debug=True)51+ from setuptools import setup52 53+ setup(54+ name='yourapplication',55+ packages=['yourapplication'],56+ include_package_data=True,57+ install_requires=[58+ 'flask',59+ ],60+ )61+62+In order to run the application you need to export an environment variable 63+that tells Flask where to find the application instance:: 64+65+ export FLASK_APP=yourapplication66+67+If you are outside of the project directory make sure to provide the exact 68+path to your application directory. Similarly you can turn on "debug 69+mode" with this environment variable:: 70+71+ export FLASK_DEBUG=true 72+73+In order to install and run the application you need to issue the following 74+commands::75+76+ pip install -e . 77+ flask run78+79 What did we gain from this? Now we can restructure the application a bit80 into multiple modules. The only thing you have to remember is the81 following quick checklist:82 83 1. 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.86 2. 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**.90 62-Here's an example `__init__.py`::91+Here's an example :file:`__init__.py`::92 93 from flask import Flask94 app = Flask(__name__)95 96 import yourapplication.views97 69-And this is what `views.py` would look like::98+And this is what :file:`views.py` would look like::99 100 from yourapplication import app101 102 @app.route('/')2 unmodified lines105 106 You should then end up with something like that::107 108 /yourapplication80- /runserver.py109+ setup.py110 /yourapplication82- /__init__.py83- /views.py111+ __init__.py112+ views.py113 /static85- /style.css114+ style.css115 /templates116 layout.html117 index.html118 login.html2 unmodified lines121 .. admonition:: Circular Imports122 123 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.130 131 There are still some problems with that approach but if you want to use1 unmodified line133 :ref:`becomingbig` section for some inspiration how to deal with that.134 135 136 .. _working-with-modules:137+.. _the full src for this example here: https://github.com/pallets/flask/tree/master/examples/patterns/largerapp138 139 Working with Blueprints140 -----------------------141 4 unmodified linesmodified:docs/patterns/sqlalchemy.rst+12 added-12 removed
18 unmodified lines19 there is a Flask extension that handles that for you. This is recommended20 if you want to get started quickly.21 22 You can download `Flask-SQLAlchemy`_ from `PyPI23-<http://pypi.python.org/pypi/Flask-SQLAlchemy>`_.23+<https://pypi.python.org/pypi/Flask-SQLAlchemy>`_.24 25-.. _Flask-SQLAlchemy: http://packages.python.org/Flask-SQLAlchemy/25+.. _Flask-SQLAlchemy: http://flask-sqlalchemy.pocoo.org/26 27 28 Declarative29 -----------2 unmodified lines32 SQLAlchemy. It allows you to define tables and models in one go, similar33 to how Django works. In addition to the following text I recommend the34 official documentation on the `declarative`_ extension.35 36-Here the example `database.py` module for your application::36+Here's the example :file:`database.py` module for your application::37 38 from sqlalchemy import create_engine39 from sqlalchemy.orm import scoped_session, sessionmaker40 from sqlalchemy.ext.declarative import declarative_base28 unmodified lines69 @app.teardown_appcontext70 def shutdown_session(exception=None):71 db_session.remove()72 73-Here is an example model (put this into `models.py`, e.g.)::73+Here is an example model (put this into :file:`models.py`, e.g.)::74 75 from sqlalchemy import Column, Integer, String76 from yourapplication.database import Base77 29 unmodified lines107 [<User u'admin'>]108 >>> User.query.filter(User.name == 'admin').first()109 <User u'admin'>110 111-.. _SQLAlchemy: http://www.sqlalchemy.org/111+.. _SQLAlchemy: https://www.sqlalchemy.org/112 .. _declarative:113- http://www.sqlalchemy.org/docs/orm/extensions/declarative.html113+ https://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/114 115 Manual Object Relational Mapping116 --------------------------------117 3 unmodified lines121 flexible but a little more to type. In general it works like the122 declarative approach, so make sure to also split up your application into123 multiple modules in a package.124 125-Here is an example `database.py` module for your application::125+Here is an example :file:`database.py` module for your application::126 127 from sqlalchemy import create_engine, MetaData128 from sqlalchemy.orm import scoped_session, sessionmaker129 4 unmodified lines134 bind=engine))135 def init_db():136 metadata.create_all(bind=engine)137 138-As for the declarative approach you need to close the session after138+As in the declarative approach, you need to close the session after139 each request or application context shutdown. Put this into your140 application module::141 142 from yourapplication.database import db_session1 unmodified line144 @app.teardown_appcontext145 def shutdown_session(exception=None):146 db_session.remove()147 148-Here is an example table and model (put this into `models.py`)::148+Here is an example table and model (put this into :file:`models.py`)::149 150 from sqlalchemy import Table, Column, Integer, String151 from sqlalchemy.orm import mapper152 from yourapplication.database import metadata, db_session23 unmodified lines176 177 If you just want to use the database system (and SQL) abstraction layer178 you basically only need the engine::179 180- from sqlalchemy import create_engine, MetaData180+ from sqlalchemy import create_engine, MetaData, Table181 182 engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)183 metadata = MetaData(bind=engine)184 185 Then you can either declare the tables in your code like in the examples186 above, or automatically load them::187 188 from sqlalchemy import Table189- 189+190 users = Table('users', metadata, autoload=True)191 192 To insert data you can use the `insert` method. We have to get a193 connection first so that we can use a transaction:20 unmodified lines214 >>> engine.execute('select * from users where id = :1', [1]).first()215 (1, u'admin', u'admin@localhost')216 217 For more information about SQLAlchemy, head over to the218-`website <http://sqlalchemy.org/>`_.218+`website <https://www.sqlalchemy.org/>`_.modified:docs/patterns/sqlite3.rst+36 added-20 removed
1 unmodified line2 3 Using SQLite 3 with Flask4 =========================5 6-In Flask you can implement the opening of database connections on demand7-and closing it when the context dies (usually at the end of the request)8-easily.6+In Flask you can easily implement the opening of database connections on7+demand and closing them when the context dies (usually at the end of the8+request).9 10 Here is a simple example of how you can use SQLite 3 with Flask::11 12 import sqlite312 unmodified lines25 db = getattr(g, '_database', None)26 if db is not None:27 db.close()28 29-All the application needs to do in order to now use the database is having30-an active application context (which is always true if there is an request31-in flight) or to create an application context itself. At that point the32-``get_db`` function can be used to get the current database connection.33-Whenever the context is destroyed the database connection will be34-terminated.29+Now, to use the database, the application must either have an active30+application context (which is always true if there is a request in flight)31+or create an application context itself. At that point the ``get_db``32+function can be used to get the current database connection. Whenever the33+context is destroyed the database connection will be terminated.34 35 Note: 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`37 object was bound to the request and not application context.16 unmodified lines54 Connect on Demand55 -----------------56 57 The upside of this approach (connecting on first use) is that this will59-only opening the connection if truly necessary. If you want to use this58+only open the connection if truly necessary. If you want to use this59 code outside a request context you can use it in a Python shell by opening60 the application context by hand::61 62 with app.app_context():6 unmodified lines69 70 Now in each request handling function you can access `g.db` to get the71 current open database connection. To simplify working with SQLite, a72 row factory function is useful. It is executed for every result returned74-from the database to convert the result. For instance in order to get75-dictionaries instead of tuples this could be inserted into ``get_db``::73+from the database to convert the result. For instance, in order to get74+dictionaries instead of tuples, this could be inserted into the ``get_db``75+function we created above::76 77 def make_dicts(cursor, row):78 return dict((cursor.description[idx][0], value)79 for idx, value in enumerate(row))80 81 db.row_factory = make_dicts82 83-Or even simpler::83+This will make the sqlite3 module return dicts for this database connection, which are much nicer to deal with. Even more simply, we could place this in ``get_db`` instead::84 85 db.row_factory = sqlite3.Row86 87+This would use Row objects rather than dicts to return the results of queries. These are ``namedtuple`` s, so we can access them either by index or by key. For example, assuming we have a ``sqlite3.Row`` called ``r`` for the rows ``id``, ``FirstName``, ``LastName``, and ``MiddleInitial``::88+89+ >>> # You can get values based on the row's name90+ >>> r['FirstName']91+ John92+ >>> # Or, you can get them based on index93+ >>> r[1]94+ John95+ # Row objects are also iterable:96+ >>> for value in r:97+ ... print(value)98+ 199+ John100+ Doe101+ M102+87-Additionally it is a good idea to provide a query function that combines103+Additionally, it is a good idea to provide a query function that combines104 getting the cursor, executing and fetching the results::89- 105+106 def query_db(query, args=(), one=False):107 cur = get_db().execute(query, args)108 rv = cur.fetchall()109 cur.close()110 return (rv[0] if rv else None) if one else rv111 96-This handy little function in combination with a row factory makes working97-with the database much more pleasant than it is by just using the raw98-cursor and connection objects.112+This handy little function, in combination with a row factory, makes113+working with the database much more pleasant than it is by just using the114+raw cursor and connection objects.115 116 Here is how you can use it::117 118 for user in query_db('select * from users'):11 unmodified lines130 To pass variable parts to the SQL statement, use a question mark in the131 statement and pass in the arguments as a list. Never directly add them to132 the SQL statement with string formatting because this makes it possible133 to attack the application using `SQL Injections118-<http://en.wikipedia.org/wiki/SQL_injection>`_.134+<https://en.wikipedia.org/wiki/SQL_injection>`_.135 136 Initial Schemas137 ---------------138 8 unmodified lines147 with app.open_resource('schema.sql', mode='r') as f:148 db.cursor().executescript(f.read())149 db.commit()150 135-You can then create such a database from the python shell:151+You can then create such a database from the Python shell:152 153 >>> from yourapplication import init_db154 >>> init_db()added:docs/patterns/subclassing.rst+17 added
1+Subclassing Flask2+=================3+4+The :class:`~flask.Flask` class is designed for subclassing.5+6+For example, you may want to override how request parameters are handled to preserve their order::7+8+ from flask import Flask, Request9+ from werkzeug.datastructures import ImmutableOrderedMultiDict10+ class MyRequest(Request):11+ """Request subclass to override request parameter storage"""12+ parameter_storage_class = ImmutableOrderedMultiDict13+ class MyFlask(Flask):14+ """Flask subclass using the custom request class"""15+ request_class = MyRequest16+17+This is the recommended approach for overriding or augmenting Flask's internal functionality.modified:docs/patterns/templateinheritance.rst+1 added-1 removed
12 unmodified lines13 14 Base Template15 -------------16 17-This template, which we'll call ``layout.html``, defines a simple HTML skeleton17+This template, which we'll call :file:`layout.html`, defines a simple HTML skeleton18 document that you might use for a simple two-column page. It's the job of19 "child" templates to fill the empty blocks with content:20 21 .. sourcecode:: html+jinja49 unmodified linesmodified:docs/patterns/viewdecorators.rst+31 added-27 removed
1 View Decorators2 ===============3 4 Python has a really interesting feature called function decorators. This5-allow some really neat things for web applications. Because each view in6-Flask is a function decorators can be used to inject additional5+allows some really neat things for web applications. Because each view in6+Flask is a function, decorators can be used to inject additional7 functionality to one or more functions. The :meth:`~flask.Flask.route`8 decorator is the one you probably used already. But there are use cases9 for implementing your own decorator. For instance, imagine you have a10-view that should only be used by people that are logged in to. If a user10+view that should only be used by people that are logged in. If a user11 goes to the site and is not logged in, they should be redirected to the12 login page. This is a good example of a use case where a decorator is an13 excellent solution.14 15 Login Required Decorator16 ------------------------17 18 So let's implement such a decorator. A decorator is a function that19-returns a function. Pretty simple actually. The only thing you have to20-keep in mind when implementing something like this is to update the21-`__name__`, `__module__` and some other attributes of a function. This is22-often forgotten, but you don't have to do that by hand, there is a23-function for that that is used like a decorator (:func:`functools.wraps`).19+wraps and replaces another function. Since the original function is20+replaced, you need to remember to copy the original function's information21+to the new function. Use :func:`functools.wraps` to handle this for you.22 23 This example assumes that the login page is called ``'login'`` and that26-the current user is stored as `g.user` and `None` if there is no-one27-logged in::24+the current user is stored in ``g.user`` and is ``None`` if there is no-one25+logged in. ::26 27 from functools import wraps28 from flask import g, request, redirect, url_for29 4 unmodified lines34 return redirect(url_for('login', next=request.url))35 return f(*args, **kwargs)36 return decorated_function37 40-So how would you use that decorator now? Apply it as innermost decorator41-to a view function. When applying further decorators, always remember42-that the :meth:`~flask.Flask.route` decorator is the outermost::38+To use the decorator, apply it as innermost decorator to a view function.39+When applying further decorators, always remember40+that the :meth:`~flask.Flask.route` decorator is the outermost. ::41 42 @app.route('/secret_page')43 @login_required44 def secret_page():45 pass46 47+.. note::48+ The ``next`` value will exist in ``request.args`` after a ``GET`` request for49+ the login page. You'll have to pass it along when sending the ``POST`` request50+ from the login form. You can do this with a hidden input tag, then retrieve it51+ from ``request.form`` when logging the user in. ::52+53+ <input type="hidden" value="{{ request.args.get('next', '') }}"/>54+55+56 Caching Decorator57 -----------------58 59 Imagine you have a view function that does an expensive calculation and60 because of that you would like to cache the generated results for a61 certain amount of time. A decorator would be nice for that. We're62 assuming you have set up a cache like mentioned in :ref:`caching-pattern`.63 57-Here an example cache function. It generates the cache key from a64+Here is an example cache function. It generates the cache key from a65 specific prefix (actually a format string) and the current path of the66 request. Notice that we are using a function that first creates the67 decorator that then decorates the function. Sounds awful? Unfortunately68 it is a little bit more complex, but the code should still be57 unmodified lines126 As you can see, if no template name is provided it will use the endpoint127 of the URL map with dots converted to slashes + ``'.html'``. Otherwise128 the provided template name is used. When the decorated function returns,129 the 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 than131 a dictionary is returned we return it from the function unchanged. That132 way you can still use the redirect function or return simple strings.133 127-Here the code for that decorator::134+Here is the code for that decorator::135 136 from functools import wraps130- from flask import request137+ from flask import request, render_template138 139 def templated(template=None):140 def decorator(f):141 @wraps(f)15 unmodified lines157 Endpoint Decorator158 ------------------159 160 When you want to use the werkzeug routing system for more flexibility you154-need to map the endpoint as defined in the :class:`~werkzeug.routing.Rule` 155-to a view function. This is possible with this decorator. For example:: 161+need to map the endpoint as defined in the :class:`~werkzeug.routing.Rule`162+to a view function. This is possible with this decorator. For example::163 164 from flask import Flask165 from werkzeug.routing import Rule166 160- app = Flask(__name__) 161- app.url_map.add(Rule('/', endpoint='index')) 167+ app = Flask(__name__)168+ app.url_map.add(Rule('/', endpoint='index'))169 163- @app.endpoint('index') 164- def my_index(): 165- return "Hello world" 166-167-168-170+ @app.endpoint('index')171+ def my_index():172+ return "Hello world"modified:docs/patterns/wtforms.rst+28 added-28 removed
1 Form Validation with WTForms2 ============================3 4-When you have to work with form data submitted by a browser view code4+When you have to work with form data submitted by a browser view, code5 quickly becomes very hard to read. There are libraries out there designed6 to make this process easier to manage. One of them is `WTForms`_ which we7 will handle here. If you find yourself in the situation of having many8 forms, you might want to give it a try.9 10 When you are working with WTForms you have to define your forms as classes11-first. I recommend breaking up the application into multiple modules 11+first. I recommend breaking up the application into multiple modules12 (:ref:`larger-applications`) for that and adding a separate module for the13 forms.14 15-.. admonition:: Getting most of WTForms with an Extension15+.. admonition:: Getting the most out of WTForms with an Extension16 17- 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>`_.21 22-.. _Flask-WTF: http://packages.python.org/Flask-WTF/22+.. _Flask-WTF: https://flask-wtf.readthedocs.io/en/stable/23 24 The Forms25 ---------26 27 This is an example form for a typical registration page::28 29- from wtforms import Form, BooleanField, TextField, PasswordField, validators29+ from wtforms import Form, BooleanField, StringField, PasswordField, validators30 31 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()])40 41 In the View42 -----------43 9 unmodified lines53 flash('Thanks for registering')54 return redirect(url_for('login'))55 return render_template('register.html', form=form)56 57-Notice that we are implying that the view is using SQLAlchemy here58-(:ref:`sqlalchemy-pattern`) but this is no requirement of course. Adapt57+Notice we're implying that the view is using SQLAlchemy here58+(:ref:`sqlalchemy-pattern`), but that's not a requirement, of course. Adapt59 the code as necessary.60 61 Things to remember:62 63 1. 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``.66 2. 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.69 3. to access individual values from the form, access `form.<NAME>.data`.70 71 Forms in Templates72 ------------------73 74-Now to the template side. When you pass the form to the templates you can74+Now to the template side. When you pass the form to the templates, you can75 easily render them there. Look at the following example template to see76 how easy this is. WTForms does half the form generation for us already.77 To make it even nicer, we can write a macro that renders a field with78 label and a list of errors if there are any.79 80-Here's an example `_formhelpers.html` template with such a macro:80+Here's an example :file:`_formhelpers.html` template with such a macro:81 82 .. sourcecode:: html+jinja83 84 {% macro render_field(field) %}9 unmodified lines94 </dd>95 {% endmacro %}96 97 This macro accepts a couple of keyword arguments that are forwarded to98-WTForm's field function that renders the field for us. The keyword99-arguments will be inserted as HTML attributes. So for example you can98+WTForm's field function, which renders the field for us. The keyword99+arguments will be inserted as HTML attributes. So, for example, you can100 call ``render_field(form.username, class='username')`` to add a class to101 the input element. Note that WTForms returns standard Python unicode102-strings, so we have to tell Jinja2 that this data is already HTML escaped103-with the `|safe` filter.102+strings, so we have to tell Jinja2 that this data is already HTML-escaped103+with the ``|safe`` filter.104 105-Here the `register.html` template for the function we used above which106-takes advantage of the `_formhelpers.html` template:105+Here is the :file:`register.html` template for the function we used above, which106+takes advantage of the :file:`_formhelpers.html` template:107 108 .. sourcecode:: html+jinja109 110 {% from "_formhelpers.html" import render_field %}111- <form method=post action="/register">111+ <form method=post>112 <dl>113 {{ render_field(form.username) }}114 {{ render_field(form.email) }}115 {{ render_field(form.password) }}5 unmodified lines121 122 For more information about WTForms, head over to the `WTForms123 website`_.124 125-.. _WTForms: http://wtforms.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:2 3-Step 7: Adding Style3+Step 8: Adding Style4 ====================5 6 Now that everything else works, it's time to add some style to the7-application. Just create a stylesheet called `style.css` in the `static`8-folder we created before:7+application. Just create a stylesheet called :file:`style.css` in the8+:file:`static` folder:9 10 .. sourcecode:: css11 12 body { font-family: sans-serif; background: #eee; }19 unmodified linesmodified:docs/tutorial/dbcon.rst+23 added-26 removed
1 .. _tutorial-dbcon:2 3-Step 3: Database Connections3+Step 4: Database Connections4 ----------------------------5 6-We have created a function for establishing a database connection with7-`connect_db` but by itself that's not particularly useful. Creating and8-closing database connections all the time is very inefficient, so we want9-to keep it around for longer. Because database connections encapsulate a10-transaction we also need to make sure that only one request at the time11-uses the connection. So how can we elegantly do that with Flask?6+You currently have a function for establishing a database connection with7+`connect_db`, but by itself, it is not particularly useful. Creating and8+closing database connections all the time is very inefficient, so you will9+need to keep it around for longer. Because database connections10+encapsulate a transaction, you will need to make sure that only one11+request at a time uses the connection. An elegant way to do this is by12+utilizing the *application context*.13 13-This is where the application context comes into play. So let's start14-there.15-16-Flask provides us with two contexts: the application context and the17-request context. For the time being all you have to know is that there18-are special variables that use these. For instance the14+Flask provides two contexts: the *application context* and the15+*request context*. For the time being, all you have to know is that there16+are special variables that use these. For instance, the17 :data:`~flask.request` variable is the request object associated with18 the current request, whereas :data:`~flask.g` is a general purpose21-variable associated with the current application context. We will go into22-the details of this a bit later.19+variable associated with the current application context. The tutorial20+will cover some more details of this later on.21 24-For the time being all you have to know is that you can store information22+For the time being, all you have to know is that you can store information23 safely on the :data:`~flask.g` object.24 25 So when do you put it on there? To do that you can make a helper28-function. The first time the function is called it will create a database29-connection for the current context and successive calls will return the26+function. The first time the function is called, it will create a database27+connection for the current context, and successive calls will return the28 already established connection::29 30 def get_db():31 """Opens a new database connection if there is none yet for the2 unmodified lines34 if not hasattr(g, 'sqlite_db'):35 g.sqlite_db = connect_db()36 return g.sqlite_db37 40-41-So now we know how to connect, but how do we properly disconnect? For42-that flask provides us with the :meth:`~flask.Flask.teardown_appcontext`38+Now you know how to connect, but how can you properly disconnect? For39+that, Flask provides us with the :meth:`~flask.Flask.teardown_appcontext`40 decorator. It's executed every time the application context tears down::41 42 @app.teardown_appcontext43 def close_db(error):1 unmodified line45 if hasattr(g, 'sqlite_db'):46 g.sqlite_db.close()47 48 Functions marked with :meth:`~flask.Flask.teardown_appcontext` are called52-every time the app context tears down. So what does this mean?53-Essentially the app context is created before the request comes in and is54-destroyed (teared down) whenever the request finishes. A teardown can49+every time the app context tears down. What does this mean?50+Essentially, the app context is created before the request comes in and is51+destroyed (torn down) whenever the request finishes. A teardown can52 happen because of two reasons: either everything went well (the error56-parameter will be `None`) or an exception happend in which case the error53+parameter will be ``None``) or an exception happened, in which case the error54 is passed to the teardown function.55 56 Curious about what these contexts mean? Have a look at the57 :ref:`app-context` documentation to learn more.13 unmodified lines71 into a single Python module. You don't have to, and if your app :ref:`grows72 larger <larger-applications>`, it's a good idea not to.73 74 .. _example source:78- 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:2 3-Step 4: Creating The Database3+Step 5: Creating The Database4 =============================5 6 As outlined earlier, Flaskr is a database powered application, and more7 precisely, it is an application powered by a relational database system. Such8-systems need a schema that tells them how to store that information. So9-before starting the server for the first time it's important to create8+systems need a schema that tells them how to store that information.9+Before starting the server for the first time, it's important to create10 that schema.11 12-Such a schema can be created by piping the `schema.sql` file into the12+Such a schema can be created by piping the ``schema.sql`` file into the13 `sqlite3` command as follows::14 15 sqlite3 /tmp/flaskr.db < schema.sql16 17-The downside of this is that it requires the sqlite3 command to be18-installed which is not necessarily the case on every system. This also19-require that we provide the path to the database which can introduce17+The downside of this is that it requires the ``sqlite3`` command to be18+installed, which is not necessarily the case on every system. This also19+requires that you provide the path to the database, which can introduce20 errors. It's a good idea to add a function that initializes the database21-for you to the application.21+for you, to the application.22 23-To do this we can create a function called `init_db` that initializes the24-database. Let me show you the code first. Just add this function below25-the `connect_db` function in `flaskr.py`::23+To do this, you can create a function and hook it into a :command:`flask`24+command that initializes the database. For now just take a look at the25+code segment below. A good place to add this function, and command, is26+just below the `connect_db` function in :file:`flaskr.py`::27 28 def init_db():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()33 34-So what's happening here? Remember how we learned last chapter that the35-application context is created every time a request comes in? Here we36-don't have a request yet, so we need to create the application context by37-hand. Without an application context the :data:`~flask.g` object does not38-know 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.')39 40-The ``with app.app_context()`` statement establishes the application41-context for us. In the body of the with statement the :data:`~flask.g`42-object will be associated with ``app``. At the end of the with statement43-the association is released and all teardown functions are executed. This44-means that our database connection is disconnected after the commit.40+The ``app.cli.command()`` decorator registers a new command with the41+:command:`flask` script. When the command executes, Flask will automatically42+create an application context which is bound to the right application.43+Within the function, you can then access :attr:`flask.g` and other things as44+you might expect. When the script ends, the application context tears down45+and the database connection is released.46 47+You will want to keep an actual function around that initializes the database,48+though, so that we can easily create databases in unit tests later on. (For49+more information see :ref:`testing`.)50+51 The :func:`~flask.Flask.open_resource` method of the application object52 is a convenient helper function that will open a resource that the53 application provides. This function opens a file from the resource49-location (your `flaskr` folder) and allows you to read from it. We are50-using this here to execute a script on the database connection.54+location (the :file:`flaskr/flaskr` folder) and allows you to read from it.55+It is used in this example to execute a script on the database connection.56 52-The connection object provided by SQLite can give us a cursor object.53-On that cursor there is a method to execute a complete script. Finally we54-only have to commit the changes. SQLite 3 and other transactional57+The connection object provided by SQLite can give you a cursor object.58+On that cursor, there is a method to execute a complete script. Finally, you59+only have to commit the changes. SQLite3 and other transactional60 databases will not commit unless you explicitly tell it to.61 57-Now it is possible to create a database by starting up a Python shell and58-importing and calling that function::62+Now, it is possible to create a database with the :command:`flask` script::63 60->>> from flaskr import init_db61->>> init_db()64+ flask initdb65+ Initialized the database.66 67 .. admonition:: Troubleshooting68 65- 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).72 73 Continue with :ref:`tutorial-views`modified:docs/tutorial/folders.rst+16 added-12 removed
1 unmodified line2 3 Step 0: Creating The Folders4 ============================5 6-Before we get started, let's create the folders needed for this6+Before getting started, you will need to create the folders needed for this7 application::8 9 /flaskr10+ /flaskr10- /static11- /templates11+ /static12+ /templates13 13-The `flaskr` folder is not a python package, but just something where we14-drop our files. We will then put our database schema as well as main module15-into this folder. It is done in the following way. The files inside16-the `static` folder are available to users of the application via `HTTP`.17-This is the place where css and javascript files go. Inside the18-`templates` folder Flask will look for `Jinja2`_ templates. The19-templates you create later in the tutorial will go in this directory.14+The application will be installed and run as Python package. This is the15+recommended way to install and run Flask applications. You will see exactly16+how to run ``flaskr`` later on in this tutorial. For now go ahead and create17+the applications directory structure. In the next few steps you will be18+creating the database schema as well as the main module.19 21-Continue with :ref:`tutorial-schema`.20+As a quick side note, the files inside of the :file:`static` folder are21+available to users of the application via HTTP. This is the place where CSS and22+JavaScript files go. Inside the :file:`templates` folder, Flask will look for23+`Jinja2`_ templates. You will see examples of this later on.24 25+For now you should continue with :ref:`tutorial-schema`.26+23-.. _Jinja2: http://jinja.pocoo.org/2/27+.. _Jinja2: http://jinja.pocoo.org/modified:docs/tutorial/index.rst+6 added-5 removed
2 unmodified lines3 Tutorial4 ========5 6 You want to develop an application with Python and Flask? Here you have7-the chance to learn that by example. In this tutorial we will create a8-simple microblog application. It only supports one user that can create7+the chance to learn by example. In this tutorial, we will create a simple8+microblogging application. It only supports one user that can create9 text-only entries and there are no feeds or comments, but it still10 features everything you need to get started. We will use Flask and SQLite11-as database which comes out of the box with Python, so there is nothing11+as a database (which comes out of the box with Python) so there is nothing12 else you need.13 14-If you want the full sourcecode in advance or for comparison, check out14+If you want the full source code in advance or for comparison, check out15 the `example source`_.16 17 .. _example source:18- http://github.com/mitsuhiko/flask/tree/master/examples/flaskr/18+ https://github.com/pallets/flask/tree/master/examples/flaskr/19 20 .. toctree::21 :maxdepth: 222 23 introduction24 folders25 schema26 setup27+ packaging28 dbcon29 dbinit30 views31 templates2 unmodified linesmodified:docs/tutorial/introduction.rst+13 added-12 removed
1 unmodified line2 3 Introducing Flaskr4 ==================5 6-We will call our blogging application flaskr here, feel free to choose a7-less web-2.0-ish name ;) Basically we want it to do the following things:6+This tutorial will demonstrate a blogging application named Flaskr, but feel7+free to choose your own less Web-2.0-ish name ;) Essentially, it will do the8+following things:9 9-1. let the user sign in and out with credentials specified in the10+1. Let the user sign in and out with credentials specified in the11 configuration. Only one user is supported.11-2. when the user is logged in they can add new entries to the page12+2. 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.14-3. 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.15+3. The index page shows all entries so far in reverse chronological order16+ (newest on top) and the user can add new ones from there if logged in.17 17-We will be using SQLite3 directly for that application because it's good18-enough for an application of that size. For larger applications however19-it makes a lot of sense to use `SQLAlchemy`_ that handles database20-connections in a more intelligent way, allows you to target different18+SQLite3 will be used directly for this application because it's good enough19+for an application of this size. For larger applications, however,20+it makes a lot of sense to use `SQLAlchemy`_, as it handles database21+connections in a more intelligent way, allowing you to target different22 relational databases at once and more. You might also want to consider23 one of the popular NoSQL databases if your data is more suited for those.24 24-Here a screenshot from the final application:25+Here a screenshot of the final application:26 27 .. image:: ../_static/flaskr.png28 :align: center29 :class: screenshot30 :alt: screenshot of the final application31 32 Continue with :ref:`tutorial-folders`.33 33-.. _SQLAlchemy: http://www.sqlalchemy.org/34+.. _SQLAlchemy: https://www.sqlalchemy.org/added:docs/tutorial/packaging.rst+108 added
1+.. _tutorial-packaging:2+3+Step 3: Installing flaskr as a Package4+======================================5+6+Flask is now shipped with built-in support for `Click`_. Click provides7+Flask with enhanced and extensible command line utilities. Later in this8+tutorial you will see exactly how to extend the ``flask`` command line9+interface (CLI).10+11+A useful pattern to manage a Flask application is to install your app12+following the `Python Packaging Guide`_. Presently this involves 13+creating two new files; :file:`setup.py` and :file:`MANIFEST.in` in the 14+projects root directory. You also need to add an :file:`__init__.py` 15+file to make the :file:`flaskr/flaskr` directory a package. After these 16+changes, your code structure should be::17+18+ /flaskr19+ /flaskr20+ __init__.py21+ /static22+ /templates23+ flaskr.py24+ schema.sql25+ setup.py26+ MANIFEST.in27+28+The content of the ``setup.py`` file for ``flaskr`` is:29+30+.. sourcecode:: python31+32+ from setuptools import setup33+34+ setup(35+ name='flaskr',36+ packages=['flaskr'],37+ include_package_data=True,38+ install_requires=[39+ 'flask',40+ ],41+ )42+43+When using setuptools, it is also necessary to specify any special files44+that should be included in your package (in the :file:`MANIFEST.in`).45+In this case, the static and templates directories need to be included,46+as well as the schema. Create the :file:`MANIFEST.in` and add the47+following lines::48+49+ graft flaskr/templates50+ graft flaskr/static51+ include flaskr/schema.sql52+53+To simplify locating the application, add the following import statement 54+into this file, :file:`flaskr/__init__.py`:55+56+.. sourcecode:: python57+58+ from .flaskr import app59+60+This import statement brings the application instance into the top-level 61+of the application package. When it is time to run the application, the 62+Flask development server needs the location of the app instance. This 63+import statement simplifies the location process. Without it the export 64+statement a few steps below would need to be 65+``export FLASK_APP=flaskr.flaskr``.66+67+At this point you should be able to install the application. As usual, it68+is recommended to install your Flask application within a `virtualenv`_.69+With that said, go ahead and install the application with::70+71+ pip install --editable .72+73+The above installation command assumes that it is run within the projects 74+root directory, `flaskr/`. The `editable` flag allows editing 75+source code without having to reinstall the Flask app each time you make 76+changes. The flaskr app is now installed in your virtualenv (see output 77+of ``pip freeze``).78+79+With that out of the way, you should be able to start up the application.80+Do this with the following commands::81+82+ export FLASK_APP=flaskr83+ export FLASK_DEBUG=true84+ flask run85+86+(In case you are on Windows you need to use `set` instead of `export`).87+The :envvar:`FLASK_DEBUG` flag enables or disables the interactive debugger.88+*Never leave debug mode activated in a production system*, because it will89+allow users to execute code on the server!90+91+You will see a message telling you that server has started along with92+the address at which you can access it.93+94+When you head over to the server in your browser, you will get a 404 error95+because we don't have any views yet. That will be addressed a little later,96+but first, you should get the database working.97+98+.. admonition:: Externally Visible Server99+100+ Want your server to be publicly available? Check out the101+ :ref:`externally visible server <public-server>` section for more102+ information.103+104+Continue with :ref:`tutorial-dbcon`.105+106+.. _Click: http://click.pocoo.org107+.. _Python Packaging Guide: https://packaging.python.org108+.. _virtualenv: https://virtualenv.pypa.iomodified:docs/tutorial/schema.rst+7 added-7 removed
1 unmodified line2 3 Step 1: Database Schema4 =======================5 6-First we want to create the database schema. Only a single table is needed7-for this application and we only want to support SQLite so creating the8-database schema is quite easy. Just put the following contents into a file9-named `schema.sql` in the just created `flaskr` folder:6+In this step, you will create the database schema. Only a single table is7+needed for this application and it will only support SQLite. All you need to do8+is put the following contents into a file named :file:`schema.sql` in the9+:file:`flaskr/flaskr` folder:10 11 .. sourcecode:: sql12 13 drop table if exists entries;14 create table entries (15 id integer primary key autoincrement,16 title text not null,17- text text not null17+ 'text' text not null18 );19 20-This schema consists of a single table called `entries` and each row in21-this table has an `id`, a `title` and a `text`. The `id` is an20+This schema consists of a single table called ``entries``. Each row in21+this table has an ``id``, a ``title``, and a ``text``. The ``id`` is an22 automatically incrementing integer and a primary key, the other two are23 strings that must not be null.24 25 Continue with :ref:`tutorial-setup`.modified:docs/tutorial/setup.rst+41 added-63 removed
1 unmodified line2 3 Step 2: Application Setup Code4 ==============================5 6-Now that we have the schema in place we can create the application module.7-Let's call it flaskr.py. We will place this file inside the flask folder.8-We will begin by adding the imports we need and by adding the config9-section. For small applications, it is possible to drop the configuration10-directly into the module, and this is what we will be doing here. However11-a cleaner solution would be to create a separate `.ini` or `.py` file and12-load that or import the values from there.6+Now that the schema is in place, you can create the application module,7+:file:`flaskr.py`. This file should be placed inside of the8+:file:`flaskr/flaskr` folder. The first several lines of code in the9+application module are the needed import statements. After that there will be a10+few lines of configuration code. For small applications like ``flaskr``, it is11+possible to drop the configuration directly into the module. However, a cleaner12+solution is to create a separate ``.ini`` or ``.py`` file, load that, and13+import the values from there.14 14-First we add the imports in `flaskr.py`::15+Here are the import statements (in :file:`flaskr.py`)::16 17 # all the imports18 import os19 import sqlite320 from flask import Flask, request, session, g, redirect, url_for, abort, \21 render_template, flash22 22-Next we can create our actual application and initialize it with the23-config from the same file, in `flaskr.py`::23+The next couple lines will create the actual application instance and24+initialize it with the config from the same file in :file:`flaskr.py`:25 25- # create our little application :)26- app = Flask(__name__)27- app.config.from_object(__name__)26+.. sourcecode:: python27 28+ app = Flask(__name__) # create the application instance :)29+ app.config.from_object(__name__) # load config from this file , flaskr.py30+31 # Load default config and override config from an environment variable32 app.config.update(dict(33 DATABASE=os.path.join(app.root_path, 'flaskr.db'),32- DEBUG=True,34 SECRET_KEY='development key',35 USERNAME='admin',36 PASSWORD='default'37 ))38 app.config.from_envvar('FLASKR_SETTINGS', silent=True)39 39-The :class:`~flask.Config` object works similar to a dictionary so we40-can update it with new values.40+The :class:`~flask.Config` object works similarly to a dictionary, so it can be41+updated with new values.42 43 .. admonition:: Database Path44 45 Operating systems know the concept of a current working directory 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.49 50 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.54 54- For a real-work application it's recommended to use55+ For a real-world application, it's recommended to use56 :ref:`instance-folders` instead.57 57-Usually, it is a good idea to load a separate, environment specific58-configuration file. Flask allows you to import multiple configurations and it 59-will use the setting defined in the last import. This enables robust 60-configuration setups. :meth:`~flask.Config.from_envvar` can help achieve this. 61- 62- app.config.from_envvar('FLASKR_SETTINGS', silent=True)58+Usually, it is a good idea to load a separate, environment-specific59+configuration file. Flask allows you to import multiple configurations and it60+will use the setting defined in the last import. This enables robust61+configuration setups. :meth:`~flask.Config.from_envvar` can help achieve this.62 63+.. sourcecode:: python64+65+ app.config.from_envvar('FLASKR_SETTINGS', silent=True)66+64-Simply define the environment variable :envvar:`FLASKR_SETTINGS` that points to 65-a config file to be loaded. The silent switch just tells Flask to not complain 67+Simply define the environment variable :envvar:`FLASKR_SETTINGS` that points to68+a config file to be loaded. The silent switch just tells Flask to not complain69 if no such environment key is set.70 68-In addition to that you can use the :meth:`~flask.Config.from_object`71+In addition to that, you can use the :meth:`~flask.Config.from_object`72 method on the config object and provide it with an import name of a70-module. Flask will the initialize the variable from that module. Note71-that in all cases only variable names that are uppercase are considered.73+module. Flask will then initialize the variable from that module. Note74+that in all cases, only variable names that are uppercase are considered.75 76 The ``SECRET_KEY`` is needed to keep the client-side sessions secure.74-Choose that key wisely and as hard to guess and complex as possible. The75-debug flag enables or disables the interactive debugger. *Never leave76-debug mode activated in a production system*, because it will allow users to77-execute code on the server!77+Choose that key wisely and as hard to guess and complex as possible.78 79-We will also add a method that allows for easily connecting to the79+Lastly, you will add a method that allows for easy connections to the80 specified database. This can be used to open a connection on request and81 also from the interactive Python shell or a script. This will come in82-handy later. We create a simple database connection through SQLite and82+handy later. You can create a simple database connection through SQLite and83 then tell it to use the :class:`sqlite3.Row` object to represent rows.84-This allows us to treat the rows as if they were dictionaries instead of84+This allows the rows to be treated as if they were dictionaries instead of85 tuples.86 87-::87+.. sourcecode:: python88 89 def connect_db():90 """Connects to the specific database."""91 rv = sqlite3.connect(app.config['DATABASE'])92 rv.row_factory = sqlite3.Row93 return rv94 95-Finally we just add a line to the bottom of the file that fires up the96-server if we want to run that file as a standalone application::95+In the next section you will see how to run the application.96 98- if __name__ == '__main__':99- app.run()100-101-With that out of the way you should be able to start up the application102-without problems. Do this with the following command::103-104- python flaskr.py105-106-You will see a message telling you that server has started along with107-the address at which you can access it.108-109-When you head over to the server in your browser you will get an 404110-page not found error because we don't have any views yet. But we will111-focus on that a little later. First we should get the database working.112-113-.. admonition:: Externally Visible Server114-115- Want your server to be publicly available? Check out the116- :ref:`externally visible server <public-server>` section for more117- information.118-119-Continue with :ref:`tutorial-dbcon`.97+Continue with :ref:`tutorial-packaging`.modified:docs/tutorial/templates.rst+15 added-14 removed
1 .. _tutorial-templates:2 3-Step 6: The Templates3+Step 7: The Templates4 =====================5 6-Now we should start working on the templates. If we request the URLs now7-we would only get an exception that Flask cannot find the templates. The8-templates are using `Jinja2`_ syntax and have autoescaping enabled by6+Now it is time to start working on the templates. As you may have7+noticed, if you make requests with the app running, you will get8+an exception that Flask cannot find the templates. The templates9+are using `Jinja2`_ syntax and have autoescaping enabled by10 default. This means that unless you mark a value in the code with11 :class:`~flask.Markup` or with the ``|safe`` filter in the template,12 Jinja2 will ensure that special characters such as ``<`` or ``>`` are13 escaped with their XML equivalents.14 15 We are also using template inheritance which makes it possible to reuse16 the layout of the website in all pages.17 17-Put the following templates into the `templates` folder:18+Put the following templates into the :file:`templates` folder:19 19-.. _Jinja2: http://jinja.pocoo.org/2/documentation/templates20+.. _Jinja2: http://jinja.pocoo.org/docs/templates21 22 layout.html23 -----------24 30 unmodified lines55 56 show_entries.html57 -----------------58 58-This template extends the `layout.html` template from above to display the59-messages. Note that the `for` loop iterates over the messages we passed60-in with the :func:`~flask.render_template` function. We also tell the61-form to submit to your `add_entry` function and use `POST` as `HTTP`62-method:59+This template extends the :file:`layout.html` template from above to display the60+messages. Note that the ``for`` loop iterates over the messages we passed61+in with the :func:`~flask.render_template` function. Notice that the form is62+configured to submit to the `add_entry` view function and use ``POST`` as63+HTTP method:64 65 .. sourcecode:: html+jinja66 67 {% extends "layout.html" %}10 unmodified lines78 </form>79 {% endif %}80 <ul class=entries>81 {% for entry in entries %}81- <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}82+ <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}</li>83 {% else %}83- <li><em>Unbelievable. No entries here so far</em>84+ <li><em>Unbelievable. No entries here so far</em></li>85 {% endfor %}86 </ul>87 {% endblock %}88 89 login.html90 ----------91 91-Finally the login template which basically just displays a form to allow92+This is the login template, which basically just displays a form to allow93 the user to login:94 95 .. sourcecode:: html+jinja96 16 unmodified linesmodified:docs/tutorial/testing.rst+87 added-1 removed
4 unmodified lines5 6 Now that you have finished the application and everything works as7 expected, it's probably not a bad idea to add automated tests to simplify8 modifications in the future. The application above is used as a basic9-example of how to perform unittesting in the :ref:`testing` section of the9+example of how to perform unit testing in the :ref:`testing` section of the10 documentation. Go there to see how easy it is to test Flask applications.11+12+Adding tests to flaskr13+----------------------14+15+Assuming you have seen the :ref:`testing` section and have either written16+your own tests for ``flaskr`` or have followed along with the examples17+provided, you might be wondering about ways to organize the project.18+19+One possible and recommended project structure is::20+21+ flaskr/22+ flaskr/23+ __init__.py24+ static/25+ templates/26+ tests/27+ test_flaskr.py28+ setup.py29+ MANIFEST.in30+31+For now go ahead a create the :file:`tests/` directory as well as the 32+:file:`test_flaskr.py` file.33+34+Running the tests35+-----------------36+37+At this point you can run the tests. Here ``pytest`` will be used. 38+39+.. note:: Make sure that ``pytest`` is installed in the same virtualenv 40+ as flaskr. Otherwise ``pytest`` test will not be able to import the 41+ required components to test the application::42+43+ pip install -e .44+ pip install pytest 45+46+Run and watch the tests pass, within the top-level :file:`flaskr/` 47+directory as::48+49+ pytest50+51+Testing + setuptools52+--------------------53+54+One way to handle testing is to integrate it with ``setuptools``. Here55+that requires adding a couple of lines to the :file:`setup.py` file and56+creating a new file :file:`setup.cfg`. One benefit of running the tests 57+this way is that you do not have to install ``pytest``. Go ahead and 58+update the :file:`setup.py` file to contain::59+60+ from setuptools import setup61+62+ setup(63+ name='flaskr',64+ packages=['flaskr'],65+ include_package_data=True,66+ install_requires=[67+ 'flask',68+ ],69+ setup_requires=[70+ 'pytest-runner',71+ ],72+ tests_require=[73+ 'pytest',74+ ],75+ )76+77+Now create :file:`setup.cfg` in the project root (alongside78+:file:`setup.py`)::79+80+ [aliases]81+ test=pytest82+83+Now you can run::84+85+ python setup.py test86+87+This calls on the alias created in :file:`setup.cfg` which in turn runs88+``pytest`` via ``pytest-runner``, as the :file:`setup.py` script has89+been called. (Recall the `setup_requires` argument in :file:`setup.py`)90+Following the standard rules of test-discovery your tests will be91+found, run, and hopefully pass.92+93+This is one possible way to run and manage testing. Here ``pytest`` is94+used, but there are other options such as ``nose``. Integrating testing95+with ``setuptools`` is convenient because it is not necessary to actually96+download ``pytest`` or any other testing framework one might use.modified:docs/tutorial/views.rst+35 added-16 removed
1 .. _tutorial-views:2 3-Step 5: The View Functions3+Step 6: The View Functions4 ==========================5 6-Now that the database connections are working we can start writing the7-view functions. We will need four of them:6+Now that the database connections are working, you can start writing the7+view functions. You will need four of them:8 9 Show Entries10 ------------11 12 This view shows all the entries stored in the database. It listens on the13 root of the application and will select title and text from the database.14 The one with the highest id (the newest entry) will be on top. The rows15-returned from the cursor look a bit like tuples because we are using15+returned from the cursor look a bit like dictionaries because we are using16 the :class:`sqlite3.Row` row factory.17 18-The view function will pass the entries as dicts to the19-`show_entries.html` template and return the rendered one::18+The view function will pass the entries to the :file:`show_entries.html`19+template and return the rendered one::20 21 @app.route('/')22 def show_entries():23 db = get_db()4 unmodified lines28 Add New Entry29 -------------30 31 This view lets the user add new entries if they are logged in. This only32-responds to `POST` requests, the actual form is shown on the33-`show_entries` page. If everything worked out well we will32+responds 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 and35 redirect back to the `show_entries` page::36 37 @app.route('/add', methods=['POST'])6 unmodified lines44 db.commit()45 flash('New entry was successfully posted')46 return redirect(url_for('show_entries'))47 48-Note that we check that the user is logged in here (the `logged_in` key is49-present in the session and `True`).48+Note that this view checks that the user is logged in (that is, if the49+`logged_in` key is present in the session and ``True``).50 51 .. admonition:: Security Note52 53 Be sure to use question marks when building SQL statements, as done in the5 unmodified lines59 ----------------60 61 These functions are used to sign the user in and out. Login checks the62 username and password against the ones from the configuration and sets the63-`logged_in` key in the session. If the user logged in successfully, that64-key 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, that64+key is set to ``True``, and the user is redirected back to the `show_entries`65 page. In addition, a message is flashed that informs the user that he or66 she was logged in successfully. If an error occurred, the template is67 notified about that, and the user is asked again::68 10 unmodified lines79 flash('You were logged in')80 return redirect(url_for('show_entries'))81 return render_template('login.html', error=error)82 83-The logout function, on the other hand, removes that key from the session84-again. We use a neat trick here: if you use the :meth:`~dict.pop` method83+The `logout` function, on the other hand, removes that key from the session84+again. There is a neat trick here: if you use the :meth:`~dict.pop` method85 of the dict and pass a second parameter to it (the default), the method86 will delete the key from the dictionary if present or do nothing when that87-key is not in there. This is helpful because now we don't have to check88-if the user was logged in.87+key is not in there. This is helpful because now it is not necessary to88+check if the user was logged in.89 90 ::91 92 @app.route('/logout')1 unmodified line94 session.pop('logged_in', None)95 flash('You were logged out')96 return redirect(url_for('show_entries'))97 98+.. admonition:: Security Note99+100+ Passwords should never be stored in plain text in a production101+ system. This tutorial uses plain text passwords for simplicity. If you102+ plan to release a project based off this tutorial out into the world,103+ passwords should be both `hashed and salted`_ before being stored in a104+ database or file.105+106+ Fortunately, there are Flask extensions for the purpose of107+ hashing passwords and verifying passwords against hashes, so adding108+ this functionality is fairly straight forward. There are also109+ many general python libraries that can be used for hashing.110+111+ You can find a list of recommended Flask extensions112+ `here <http://flask.pocoo.org/extensions/>`_113+114+115 Continue with :ref:`tutorial-templates`.116+117+.. _hashed and salted: https://blog.codinghorror.com/youre-probably-storing-passwords-incorrectly/modified:docs/advanced_foreword.rst+5 added-19 removed
6 unmodified lines7 ----------------------8 9 One of the design decisions in Flask was that simple tasks should be simple;10 they should not take a lot of code and yet they should not limit you. Because11-of that, Flask has few design choices that some people might find surprising or11+of that, Flask has a few design choices that some people might find surprising or12 unorthodox. For example, Flask uses thread-local objects internally so that you13 don’t have to pass objects around from function to function within a request in14 order to stay threadsafe. This approach is convenient, but requires a valid15 request context for dependency injection or when attempting to reuse code which29 unmodified lines45 46 Flask is no different from any other framework in that you the developer must47 build with caution, watching for exploits when building to your requirements.48 49-The Status of Python 350-----------------------49+Python 3 Support in Flask50+-------------------------51 52-Currently the Python community is in the process of improving libraries to53-support the new iteration of the Python programming language. While the54-situation is greatly improving there are still some issues that make it55-hard for users to switch over to Python 3 just now. These problems are56-partially caused by changes in the language that went unreviewed for too57-long, partially also because we have not quite worked out how the lower-58-level API should change to account for the Unicode differences in Python 3.52+Flask, its dependencies, and most Flask extensions all support Python 3.53+If you want to use Flask with Python 3 have a look at the :ref:`python3-support` page.54 60-We strongly recommend using Python 2.6 and 2.7 with activated Python 361-warnings during development. If you plan on upgrading to Python 3 in the62-near future we strongly recommend that you read `How to write forwards63-compatible Python code64-<http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/>`_.65-66-If you do want to dive into Python 3 already have a look at the67-:ref:`python3-support` page.68-55 Continue to :ref:`installation` or the :ref:`quickstart`.modified:docs/api.rst+190 added-110 removed
28 unmodified lines29 ---------------------30 31 .. autoclass:: Request32 :members:33+ :inherited-members:34 34- .. attribute:: form35-36- A :class:`~werkzeug.datastructures.MultiDict` with the parsed form data from `POST`37- or `PUT` requests. Please keep in mind that file uploads will not38- end up here, but instead in the :attr:`files` attribute.39-40- .. attribute:: args41-42- A :class:`~werkzeug.datastructures.MultiDict` with the parsed contents of the query43- string. (The part in the URL after the question mark).44-45- .. attribute:: values46-47- A :class:`~werkzeug.datastructures.CombinedMultiDict` with the contents of both48- :attr:`form` and :attr:`args`.49-50- .. attribute:: cookies51-52- A :class:`dict` with the contents of all cookies transmitted with53- the request.54-55- .. attribute:: stream56-57- If the incoming form data was not encoded with a known mimetype58- the data is stored unmodified in this stream for consumption. Most59- of the time it is a better idea to use :attr:`data` which will give60- you that data as a string. The stream only returns the data once.61-62- .. attribute:: headers63-64- The incoming request headers as a dictionary like object.65-66- .. attribute:: data67-68- Contains the incoming request data as string in case it came with69- a mimetype Flask does not handle.70-71- .. attribute:: files72-73- A :class:`~werkzeug.datastructures.MultiDict` with files uploaded as part of a74- `POST` or `PUT` request. Each file is stored as75- :class:`~werkzeug.datastructures.FileStorage` object. It basically behaves like a76- standard file object you know from Python, with the difference that77- it also has a :meth:`~werkzeug.datastructures.FileStorage.save` function that can78- store the file on the filesystem.79-35 .. attribute:: environ36 37 The underlying WSGI environment.38 84- .. attribute:: method85-86- The current request method (``POST``, ``GET`` etc.)87-39 .. attribute:: path40+ .. attribute:: full_path41 .. attribute:: script_root42 .. attribute:: url43 .. attribute:: base_url44 .. attribute:: url_root45 94- 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::49 50 http://www.example.com/myapplication51 99- And a user requests the following URL::52+ And a user requests the following URI::53 101- http://www.example.com/myapplication/page.html?x=y54+ http://www.example.com/myapplication/%CF%80/page.html?x=y55 56 In this case the values of the above mentioned attributes would be57 the following:58 59 ============= ======================================================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 ============= ======================================================67 114- .. attribute:: is_xhr68 116- `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:: request70 122-.. class:: request123-71 To access incoming request data, you can use the global `request`72 object. Flask parses incoming request data for you and gives you73 access to it through that global object. Internally Flask makes74 sure that you always get the correct data for the active thread if you13 unmodified lines88 :members: set_cookie, data, mimetype89 90 .. attribute:: headers91 145- A :class:`Headers` object representing the response headers.92+ A :class:`~werkzeug.datastructures.Headers` object representing the response headers.93 94 .. attribute:: status95 96 A string with a response status.25 unmodified lines122 The following attributes are interesting:123 124 .. attribute:: new125 179- `True` if the session is new, `False` otherwise.126+ ``True`` if the session is new, ``False`` otherwise.127 128 .. attribute:: modified129 183- `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::134 135 # this change is not picked up because a mutable object (here136 # a list) is changed.137 session['objects'].append(42)1 unmodified line139 session.modified = True140 141 .. attribute:: permanent142 196- 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.147 148 149 Session Interface73 unmodified lines223 is especially useful when combined with the :ref:`faking-resources`224 pattern for testing.225 226 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::229 230 user = getattr(flask.g, 'user', None)231 user = flask.g.get('user', None)232 233 It's now also possible to use the ``in`` operator on it to see if an234 attribute is defined and it yields all keys on iteration.235 236+ As of 0.11 you can use :meth:`pop` and :meth:`setdefault` in the same237+ way you would use them on a dictionary.238+239 This is a proxy. See :ref:`notes-on-proxies` for more information.240 241 242 Useful Functions and Classes16 unmodified lines259 .. autofunction:: has_app_context260 261 .. autofunction:: url_for262 313-.. function:: abort(code)263+.. autofunction:: abort264 315- 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)``.318-319- :param code: the HTTP error code.320-265 .. autofunction:: redirect266 267 .. autofunction:: make_response268 22 unmodified lines291 292 .. module:: flask.json293 294 Flask uses ``simplejson`` for the JSON implementation. Since simplejson351-is provided both by the standard library as well as extension Flask will295+is provided by both the standard library as well as extension, Flask will296 try simplejson first and then fall back to the stdlib json module. On top297 of that it will delegate access to the current application's JSON encoders298 and decoders for easier customization.299 17 unmodified lines317 will have that method called and then the return value is serialized318 as string.319 320 The :func:`~htmlsafe_dumps` function of this json module is also available377-as filter called ``|tojson`` in Jinja2. Note that inside `script`321+as filter called ``|tojson`` in Jinja2. Note that inside ``script``322 tags no escaping must take place, so make sure to disable escaping379-with ``|safe`` if you intend to use it inside `script` tags unless323+with ``|safe`` if you intend to use it inside ``script`` tags unless324 you are using Flask 0.10 which implies that:325 326 .. sourcecode:: html+jinja327 120 unmodified lines448 449 .. autoclass:: flask.blueprints.BlueprintSetupState450 :members:451 452+.. _core-signals-list:453+454 Signals455 -------456 511-.. when modifying this list, also update the one in signals.rst512-457 .. versionadded:: 0.6458 515-.. data:: signals_available459+.. data:: signals.signals_available460 517- `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.463 464+The following signals exist in Flask:465+466 .. data:: template_rendered467 468 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`).471 472+ Example subscriber::473+474+ 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)478+479+ from flask import template_rendered480+ template_rendered.connect(log_template_renders, app)481+482+.. data:: flask.before_render_template483+ :noindex:484+485+ 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`).488+489+ Example subscriber::490+491+ 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)495+496+ from flask import before_render_template497+ before_render_template.connect(log_template_renders, app)498+499 .. data:: request_started500 528- 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`.505 506+ Example subscriber::507+508+ def log_request(sender, **extra):509+ sender.logger.debug('Request context is set up')510+511+ from flask import request_started512+ request_started.connect(log_request, app)513+514 .. data:: request_finished515 516 This signal is sent right before the response is sent to the client.517 It is passed the response to be sent named `response`.518 519+ Example subscriber::520+521+ def log_response(sender, response, **extra):522+ sender.logger.debug('Request context is about to close down. '523+ 'Response: %s', response)524+525+ from flask import request_finished526+ request_finished.connect(log_response, app)527+528 .. data:: got_request_exception529 530 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`.534 535+ Example subscriber::536+537+ def log_exception(sender, exception, **extra):538+ sender.logger.debug('Got exception during processing: %s', exception)539+540+ from flask import got_request_exception541+ got_request_exception.connect(log_exception, app)542+543 .. data:: request_tearing_down544 547- 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.549 551- .. versionchanged:: 0.9552- The `exc` parameter was added.550+ Example subscriber::551 552+ def close_db_connection(sender, **extra):553+ session.close()554+555+ from flask import request_tearing_down556+ request_tearing_down.connect(close_db_connection, app)557+558+ 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.561+562 .. data:: appcontext_tearing_down563 556- 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.568 569+ Example subscriber::570+571+ def close_db_connection(sender, **extra):572+ session.close()573+574+ from flask import appcontext_tearing_down575+ appcontext_tearing_down.connect(close_db_connection, app)576+577+ This will also be passed an `exc` keyword argument that has a reference578+ to the exception that caused the teardown if there was one.579+580 .. data:: appcontext_pushed581 582 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.586 587+ Example usage::588+589+ from contextlib import contextmanager590+ from flask import appcontext_pushed591+592+ @contextmanager593+ def user_set(app, user):594+ def handler(sender, **kwargs):595+ g.user = user596+ with appcontext_pushed.connected_to(handler, app):597+ yield598+599+ And in the testcode::600+601+ 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'606+607 .. versionadded:: 0.10608 609 .. data:: appcontext_popped610 2 unmodified lines613 :data:`appcontext_tearing_down` signal.614 615 .. versionadded:: 0.10616 617+618 .. data:: message_flashed619 620 This signal is sent when the application is flashing a message. The621 messages is sent as `message` keyword argument and the category as622 `category`.623 582- .. versionadded:: 0.10624+ Example subscriber::625 584-.. currentmodule:: None626+ recorded = []627+ def record(sender, message, category, **extra):628+ recorded.append((message, category))629 586-.. class:: flask.signals.Namespace630+ from flask import message_flashed631+ message_flashed.connect(record, app)632 633+ .. versionadded:: 0.10634+635+.. class:: signals.Namespace636+637 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 lines645 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.648 600-.. _blinker: http://pypi.python.org/pypi/blinker649 650+.. _blinker: https://pypi.python.org/pypi/blinker651+652+653 Class-Based Views654 -----------------655 656 .. versionadded:: 0.731 unmodified lines688 `string` accepts any text without a slash (the default)689 `int` accepts integers690 `float` like `int` but for floating point values691 `path` like the default but also accepts slashes692+`any` matches one of the items provided693+`uuid` accepts UUID strings694 =========== ===============================================695 696+Custom converters can be defined using :attr:`flask.Flask.url_map`.697+698 Here are some examples::699 700 @app.route('/')701 def index():54 unmodified lines756 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 lines779 will be prefixed with the name of the blueprint by default which780 cannot be customized from the function itself.781 782 - `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.786 787 - `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.792 793 - `required_methods`: if this attribute is set, Flask will always add794 these methods when registering a URL rule even if the methods were12 unmodified lines807 app.add_url_rule('/', index)808 809 .. versionadded:: 0.8810 The `provide_automatic_options` functionality was added.811+812+Command Line Interface813+----------------------814+815+.. currentmodule:: flask.cli816+817+.. autoclass:: FlaskGroup818+ :members:819+820+.. autoclass:: AppGroup821+ :members:822+823+.. autoclass:: ScriptInfo824+ :members:825+826+.. autofunction:: with_appcontext827+828+.. autofunction:: pass_script_info829+830+ Marks a function so that an instance of :class:`ScriptInfo` is passed831+ as first argument to the click callback.832+833+.. autodata:: run_command834+835+.. autodata:: shell_commandmodified:docs/appcontext.rst+19 added-14 removed
24 unmodified lines25 - any code can get hold of these objects at any time.26 27 There is a third state which is sitting in between a little bit.28 Sometimes you are dealing with an application in a way that is similar to29-how you interact with applications during request handling just that there30-is no request active. Consider for instance that you're sitting in an29+how you interact with applications during request handling; just that there30+is no request active. Consider, for instance, that you're sitting in an31 interactive Python shell and interacting with the application, or a32 command line application.33 34 The application context is what powers the :data:`~flask.current_app`2 unmodified lines37 Purpose of the Application Context38 ----------------------------------39 40 The main reason for the application's context existence is that in the41-past a bunch of functionality was attached to the request context in lack42-of a better solution. Since one of the pillar's of Flask's design is that41+past a bunch of functionality was attached to the request context for lack42+of a better solution. Since one of the pillars of Flask's design is that43 you can have more than one application in the same Python process.44 45 So how does the code find the “right” application? In the past we46 recommended passing applications around explicitly, but that caused issues47 with libraries that were not designed with that in mind.48 49 A common workaround for that problem was to use the50 :data:`~flask.current_app` proxy later on, which was bound to the current51-request's application reference. Since however creating such a request52-context is an unnecessarily expensive operation in case there is no53-request around, the application context was introduced.51+request's application reference. Since creating such a request context is52+an unnecessarily expensive operation in case there is no request around,53+the application context was introduced.54 55 Creating an Application Context56 -------------------------------57 58-To make an application context there are two ways. The first one is the59-implicit one: whenever a request context is pushed, an application context60-will be created alongside if this is necessary. As a result of that, you61-can ignore the existence of the application context unless you need it.58+There are two ways to make an application context. The first one is59+implicit: whenever a request context is pushed, an application context60+will be created alongside if this is necessary. As a result, you can61+ignore the existence of the application context unless you need it.62 63 The second way is the explicit way using the64 :meth:`~flask.Flask.app_context` method::65 7 unmodified lines73 The application context is also used by the :func:`~flask.url_for`74 function in case a ``SERVER_NAME`` was configured. This allows you to75 generate URLs even in the absence of a request.76 77+If no request context has been pushed and an application context has78+not been explicitly set, a ``RuntimeError`` will be raised. ::79+80+ RuntimeError: Working outside of application context.81+82 Locality of the Context83 -----------------------84 85 The application context is created and destroyed as necessary. It never9 unmodified lines95 96 Context Usage97 -------------98 94-The context is typically used to cache resources on there that need to be95-created on a per-request or usage case. For instance database connects96-are destined to go there. When storing things on the application context99+The context is typically used to cache resources that need to be created100+on a per-request or usage case. For instance, database connections are101+destined to go there. When storing things on the application context102 unique names should be chosen as this is a place that is shared between103 Flask applications and extensions.104 105 The most common usage is to split resource management into two parts:33 unmodified linesmodified:docs/becomingbig.rst+2 added-2 removed
10 unmodified lines11 Flask started in part to demonstrate how to build your own framework on top of12 existing well-used tools Werkzeug (WSGI) and Jinja (templating), and as it13 developed, it became useful to a wide audience. As you grow your codebase,14 don't just use Flask -- understand it. Read the source. Flask's code is15-written to be read; it's documentation published so you can use its internal15+written to be read; its documentation is published so you can use its internal16 APIs. Flask sticks to documented APIs in upstream libraries, and documents its17 internal utilities so that you can find the hook points needed for your18 project.19 14 unmodified lines34 35 The :class:`~flask.Flask` class has many methods designed for subclassing. You36 can quickly add or customize behavior by subclassing :class:`~flask.Flask` (see37 the linked method docs) and using that subclass wherever you instantiate an38-application class. This works well with :ref:`app-factories`.38+application class. This works well with :ref:`app-factories`. See :doc:`/patterns/subclassing` for an example.39 40 Wrap with middleware.41 ---------------------42 59 unmodified linesmodified:docs/blueprints.rst+55 added-8 removed
1 unmodified line2 3 Modular Applications with Blueprints4 ====================================5 6+.. currentmodule:: flask7+8 .. versionadded:: 0.79 10 Flask uses a concept of *blueprints* for making application components and11 supporting common patterns within an application or across applications.86 unmodified lines98 [<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>,99 <Rule '/<page>' (HEAD, OPTIONS, GET) -> simple_page.show>,100 <Rule '/' (HEAD, OPTIONS, GET) -> simple_page.show>]101 100-The first one is obviously from the application ifself for the static102+The first one is obviously from the application itself for the static103 files. The other two are for the `show` function of the ``simple_page``104 blueprint. As you can see, they are also prefixed with the name of the105 blueprint and separated by a dot (``.``).106 51 unmodified lines158 159 admin = Blueprint('admin', __name__, static_folder='static')160 161 By default the rightmost part of the path is where it is exposed on the160-web. Because the folder is called ``static`` here it will be available at162+web. Because the folder is called :file:`static` here it will be available at163 the location of the blueprint + ``/static``. Say the blueprint is164 registered for ``/admin`` the static folder will be at ``/admin/static``.165 166 The endpoint is named `blueprint_name.static` so you can generate URLs to8 unmodified lines175 the `template_folder` parameter to the :class:`Blueprint` constructor::176 177 admin = Blueprint('admin', __name__, template_folder='templates')178 177-As for static files, the path can be absolute or relative to the blueprint178-resource folder. The template folder is added to the searchpath of179-templates but with a lower priority than the actual application's template180-folder. That way you can easily override templates that a blueprint181-provides in the actual application.179+For static files, the path can be absolute or relative to the blueprint180+resource folder.181 182+The template folder is added to the search path of templates but with a lower183+priority than the actual application's template folder. That way you can184+easily override templates that a blueprint provides in the actual application.185+This also means that if you don't want a blueprint template to be accidentally186+overridden, make sure that no other blueprint or actual application template187+has the same relative path. When multiple blueprints provide the same relative188+template path the first blueprint registered takes precedence over the others.189+190+191 So if you have a blueprint in the folder ``yourapplication/admin`` and you192 want to render the template ``'admin/index.html'`` and you have provided193 ``templates`` as a `template_folder` you will have to create a file like186-this: ``yourapplication/admin/templates/admin/index.html``.194+this: :file:`yourapplication/admin/templates/admin/index.html`. The reason195+for the extra ``admin`` folder is to avoid getting our template overridden196+by a template named ``index.html`` in the actual application template197+folder.198 199+To further reiterate this: if you have a blueprint named ``admin`` and you200+want to render a template called :file:`index.html` which is specific to this201+blueprint, the best idea is to lay out your templates like this::202+203+ yourpackage/204+ blueprints/205+ admin/206+ templates/207+ admin/208+ index.html209+ __init__.py210+211+And then when you want to render the template, use :file:`admin/index.html` as212+the name to look up the template by. If you encounter problems loading213+the correct templates enable the ``EXPLAIN_TEMPLATE_LOADING`` config214+variable which will instruct Flask to print out the steps it goes through215+to locate templates on every ``render_template`` call.216+217 Building URLs218 -------------219 220 If you want to link from one page to another you can use the23 unmodified lines244 @simple_page.errorhandler(404)245 def page_not_found(e):246 return render_template('pages/404.html')247 248+Most errorhandlers will simply work as expected; however, there is a caveat249+concerning handlers for 404 and 405 exceptions. These errorhandlers are only250+invoked from an appropriate ``raise`` statement or a call to ``abort`` in another251+of the blueprint's view functions; they are not invoked by, e.g., an invalid URL252+access. This is because the blueprint does not "own" a certain URL space, so253+the application instance has no way of knowing which blueprint errorhandler it254+should run if given an invalid URL. If you would like to execute different255+handling strategies for these errors based on URL prefixes, they may be defined256+at the application level using the ``request`` proxy object::257+258+ @app.errorhandler(404)259+ @app.errorhandler(405)260+ def _handle_api_error(ex):261+ if request.path.startswith('/api/'):262+ return jsonify_error(ex)263+ else:264+ return ex265+266 More information on error handling see :ref:`errorpages`.added:docs/cli.rst+260 added
1+.. _cli:2+3+Command Line Interface4+======================5+6+.. versionadded:: 0.117+8+.. currentmodule:: flask9+10+One of the nice new features in Flask 0.11 is the built-in integration of11+the `click <http://click.pocoo.org/>`_ command line interface. This12+enables a wide range of new features for the Flask ecosystem and your own13+applications.14+15+Basic Usage16+-----------17+18+After installation of Flask you will now find a :command:`flask` script19+installed into your virtualenv. If you don't want to install Flask or you20+have a special use-case you can also use ``python -m flask`` to accomplish21+exactly the same.22+23+The way this script works is by providing access to all the commands on24+your Flask application's :attr:`Flask.cli` instance as well as some25+built-in commands that are always there. Flask extensions can also26+register more commands there if they desire so.27+28+For the :command:`flask` script to work, an application needs to be29+discovered. This is achieved by exporting the ``FLASK_APP`` environment30+variable. It can be either set to an import path or to a filename of a31+Python module that contains a Flask application.32+33+In that imported file the name of the app needs to be called ``app`` or34+optionally be specified after a colon. For instance35+``mymodule:application`` would tell it to use the `application` object in36+the :file:`mymodule.py` file.37+38+Given a :file:`hello.py` file with the application in it named ``app``39+this is how it can be run.40+41+Environment variables (On Windows use ``set`` instead of ``export``)::42+43+ export FLASK_APP=hello44+ flask run45+46+Or with a filename::47+48+ export FLASK_APP=/path/to/hello.py49+ flask run50+51+Virtualenv Integration52+----------------------53+54+If you are constantly working with a virtualenv you can also put the55+``export FLASK_APP`` into your ``activate`` script by adding it to the56+bottom of the file. That way every time you activate your virtualenv you57+automatically also activate the correct application name.58+59+Edit the activate script for the shell you use. For example:60+61+Unix Bash: ``venv/bin/activate``::62+63+ FLASK_APP=hello64+ export FLASK_APP65+66+Windows CMD.exe: ``venv\Scripts\activate.bat``::67+68+ set "FLASK_APP=hello"69+ :END70+71+Debug Flag72+----------73+74+The :command:`flask` script can also be instructed to enable the debug75+mode of the application automatically by exporting ``FLASK_DEBUG``. If76+set to ``1`` debug is enabled or ``0`` disables it::77+78+ export FLASK_DEBUG=179+80+Running a Shell81+---------------82+83+To run an interactive Python shell you can use the ``shell`` command::84+85+ flask shell86+87+This will start up an interactive Python shell, setup the correct88+application context and setup the local variables in the shell. This is89+done by invoking the :meth:`Flask.make_shell_context` method of the90+application. By default you have access to your ``app`` and :data:`g`.91+92+Custom Commands93+---------------94+95+If you want to add more commands to the shell script you can do this96+easily. Flask uses `click`_ for the command interface which makes97+creating custom commands very easy. For instance if you want a shell98+command to initialize the database you can do this::99+100+ import click101+ from flask import Flask102+103+ app = Flask(__name__)104+105+ @app.cli.command()106+ def initdb():107+ """Initialize the database."""108+ click.echo('Init the db')109+110+The command will then show up on the command line::111+112+ $ flask initdb113+ Init the db114+115+Application Context116+-------------------117+118+Most commands operate on the application so it makes a lot of sense if119+they have the application context setup. Because of this, if you register120+a callback on ``app.cli`` with the :meth:`~flask.cli.AppGroup.command` the121+callback will automatically be wrapped through :func:`cli.with_appcontext`122+which informs the cli system to ensure that an application context is set123+up. This behavior is not available if a command is added later with124+:func:`~click.Group.add_command` or through other means.125+126+It can also be disabled by passing ``with_appcontext=False`` to the127+decorator::128+129+ @app.cli.command(with_appcontext=False)130+ def example():131+ pass132+133+Factory Functions134+-----------------135+136+In case you are using factory functions to create your application (see137+:ref:`app-factories`) you will discover that the :command:`flask` command138+cannot work with them directly. Flask won't be able to figure out how to139+instantiate your application properly by itself. Because of this reason140+the recommendation is to create a separate file that instantiates141+applications. This is not the only way to make this work. Another is the142+:ref:`custom-scripts` support.143+144+For instance if you have a factory function that creates an application145+from a filename you could make a separate file that creates such an146+application from an environment variable.147+148+This could be a file named :file:`autoapp.py` with these contents::149+150+ import os151+ from yourapplication import create_app152+ app = create_app(os.environ['YOURAPPLICATION_CONFIG'])153+154+Once this has happened you can make the :command:`flask` command automatically155+pick it up::156+157+ export YOURAPPLICATION_CONFIG=/path/to/config.cfg158+ export FLASK_APP=/path/to/autoapp.py159+160+From this point onwards :command:`flask` will find your application.161+162+.. _custom-scripts:163+164+Custom Scripts165+--------------166+167+While the most common way is to use the :command:`flask` command, you can168+also make your own "driver scripts". Since Flask uses click for the169+scripts there is no reason you cannot hook these scripts into any click170+application. There is one big caveat and that is, that commands171+registered to :attr:`Flask.cli` will expect to be (indirectly at least)172+launched from a :class:`flask.cli.FlaskGroup` click group. This is173+necessary so that the commands know which Flask application they have to174+work with.175+176+To understand why you might want custom scripts you need to understand how177+click finds and executes the Flask application. If you use the178+:command:`flask` script you specify the application to work with on the179+command line or environment variable as an import name. This is simple180+but it has some limitations. Primarily it does not work with application181+factory functions (see :ref:`app-factories`).182+183+With a custom script you don't have this problem as you can fully184+customize how the application will be created. This is very useful if you185+write reusable applications that you want to ship to users and they should186+be presented with a custom management script.187+188+To explain all of this, here is an example :file:`manage.py` script that189+manages a hypothetical wiki application. We will go through the details190+afterwards::191+192+ import os193+ import click194+ from flask.cli import FlaskGroup195+196+ def create_wiki_app(info):197+ from yourwiki import create_app198+ return create_app(199+ config=os.environ.get('WIKI_CONFIG', 'wikiconfig.py'))200+201+ @click.group(cls=FlaskGroup, create_app=create_wiki_app)202+ def cli():203+ """This is a management script for the wiki application."""204+205+ if __name__ == '__main__':206+ cli()207+208+That's a lot of code for not much, so let's go through all parts step by209+step.210+211+1. First we import the ``click`` library as well as the click extensions212+ from the ``flask.cli`` package. Primarily we are here interested213+ in the :class:`~flask.cli.FlaskGroup` click group.214+2. 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.220+3. Next step is to create a :class:`FlaskGroup`. In this case we just221+ make an empty function with a help doc string that just does nothing222+ and then pass the ``create_wiki_app`` function as a factory function.223+224+ Whenever click now needs to operate on a Flask application it will225+ call that function with the script info and ask for it to be created.226+4. All is rounded up by invoking the script.227+228+CLI Plugins229+-----------230+231+Flask extensions can always patch the :attr:`Flask.cli` instance with more232+commands if they want. However there is a second way to add CLI plugins233+to Flask which is through ``setuptools``. If you make a Python package that234+should export a Flask command line plugin you can ship a :file:`setup.py` file235+that declares an entrypoint that points to a click command:236+237+Example :file:`setup.py`::238+239+ from setuptools import setup240+241+ setup(242+ name='flask-my-extension',243+ ...244+ entry_points='''245+ [flask.commands]246+ my-command=mypackage.commands:cli247+ ''',248+ )249+250+Inside :file:`mypackage/commands.py` you can then export a Click object::251+252+ import click253+254+ @click.command()255+ def cli():256+ """This is an example command."""257+258+Once that package is installed in the same virtualenv as Flask itself you259+can run ``flask my-command`` to invoke your command. This is useful to260+provide extra functionality that Flask itself cannot ship.modified:docs/conf.py+87 added-46 removed
8 unmodified lines9 # autogenerated file.10 #11 # All configuration values have a default; values that are commented out12 # serve to show the default.13+from __future__ import print_function14+import os15+import sys16+import pkg_resources17+import time18+import datetime19 14-import sys, os20+BUILD_DATE = datetime.datetime.utcfromtimestamp(int(os.environ.get('SOURCE_DATE_EPOCH', time.time())))21 22 # If extensions (or modules to document with autodoc) are in another directory,23 # add these directories to sys.path here. If the directory is relative to the24 # documentation root, use os.path.abspath to make it absolute, like shown here.19-sys.path.append(os.path.abspath('_themes'))20-sys.path.append(os.path.abspath('.'))25+sys.path.append(os.path.join(os.path.dirname(__file__), '_themes'))26+sys.path.append(os.path.dirname(__file__))27 28 # -- General configuration -----------------------------------------------------29 30 # If your documentation needs a minimal Sphinx version, state it here.31 #needs_sphinx = '1.0'32 33 # Add any Sphinx extension module names here, as strings. They can be extensions34 # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.35+extensions = [36+ 'sphinx.ext.autodoc',29-extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx',30- 'flaskdocext']37+ 'sphinx.ext.intersphinx',38+ 'flaskdocext'39+]40 41+try:42+ __import__('sphinxcontrib.log_cabinet')43+except ImportError:44+ print('sphinxcontrib-log-cabinet is not installed.')45+ print('Changelog directives will not be re-organized.')46+else:47+ extensions.append('sphinxcontrib.log_cabinet')48+49 # Add any paths that contain templates here, relative to this directory.50 templates_path = ['_templates']51 52 # The suffix of source filenames.6 unmodified lines59 master_doc = 'index'60 61 # General information about the project.62 project = u'Flask'46-copyright = u'2014, Armin Ronacher'63+copyright = u'2010 - {0}, Armin Ronacher'.format(BUILD_DATE.year)64 65 # The version info for the project you're documenting, acts as replacement for66 # |version| and |release|, also used in various other places throughout the67 # built documents.51-import pkg_resources68 try:69 release = pkg_resources.get_distribution('Flask').version70 except pkg_resources.DistributionNotFound:55- print 'To build the documentation, The distribution information of Flask'56- print 'Has to be available. Either install the package into your'57- print 'development environment or run "setup.py develop" to setup the'58- print 'metadata. A virtualenv is recommended!'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)60-del pkg_resources74 75 if 'dev' in release:63- release = release.split('dev')[0] + 'dev'76+ release = ''.join(release.partition('dev')[:2])77+78 version = '.'.join(release.split('.')[:2])79 80 # The language for content autogenerated by Sphinx. Refer to documentation81 # for a list of supported languages.30 unmodified lines112 # -- Options for HTML output ---------------------------------------------------113 114 # The theme to use for HTML and HTML Help pages. Major themes that come with115 # Sphinx are currently 'default' and 'sphinxdoc'.102-html_theme = 'flask'116+# html_theme = 'default'117 118 # 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.107-html_theme_options = {108- 'touch_icon': 'touch-icon.png'109-}121+# html_theme_options = {}122 123 # Add any paths that contain custom themes here, relative to this directory.124 html_theme_path = ['_themes']125 10 unmodified lines136 137 # 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.128-html_favicon = "flask-favicon.ico"140+html_favicon = '_static/flask-favicon.ico'141 142 # 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 lines153 #html_use_smartypants = True154 155 # Custom sidebar templates, maps document names to template names.156 html_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 }170 171 # Additional templates that should be rendered to pages, maps page names to172 # template names.33 unmodified lines206 207 # Grouping the document tree into LaTeX files. List of tuples208 # (source start file, target name, title, author, documentclass [howto/manual]).209 latex_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 ]212 213 # Documents to append as an appendix to all manuals.214 #latex_appendices = []1 unmodified line216 # If false, no module index is generated.217 latex_use_modindex = False218 219 latex_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 }225 latex_use_parts = True226 227 latex_additional_files = ['flaskstyle.sty', 'logo.pdf']13 unmodified lines241 242 # The scheme of the identifier. Typical schemes are ISBN or URL.243 #epub_scheme = ''244 225-# The unique identifier of the text. This can be a ISBN number245+# The unique identifier of the text. This can be an ISBN number246 # or the project homepage.247 #epub_identifier = ''248 249 # A unique identification for the text.13 unmodified lines263 # The depth of the table of contents in toc.ncx.264 #epub_tocdepth = 3265 266 intersphinx_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 }275 254-pygments_style = 'flask_theme_support.FlaskyStyle'255-256-# fall back if theme is not there276 try:277 __import__('flask_theme_support')259-except 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+ }283+except 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)290 267- pygments_style = 'tango'268- html_theme = 'default'269- html_theme_options = {}291+292+# unwrap decorators293+def unwrap_decorators():294+ import sphinx.util.inspect as inspect295+ import functools296+297+ old_getargspec = inspect.getargspec298+ def getargspec(x):299+ return old_getargspec(getattr(x, '_original_function', x))300+ inspect.getargspec = getargspec301+302+ 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_wrapper308+309+unwrap_decorators()310+del unwrap_decoratorsmodified:docs/config.rst+72 added-43 removed
42 unmodified lines43 DEBUG=True,44 SECRET_KEY='...'45 )46 47+.. admonition:: Debug Mode with the ``flask`` Script48+49+ If you use the :command:`flask` script to start a local development50+ server, to enable the debug mode, you need to export the ``FLASK_DEBUG``51+ environment variable before running the server::52+53+ $ export FLASK_DEBUG=154+ $ flask run55+56+ (On Windows you need to use ``set`` instead of ``export``).57+ 58+ ``app.debug`` and ``app.config['DEBUG']`` are not compatible with 59+ the :command:`flask` script. They only worked when using ``Flask.run()``60+ method.61+ 62 Builtin Configuration Values63 ----------------------------64 65 The following configuration values are used internally by Flask:66 67 .. tabularcolumns:: |p{6.5cm}|p{8.5cm}|68 69 ================================= =========================================55-``DEBUG`` enable/disable debug mode70+``DEBUG`` enable/disable debug mode when using 71+ ``Flask.run()`` method to start server72 ``TESTING`` enable/disable testing mode73 ``PROPAGATE_EXCEPTIONS`` explicitly enable or disable the74 propagation of exceptions. If not set 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 be13 unmodified lines95 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 so1 unmodified line131 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 lines192 caches. You can override the default193 behavior by changing this variable.194 This is not recommended but might give195 you a performance improvement on 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 ================================= =========================================214 215 .. admonition:: More on ``SERVER_NAME``216 6 unmodified lines223 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`_.231 202-.. _bind: https://www.isc.org/software/bind232+.. _bind: https://www.isc.org/downloads/bind/233 234 .. versionadded:: 0.4235 ``LOGGER_NAME``236 17 unmodified lines254 255 .. versionadded:: 0.10256 ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_PRETTYPRINT_REGULAR``257 228-.. 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``261 231-.. versionadded:: 1.0232- ``TEMPLATES_AUTO_RELOAD``233-262 Configuring from Files263 ----------------------264 265 Configuration becomes more useful if you can store it in a separate file,48 unmodified lines314 a little harder. There is no single 100% solution for this problem in315 general, but there are a couple of things you can keep in mind to improve316 that experience:317 290-1. create your application in a function and register blueprints on it.318+1. 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.322 323 2. Do not write code that needs the configuration at import time. If you324 limit yourself to request-only accesses to the configuration you can325 reconfigure the object later on as needed.326 327+.. _config-dev-prod:328 329 Development / Production330 ------------------------331 7 unmodified lines339 app = Flask(__name__)340 app.config.from_object('yourapplication.default_settings')341 app.config.from_envvar('YOURAPPLICATION_SETTINGS')342 314-Then you just have to add a separate `config.py` file and export343+Then you just have to add a separate :file:`config.py` file and export344 ``YOURAPPLICATION_SETTINGS=/path/to/config.py`` and you are done. However345 there are alternative ways as well. For example you could use imports or346 subclassing.347 348 What is very popular in the Django world is to make the import explicit in320-the config file by adding an ``from yourapplication.default_settings349+the config file by adding ``from yourapplication.default_settings350 import *`` to the top of the file and then overriding the changes by hand.351 You could also inspect an environment variable like352 ``YOURAPPLICATION_MODE`` and set that to `production`, `development` etc353 and import different hardcoded files based on that.22 unmodified lines376 377 There are many different ways and it's up to you how you want to manage378 your configuration files. However here a list of good recommendations:379 351-- 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 can3 unmodified lines391 configurations separately to the production server(s). For some392 details about how to do that, head over to the393 :ref:`fabric-deployment` pattern.394 366-.. _fabric: http://fabfile.org/395+.. _fabric: http://www.fabfile.org/396 397 398 .. _instance-folders:399 80 unmodified linesmodified:docs/contents.rst.inc+2 added
21 unmodified lines22 appcontext23 reqcontext24 blueprints25 extensions26+ cli27+ server28 shell29 patterns/index30 deploying/index31 becomingbig30 unmodified linesmodified:docs/errorhandling.rst+115 added-23 removed
1 .. _application-errors:2 3-Logging Application Errors4-==========================3+Application Errors4+==================5 6 .. versionadded:: 0.37 8 Applications fail, servers fail. Sooner or later you will see an exception9 in production. Even if your code is 100% correct, you will still see10 exceptions from time to time. Why? Because everything else involved will11-fail. Here some situations where perfectly fine code can lead to server11+fail. Here are some situations where perfectly fine code can lead to server12 errors:13 14 - 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 failed22 23 And that's just a small sample of issues you could be facing. So how do we24 deal with that sort of problem? By default if your application runs in25 production mode, Flask will display a very simple page for you and log the1 unmodified line27 28 But there is more you can do, and we will cover some better setups to deal29 with errors.30 31+Error Logging Tools32+-------------------33+34+Sending error mails, even if just for critical ones, can become35+overwhelming if enough users are hitting the error and log files are36+typically never looked at. This is why we recommend using `Sentry37+<https://www.getsentry.com/>`_ for dealing with application errors. It's38+available as an Open Source project `on GitHub39+<https://github.com/getsentry/sentry>`__ and is also available as a `hosted version40+<https://getsentry.com/signup/>`_ which you can try for free. Sentry41+aggregates duplicate errors, captures the full stack trace and local42+variables for debugging, and sends you mails based on new errors or43+frequency thresholds.44+45+To use Sentry you need to install the `raven` client::46+47+ $ pip install raven48+49+And then add this to your Flask app::50+51+ from raven.contrib.flask import Sentry52+ sentry = Sentry(app, dsn='YOUR_DSN_HERE')53+54+Or if you are using factories you can also init it later::55+56+ from raven.contrib.flask import Sentry57+ sentry = Sentry(dsn='YOUR_DSN_HERE')58+59+ def create_app():60+ app = Flask(__name__)61+ sentry.init_app(app)62+ ...63+ return app64+65+The `YOUR_DSN_HERE` value needs to be replaced with the DSN value you get66+from your Sentry installation.67+68+Afterwards failures are automatically reported to Sentry and from there69+you can receive error notifications.70+71+.. _error-handlers:72+73+Error handlers74+--------------75+76+You might want to show custom error pages to the user when an error occurs.77+This can be done by registering error handlers.78+79+Error handlers are normal :ref:`views` but instead of being registered for80+routes, they are registered for exceptions that are raised while trying to81+do something else.82+83+Registering84+```````````85+86+Register error handlers using :meth:`~flask.Flask.errorhandler` or87+:meth:`~flask.Flask.register_error_handler`::88+89+ @app.errorhandler(werkzeug.exceptions.BadRequest)90+ def handle_bad_request(e):91+ return 'bad request!'92+93+ app.register_error_handler(400, lambda e: 'bad request!')94+95+Those two ways are equivalent, but the first one is more clear and leaves96+you with a function to call on your whim (and in tests). Note that97+:exc:`werkzeug.exceptions.HTTPException` subclasses like98+:exc:`~werkzeug.exceptions.BadRequest` from the example and their HTTP codes99+are interchangeable when handed to the registration methods or decorator100+(``BadRequest.code == 400``).101+102+You are however not limited to :exc:`~werkzeug.exceptions.HTTPException`103+or HTTP status codes but can register a handler for every exception class you104+like.105+106+.. versionchanged:: 0.11107+108+ Errorhandlers are now prioritized by specificity of the exception classes109+ they are registered for instead of the order they are registered in.110+111+Handling112+````````113+114+Once an exception instance is raised, its class hierarchy is traversed,115+and searched for in the exception classes for which handlers are registered.116+The most specific handler is selected.117+118+E.g. if an instance of :exc:`ConnectionRefusedError` is raised, and a handler119+is registered for :exc:`ConnectionError` and :exc:`ConnectionRefusedError`,120+the more specific :exc:`ConnectionRefusedError` handler is called on the121+exception instance, and its response is shown to the user.122+123 Error Mails124 -----------125 126 If the application runs in production mode (which it will do on your35-server) you won't see any log messages by default. Why is that? Flask36-tries to be a zero-configuration framework. Where should it drop the logs37-for you if there is no configuration? Guessing is not a good idea because38-chances are, the place it guessed is not the place where the user has39-permission to create a logfile. Also, for most small applications nobody40-will look at the logs anyways.127+server) you might not see any log messages. The reason for that is that128+Flask by default will just report to the WSGI error stream or stderr129+(depending on what's available). Where this ends up is sometimes hard to130+find. Often it's in your webserver's log files.131 42-In fact, I promise you right now that if you configure a logfile for the43-application errors you will never look at it except for debugging an issue44-when a user reported it for you. What you want instead is a mail the45-second the exception happened. Then you get an alert and you can do46-something about it.132+I can pretty much promise you however that if you only use a logfile for133+the application errors you will never look at it except for debugging an134+issue when a user reported it for you. What you probably want instead is135+a mail the second the exception happened. Then you get an alert and you136+can do something about it.137 138 Flask uses the Python builtin logging system, and it can actually send139 you mails for errors which is probably what you want. Here is how you can140 configure the Flask logger to send you mails for exceptions::29 unmodified lines170 -----------------171 172 Even if you get mails, you probably also want to log warnings. It's a173 good idea to keep as much information around that might be required to84-debug a problem. Please note that Flask itself will not issue any85-warnings in the core system, so it's your responsibility to warn in the86-code if something seems odd.174+debug a problem. By default as of Flask 0.11, errors are logged to your175+webserver's log automatically. Warnings however are not. Please note176+that Flask itself will not issue any warnings in the core system, so it's177+your responsibility to warn in the code if something seems odd.178 179 There are a couple of handlers provided by the logging system out of the180 box but not all of them are useful for basic error logging. The most181 interesting are probably the following:33 unmodified lines215 A formatter can be instantiated with a format string. Note that216 tracebacks are appended to the log entry automatically. You don't have to217 do that in the log formatter format string.218 128-Here some example setups:219+Here are some example setups:220 221 Email222 `````223 51 unmodified lines275 +------------------+----------------------------------------------------+276 | ``%(lineno)d`` | Source line number where the logging call was |277 | | issued (if available). |278 +------------------+----------------------------------------------------+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 linesmodified:docs/extensiondev.rst+20 added-30 removed
25 unmodified lines26 The name of the actual extension (the human readable name) however would27 be something like "Flask-SimpleXML". Make sure to include the name28 "Flask" somewhere in that name and that you check the capitalization.29 This is how users can then register dependencies to your extension in30-their `setup.py` files.30+their :file:`setup.py` files.31 32-Flask sets up a redirect package called :data:`flask.ext` where users33-should import the extensions from. If you for instance have a package34-called ``flask_something`` users would import it as35-``flask.ext.something``. This is done to transition from the old36-namespace packages. See :ref:`ext-import-transition` for more details.37-38-But how do extensions look like themselves? An extension has to ensure32+But what do extensions look like themselves? An extension has to ensure33 that it works with multiple Flask application instances at once. This is34 a requirement because many people will use patterns like the35 :ref:`app-factories` pattern to create their application as needed to aid36 unittests and to support multiple configurations. Because of that it is37 crucial that your application supports that kind of behavior.38 45-Most importantly the extension must be shipped with a `setup.py` file and39+Most importantly the extension must be shipped with a :file:`setup.py` file and40 registered on PyPI. Also the development checkout link should work so41 that people can easily install the development version into their42 virtualenv without having to download the library by hand.43 19 unmodified lines63 64 setup.py65 ````````66 73-The next file that is absolutely required is the `setup.py` file which is67+The next file that is absolutely required is the :file:`setup.py` file which is68 used to install your Flask extension. The following contents are69 something you can work with::70 71 """180 unmodified lines252 with app.app_context():253 cur = db.connection.cursor()254 cur.execute(...)255 262-At the end of the `with` block the teardown handles will be executed256+At the end of the ``with`` block the teardown handles will be executed257 automatically.258 259 Additionally, the ``init_app`` method is used to support the factory pattern260 for creating apps::92 unmodified lines353 extension author would like to move beyond the project, the project should354 find a new maintainer including full source hosting transition and PyPI355 access. If no maintainer is available, give access to the Flask core team.356 1. An approved Flask extension must provide exactly one package or module363- named ``flask_extensionname``. They might also reside inside a364- ``flaskext`` namespace packages though this is discouraged now.357+ named ``flask_extensionname``.358 2. It must ship a testing suite that can either be invoked with ``make test``359 or ``python setup.py test``. For test suites invoked with ``make360 test`` the extension has to ensure that all dependencies for the test361 are installed automatically. If tests are invoked with ``python setup.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.364 3. APIs of approved extensions will be checked for the following365 characteristics:366 5 unmodified lines372 4. The license must be BSD/MIT/WTFPL licensed.373 5. The naming scheme for official extensions is *Flask-ExtensionName* or374 *ExtensionName-Flask*.375 6. 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.378 7. The extension must have documentation that uses one of the two Flask379 themes for Sphinx documentation.380 8. The setup.py description (and thus the PyPI description) has to5 unmodified lines386 10. An extension currently has to support Python 2.6 as well as387 Python 2.7388 389 397-.. _ext-import-transition:398-390 Extension Import Transition391 ---------------------------392 402-For a while we recommended using namespace packages for Flask extensions.403-This turned out to be problematic in practice because many different404-competing namespace package systems exist and pip would automatically405-switch between different systems and this caused a lot of problems for406-users.393+In early versions of Flask we recommended using namespace packages for Flask394+extensions, of the form ``flaskext.foo``. This turned out to be problematic in395+practice because it meant that multiple ``flaskext`` packages coexist.396+Consequently we have recommended to name extensions ``flask_foo`` over397+``flaskext.foo`` for a long time.398 408-Instead we now recommend naming packages ``flask_foo`` instead of the now409-deprecated ``flaskext.foo``. Flask 0.8 introduces a redirect import410-system that lets uses import from ``flask.ext.foo`` and it will try411-``flask_foo`` first and if that fails ``flaskext.foo``.399+Flask 0.8 introduced a redirect import system as a compatibility aid for app400+developers: Importing ``flask.ext.foo`` would try ``flask_foo`` and401+``flaskext.foo`` in that order.402 413-Flask extensions should urge users to import from ``flask.ext.foo``414-instead of ``flask_foo`` or ``flaskext_foo`` so that extensions can415-transition to the new package name without affecting users.403+As of Flask 0.11, most Flask extensions have transitioned to the new naming404+schema. The ``flask.ext.foo`` compatibility alias is still in Flask 0.11 but is405+now deprecated -- you should use ``flask_foo``.406 407 418-.. _OAuth extension: http://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:2+3 Flask Extensions4 ================5 6 Flask extensions extend the functionality of Flask in various different2 unmodified lines9 Finding Extensions10 ------------------11 12 Flask extensions are listed on the `Flask Extension Registry`_ and can be11-downloaded with ``easy_install`` or ``pip``. If you add a Flask extension12-as dependency to your ``requirements.rst`` or ``setup.py`` file they are13+downloaded with :command:`easy_install` or :command:`pip`. If you add a Flask extension14+as dependency to your :file:`requirements.txt` or :file:`setup.py` file they are15 usually installed with a simple command or when your application installs.16 17 Using Extensions18 ----------------19 20 Extensions typically have documentation that goes along that shows how to21 use it. There are no general rules in how extensions are supposed to22 behave but they are imported from common locations. If you have an21-extension called ``Flask-Foo`` or ``Foo-Flask`` it will be always22-importable from ``flask.ext.foo``::23+extension called ``Flask-Foo`` or ``Foo-Flask`` it should be always24+importable from ``flask_foo``::25 24- from flask.ext import foo26+ import flask_foo27 28+Building Extensions29+-------------------30+31+While `Flask Extension Registry`_ contains many Flask extensions, you may not find32+an extension that fits your need. If this is the case, you can always create your own. 33+Consider reading :ref:`extension-dev` to develop your own Flask extension.34+35 Flask Before 0.836 ----------------37 38 If you are using Flask 0.7 or earlier the :data:`flask.ext` package will not1 unmodified line40 depending on how the extension is distributed. If you want to develop an41 application that supports Flask 0.7 or earlier you should still import42 from the :data:`flask.ext` package. We provide you with a compatibility43 module that provides this package for older versions of Flask. You can35-download it from github: `flaskext_compat.py`_44+download it from GitHub: `flaskext_compat.py`_45 46 And here is how you can use it::47 48 import flaskext_compat3 unmodified lines52 53 Once the ``flaskext_compat`` module is activated the :data:`flask.ext` will54 exist and you can start importing from there.55 56+57 .. _Flask Extension Registry: http://flask.pocoo.org/extensions/48-.. _flaskext_compat.py: https://github.com/mitsuhiko/flask/raw/master/scripts/flaskext_compat.py58+.. _flaskext_compat.py: https://raw.githubusercontent.com/pallets/flask/master/scripts/flaskext_compat.pymodified:docs/foreword.rst+3 added-3 removed
7 unmodified lines8 What does "micro" mean?9 -----------------------10 11 “Micro” does not mean that your whole web application has to fit into a single12-Python file, although it certainly can. Nor does it mean that Flask is lacking12+Python file (although it certainly can), nor does it mean that Flask is lacking13 in functionality. The "micro" in microframework means Flask aims to keep the14 core simple but extensible. Flask won't make many decisions for you, such as15 what database to use. Those decisions that it does make, such as what16 templating engine to use, are easy to change. Everything else is up to you, so10 unmodified lines27 Configuration and Conventions28 -----------------------------29 30 Flask has many configuration values, with sensible defaults, and a few31-conventions when getting started. By convention templates and static files are31+conventions when getting started. By convention, templates and static files are32 stored in subdirectories within the application's Python source tree, with the33-names `templates` and `static` respectively. While this can be changed you33+names :file:`templates` and :file:`static` respectively. While this can be changed, you34 usually don't have to, especially when getting started.35 36 Growing with Flask37 ------------------20 unmodified linesmodified:docs/htmlfaq.rst+3 added-3 removed
14 unmodified lines15 However, barely any websites on the Internet are actual XHTML (which is16 HTML processed using XML rules). There are a couple of major reasons17 why this is the case. One of them is Internet Explorer's lack of proper18 XHTML support. The XHTML spec states that XHTML must be served with the MIME19-type `application/xhtml+xml`, but Internet Explorer refuses to read files19+type :mimetype:`application/xhtml+xml`, but Internet Explorer refuses to read files20 with that MIME type.21 While it is relatively easy to configure Web servers to serve XHTML properly,22 few people do. This is likely because properly using XHTML can be quite23 painful.5 unmodified lines29 the (X)HTML generation on the web is based on non-XML template engines30 (such as Jinja, the one used in Flask) which do not protect you from31 accidentally creating invalid XHTML. There are XML based template engines,32 such as Kid and the popular Genshi, but they often come with a larger33-runtime overhead and, are not as straightforward to use because they have33+runtime overhead and are not as straightforward to use because they have34 to obey XML rules.35 36 The majority of users, however, assumed they were properly using XHTML.37 They wrote an XHTML doctype at the top of the document and self-closed all147 unmodified lines185 Many other features have been added, as well. A good guide to new features186 in HTML5 is Mark Pilgrim's soon-to-be-published book, `Dive Into HTML5`_.187 Not all of them are supported in browsers yet, however, so use caution.188 189-.. _Dive Into HTML5: http://www.diveintohtml5.org/189+.. _Dive Into HTML5: http://diveintohtml5.info/190 191 What should be used?192 --------------------193 14 unmodified linesmodified:docs/index.rst+3 added-3 removed
19 unmodified lines20 engine and the `Werkzeug`_ WSGI toolkit. These libraries are not documented21 here. If you want to dive into their documentation, check out the22 following links:23 24-- `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>`_26 27 28-.. _Jinja2: http://jinja.pocoo.org/2/28+.. _Jinja2: http://jinja.pocoo.org/29 .. _Werkzeug: http://werkzeug.pocoo.org/30 31 .. include:: contents.rst.incmodified:docs/installation.rst+119 added-125 removed
1 unmodified line2 3 Installation4 ============5 6-Flask depends on some external libraries, like `Werkzeug7-<http://werkzeug.pocoo.org/>`_ and `Jinja2 <http://jinja.pocoo.org/2/>`_.8-Werkzeug is a toolkit for WSGI, the standard Python interface between web9-applications and a variety of servers for both development and deployment.10-Jinja2 renders templates.6+Python Version7+--------------8 12-So how do you get all that on your computer quickly? There are many ways you13-could do that, but the most kick-ass method is virtualenv, so let's have a look14-at that first.9+We recommend using the latest version of Python 3. Flask supports Python 3.310+and newer, Python 2.6 and newer, and PyPy.11 16-You will need Python 2.6 or newer to get started, so be sure to have an17-up-to-date Python 2.x installation. For using Flask with Python 3 have a18-look at :ref:`python3-support`.12+Dependencies13+------------14 20-.. _virtualenv:15+These distributions will be installed automatically when installing Flask.16 22-virtualenv23-----------17+* `Werkzeug`_ implements WSGI, the standard Python interface between18+ applications and servers.19+* `Jinja`_ is a template language that renders the pages your application20+ serves.21+* `MarkupSafe`_ comes with Jinja. It escapes untrusted input when rendering22+ templates to avoid injection attacks.23+* `ItsDangerous`_ securely signs data to ensure its integrity. This is used24+ to protect Flask's session cookie.25+* `Click`_ is a framework for writing command line applications. It provides26+ the ``flask`` command and allows adding custom management commands.27 25-Virtualenv is probably what you want to use during development, and if you have26-shell access to your production machines, you'll probably want to use it there,27-too.28+.. _Werkzeug: http://werkzeug.pocoo.org/29+.. _Jinja: http://jinja.pocoo.org/30+.. _MarkupSafe: https://pypi.python.org/pypi/MarkupSafe31+.. _ItsDangerous: https://pythonhosted.org/itsdangerous/32+.. _Click: http://click.pocoo.org/33 29-What problem does virtualenv solve? If you like Python as much as I do,30-chances are you want to use it for other projects besides Flask-based web31-applications. But the more projects you have, the more likely it is that you32-will be working with different versions of Python itself, or at least different33-versions of Python libraries. Let's face it: quite often libraries break34-backwards compatibility, and it's unlikely that any serious application will35-have zero dependencies. So what do you do if two or more of your projects have36-conflicting dependencies?34+Optional dependencies35+~~~~~~~~~~~~~~~~~~~~~36 38-Virtualenv to the rescue! Virtualenv enables multiple side-by-side39-installations of Python, one for each project. It doesn't actually install40-separate copies of Python, but it does provide a clever way to keep different41-project environments isolated. Let's see how virtualenv works.37+These distributions will not be installed automatically. Flask will detect and38+use them if you install them.39 43-If you are on Mac OS X or Linux, chances are that one of the following two44-commands will work for you::40+* `Blinker`_ provides support for :ref:`signals`.41+* `SimpleJSON`_ is a fast JSON implementation that is compatible with42+ Python's ``json`` module. It is preferred for JSON operations if it is43+ installed.44 46- $ sudo easy_install virtualenv45+.. _Blinker: https://pythonhosted.org/blinker/46+.. _SimpleJSON: https://simplejson.readthedocs.io/47 48-or even better::48+Virtual environments49+--------------------50 50- $ sudo pip install virtualenv51+Use a virtual environment to manage the dependencies for your project, both in52+development and in production.53 52-One of these will probably install virtualenv on your system. Maybe it's even53-in your package manager. If you use Ubuntu, try::54+What problem does a virtual environment solve? The more Python projects you55+have, the more likely it is that you need to work with different versions of56+Python libraries, or even Python itself. Newer versions of libraries for one57+project can break compatibility in another project.58 55- $ sudo apt-get install python-virtualenv59+Virtual environments are independent groups of Python libraries, one for each60+project. Packages installed for one project will not affect other projects or61+the operating system's packages.62 57-If you are on Windows and don't have the `easy_install` command, you must58-install it first. Check the :ref:`windows-easy-install` section for more59-information about how to do that. Once you have it installed, run the same60-commands as above, but without the `sudo` prefix.63+Python 3 comes bundled with the :mod:`venv` module to create virtual64+environments. If you're using a modern version of Python, you can continue on65+to the next section.66 62-Once you have virtualenv installed, just fire up a shell and create63-your own environment. I usually create a project folder and a `venv`64-folder within::67+If you're using Python 2, see :ref:`install-install-virtualenv` first.68 66- $ mkdir myproject67- $ cd myproject68- $ virtualenv venv69- New python executable in venv/bin/python70- Installing setuptools, pip............done.69+.. _install-create-env:70 72-Now, whenever you want to work on a project, you only have to activate the73-corresponding environment. On OS X and Linux, do the following::71+Create an environment72+~~~~~~~~~~~~~~~~~~~~~73 75- $ . venv/bin/activate74+Create a project folder and a :file:`venv` folder within:75 77-If you are a Windows user, the following command is for you::76+.. code-block:: sh77 79- $ venv\scripts\activate78+ mkdir myproject79+ cd myproject80+ python3 -m venv venv81 81-Either way, you should now be using your virtualenv (notice how the prompt of82-your shell has changed to show the active environment).82+On Windows:83 84-Now you can just enter the following command to get Flask activated in your85-virtualenv::84+.. code-block:: bat85 87- $ pip install Flask86+ py -3 -m venv venv87 89-A few seconds later and you are good to go.88+If you needed to install virtualenv because you are on an older version of89+Python, use the following command instead:90 91+.. code-block:: sh92 92-System-Wide Installation93-------------------------93+ virtualenv venv94 95-This is possible as well, though I do not recommend it. Just run96-`pip` with root privileges::95+On Windows:96 98- $ sudo pip install Flask97+.. code-block:: bat98 100-(On Windows systems, run it in a command-prompt window with administrator101-privileges, and leave out `sudo`.)99+ \Python27\Scripts\virtualenv.exe venv100 101+Activate the environment102+~~~~~~~~~~~~~~~~~~~~~~~~103 104-Living on the Edge105-------------------104+Before you work on your project, activate the corresponding environment:105 107-If you want to work with the latest version of Flask, there are two ways: you108-can either let `pip` pull in the development version, or you can tell109-it to operate on a git checkout. Either way, virtualenv is recommended.106+.. code-block:: sh107 111-Get the git checkout in a new virtualenv and run in development mode::108+ . venv/bin/activate109 113- $ 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 Flask110+On Windows:111 124-This will pull in the dependencies and activate the git head as the current125-version inside the virtualenv. Then all you have to do is run ``git pull126-origin`` to update to the latest version.112+.. code-block:: bat113 128-To just get the development version without git, do this instead::114+ venv\Scripts\activate115 130- $ 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==dev116+Your shell prompt will change to show the name of the activated environment.117 140-.. _windows-easy-install:118+Install Flask119+-------------120 142-`pip` and `setuptools` on Windows143----------------------------------121+Within the activated environment, use the following command to install Flask:122 145-Sometimes getting the standard "Python packaging tools" like *pip*, *setuptools*146-and *virtualenv* can be a little trickier, but nothing very hard. The two crucial147-packages you will need are setuptools and pip - these will let you install148-anything else (like virtualenv). Fortunately there are two "bootstrap scripts"149-you can run to install either.123+.. code-block:: sh124 151-If 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 Flask126 154-`get-pip.py`_127+Living on the edge128+~~~~~~~~~~~~~~~~~~129 156-To install the latest setuptools, you can use its bootstrap file:130+If you want to work with the latest Flask code before it's released, install or131+update the code from the master branch:132 158-`ez_setup.py`_133+.. code-block:: sh134 160-Either should be double-clickable once you download them. If you already have pip,161-you can upgrade them by running::135+ pip install -U https://github.com/pallets/flask/archive/master.tar.gz136 163- > pip install --upgrade pip setuptools137+.. _install-install-virtualenv:138 165-Most often, once you pull up a command prompt you want to be able to type ``pip``166-and ``python`` which will run those things, but this might not automatically happen167-on Windows, because it doesn't know where those executables are (give either a try!).139+Install virtualenv140+------------------141 169-To 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 and172-check that you can now just type ``python`` to bring up the interpreter.142+If you are using Python 2, the venv module is not available. Instead,143+install `virtualenv`_.144 174-Finally, to install `virtualenv`_, you can simply run::145+On Linux, virtualenv is provided by your package manager:146 176- > pip install virtualenv177- 178-Then you can be off on your way following the installation instructions above.147+.. code-block:: sh148 180-.. _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-virtualenv151+152+ # CentOS, Fedora153+ sudo yum install python-virtualenv154+155+ # Arch156+ sudo pacman -S python-virtualenv157+158+If you are on Mac OS X or Windows, download `get-pip.py`_, then:159+160+.. code-block:: sh161+162+ sudo python2 Downloads/get-pip.py163+ sudo python2 -m pip install virtualenv164+165+On Windows, as an administrator:166+167+.. code-block:: bat168+169+ \Python27\python.exe Downloads\get-pip.py170+ \Python27\python.exe -m pip install virtualenv171+172+Now you can continue to :ref:`install-create-env`.173+174+.. _virtualenv: https://virtualenv.pypa.io/175+.. _get-pip.py: https://bootstrap.pypa.io/get-pip.pymodified:docs/license.rst+1 added-1 removed
24 unmodified lines25 26 - "AUTHORS" hereby refers to all the authors listed in the27 :ref:`authors` section.28 29-- 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.32 33 - The ":ref:`artwork-license`" applies to the project's Horn-Logo.15 unmodified linesmodified:docs/python3.rst+14 added-52 removed
1 unmodified line2 3 Python 3 Support4 ================5 6-Flask and all of its dependencies support Python 3 so you can in theory7-start working on it already. There are however a few things you should be8-aware of before you start using Python 3 for your next project.6+Flask, its dependencies, and most Flask extensions support Python 3.7+You should start using Python 3 for your next project,8+but there are a few things to be aware of.9 10-Requirements11-------------10+You need to use Python 3.3 or higher. 3.2 and older are *not* supported.11 13-If you want to use Flask with Python 3 you will need to use Python 3.3 or14-higher. 3.2 and older are *not* supported.12+You should use the latest versions of all Flask-related packages.13+Flask 0.10 and Werkzeug 0.9 were the first versions to introduce Python 3 support.14 16-In addition to that you need to use the latest and greatest versions of17-`itsdangerous`, `Jinja2` and `Werkzeug`.15+Python 3 changed how unicode and bytes are handled, which complicates how low16+level code handles HTTP data. This mainly affects WSGI middleware interacting17+with the WSGI ``environ`` data. Werkzeug wraps that information in high-level18+helpers, so encoding issues should not affect you.19 19-API Stability20--------------21-22-Some of the decisions made in regards to unicode and byte untilization on23-Python 3 make it hard to write low level code. This mainly affects WSGI24-middlewares and interacting with the WSGI provided information. Werkzeug25-wraps all that information in high-level helpers but some of those were26-specifically added for the Python 3 support and are quite new.27-28-A lot of the documentation out there on using WSGI leaves out those29-details as it was written before WSGI was updated to Python 3. While the30-API for Werkzeug and Flask on Python 2.x should not change much we cannot31-guarantee that this won't happen on Python 3.32-33-Few Users34----------35-36-Python 3 currently has less than 1% of the users of Python 2 going by PyPI37-download stats. As a result many of the problems you will encounter are38-probably hard to search for on the internet if they are Python 3 specific.39-40-Small Ecosystem41----------------42-43-The majority of the Flask extensions, all of the documentation and the44-vast majority of the PyPI provided libraries do not support Python 3 yet.45-Even if you start your project with knowing that all you will need is46-supported by Python 3 you don't know what happens six months from now. If47-you are adventurous you can start porting libraries on your own, but that48-is nothing for the faint of heart.49-50-Recommendations51----------------52-53-Unless you are already familiar with the differences in the versions we54-recommend sticking to current versions of Python until the ecosystem55-caught up.56-57-The majority of the upgrade pain is in the lower-level libararies like58-Flask and Werkzeug and not in the actual high-level application code. For59-instance all of the Flask examples that are in the Flask repository work60-out of the box on both 2.x and 3.x and did not require a single line of61-code changed.20+The majority of the upgrade work is in the lower-level libraries like21+Flask and Werkzeug, not the high-level application code.22+For example, all of the examples in the Flask repository work on both Python 2 and 323+and did not require a single line of code changed.modified:docs/quickstart.rst+231 added-249 removed
16 unmodified lines17 app = Flask(__name__)18 19 @app.route('/')20 def hello_world():21- return 'Hello World!'21+ return 'Hello, World!'22 23- if __name__ == '__main__':24- app.run()25-26-Just save it as `hello.py` (or something similar) and run it with your Python27-interpreter. Make sure to not call your application `flask.py` because this28-would conflict with Flask itself.29-30-::31-32- $ python hello.py33- * Running on http://127.0.0.1:5000/34-35-Now head over to `http://127.0.0.1:5000/ <http://127.0.0.1:5000/>`_, and you36-should see your hello world greeting.37-23 So what did that code do?24 25 1. 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.27 2. Next we create an instance of this class. The first argument is the name of28 the application's module or package. If you are using a single module (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 line35 should trigger our function.36 4. The function is given a name which is also used to generate URLs for that37 particular function, and returns the message we want to display in the38 user's browser.54-5. 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.39 59-To stop the server, hit control-C.40+Just save it as :file:`hello.py` or something similar. Make sure to not call41+your application :file:`flask.py` because this would conflict with Flask42+itself.43 44+To run the application you can either use the :command:`flask` command or45+python's ``-m`` switch with Flask. Before you can do that you need46+to tell your terminal the application to work with by exporting the47+``FLASK_APP`` environment variable::48+49+ $ export FLASK_APP=hello.py50+ $ flask run51+ * Running on http://127.0.0.1:5000/52+53+If you are on Windows you need to use ``set`` instead of ``export``.54+55+Alternatively you can use :command:`python -m flask`::56+57+ $ export FLASK_APP=hello.py58+ $ python -m flask run59+ * Running on http://127.0.0.1:5000/60+61+This launches a very simple builtin server, which is good enough for testing62+but probably not what you want to use in production. For deployment options see63+:ref:`deployment`.64+65+Now head over to `http://127.0.0.1:5000/ <http://127.0.0.1:5000/>`_, and you66+should see your hello world greeting.67+68 .. _public-server:69 70 .. admonition:: Externally Visible Server71 1 unmodified line73 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.76 70- 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::80 74- app.run(host='0.0.0.0')81+ flask run --host=0.0.0.082 83 This tells your operating system to listen on all public IPs.84 85 86+What to do if the Server does not Start87+---------------------------------------88+89+In case the :command:`python -m flask` fails or :command:`flask` does not exist,90+there are multiple reasons this might be the case. First of all you need91+to look at the error message.92+93+Old Version of Flask94+````````````````````95+96+Versions of Flask older than 0.11 use to have different ways to start the97+application. In short, the :command:`flask` command did not exist, and98+neither did :command:`python -m flask`. In that case you have two options:99+either upgrade to newer Flask versions or have a look at the :ref:`server`100+docs to see the alternative method for running a server.101+102+Invalid Import Name103+```````````````````104+105+The ``FLASK_APP`` environment variable is the name of the module to import at106+:command:`flask run`. In case that module is incorrectly named you will get an107+import error upon start (or if debug is enabled when you navigate to the108+application). It will tell you what it tried to import and why it failed.109+110+The most common reason is a typo or because you did not actually create an111+``app`` object.112+113 .. _debug-mode:114 115 Debug Mode116 ----------117 84-The :meth:`~flask.Flask.run` method is nice to start a local85-development server, but you would have to restart it manually after each86-change to your code. That is not very nice and Flask can do better. If87-you enable debug support the server will reload itself on code changes,88-and 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`)119 90-There are two ways to enable debugging. Either set that flag on the91-application object::120+The :command:`flask` script is nice to start a local development server, but121+you would have to restart it manually after each change to your code.122+That is not very nice and Flask can do better. If you enable debug123+support the server will reload itself on code changes, and it will also124+provide you with a helpful debugger if things go wrong.125 93- app.debug = True94- app.run()126+To enable debug mode you can export the ``FLASK_DEBUG`` environment variable127+before running the server::128 96-Or pass it as a parameter to run::129+ $ export FLASK_DEBUG=1130+ $ flask run131 98- app.run(debug=True)132+(On Windows you need to use ``set`` instead of ``export``).133 100-Both methods have the exact same effect.134+This does the following things:135 136+1. it activates the debugger137+2. it activates the automatic reloader138+3. it enables the debug mode on the Flask application.139+140+There are more parameters that are explained in the :ref:`server` docs.141+142 .. admonition:: Attention143 144 Even though the interactive debugger does not work in forking environments145 (which makes it nearly impossible to use on production servers), it still12 unmodified lines158 159 Routing160 -------161 122-Modern web applications have beautiful URLs. This helps people remember123-the URLs, which is especially handy for applications that are used from124-mobile devices with slower network connections. If the user can directly125-go to the desired page without having to hit the index page it is more126-likely they will like the page and come back next time.162+Modern web applications use meaningful URLs to help users. Users are more163+likely to like a page and come back if the page uses a meaningful URL they can164+remember and use to directly visit a page.165 128-As you have seen above, the :meth:`~flask.Flask.route` decorator is used to129-bind a function to a URL. Here are some basic examples::166+Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::167 168 @app.route('/')169 def index():170 return 'Index Page'171 172 @app.route('/hello')173 def hello():137- return 'Hello World'174+ return 'Hello, World'175 139-But there is more to it! You can make certain parts of the URL dynamic and140-attach multiple rules to a function.176+You can do more! You can make parts of the URL dynamic and attach multiple177+rules to a function.178 179 Variable Rules180 ``````````````181 145-To 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 your147-function. Optionally a converter can be used by specifying a rule with148-``<converter:variable_name>``. Here are some nice examples::182+You can add variable sections to a URL by marking sections with183+``<variable_name>``. Your function then receives the ``<variable_name>``184+as a keyword argument. Optionally, you can use a converter to specify the type185+of the argument like ``<converter:variable_name>``. ::186 187 @app.route('/user/<username>')188 def show_user_profile(username):189 # show the user profile for that user3 unmodified lines193 def show_post(post_id):194 # show the post with the given id, the id is an integer195 return 'Post %d' % post_id196 160-The following converters exist:197+ @app.route('/path/<path:subpath>')198+ def show_subpath(subpath):199+ # show the subpath after /path/200+ return 'Subpath %s' % subpath201 162-=========== ===========================================163-`int` accepts integers164-`float` like `int` but for floating point values165-`path` like the default but also accepts slashes166-=========== ===========================================202+Converter types:203 168-.. admonition:: Unique URLs / Redirection Behavior204+========== ==========================================205+``string`` (default) accepts any text without a slash206+``int`` accepts positive integers207+``float`` accepts positive floating point values208+``path`` like ``string`` but also accepts slashes209+``uuid`` accepts UUID strings210+========== ==========================================211 170- 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.212+Unique URLs / Redirection Behavior213+``````````````````````````````````214 174- Take these two rules::215+Take these two rules::216 176- @app.route('/projects/')177- def projects():178- return 'The project page'217+ @app.route('/projects/')218+ def projects():219+ return 'The project page'220 180- @app.route('/about')181- def about():182- return 'The about page'221+ @app.route('/about')222+ def about():223+ return 'The about page'224 184- 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.225+Though they look similar, they differ in their use of the trailing slash in226+the URL. In the first case, the canonical URL for the ``projects`` endpoint227+uses a trailing slash. It's similar to a folder in a file system; if you228+access the URL without a trailing slash, Flask redirects you to the229+canonical URL with the trailing slash.230 190- 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.231+In the second case, however, the URL definition lacks a trailing slash,232+like the pathname of a file on UNIX-like systems. Accessing the URL with a233+trailing slash produces a 404 “Not Found” error.234 194- 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.235+This behavior allows relative URLs to continue working even if the trailing236+slash is omitted, consistent with how Apache and other servers work. Also,237+the URLs will stay unique, which helps search engines avoid indexing the238+same page twice.239 199-240 .. _url-building:241 242 URL Building243 ````````````244 205-If it can match URLs, can Flask also generate them? Of course it can. To206-build a URL to a specific function you can use the :func:`~flask.url_for`207-function. It accepts the name of the function as first argument and a number208-of keyword arguments, each corresponding to the variable part of the URL rule.209-Unknown variable parts are appended to the URL as query parameters. Here are210-some examples:245+To build a URL to a specific function, use the :func:`~flask.url_for` function.246+It accepts the name of the function as its first argument and any number of247+keyword arguments, each corresponding to a variable part of the URL rule.248+Unknown variable parts are appended to the URL as query parameters.249 212->>> 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%20Doe250+Why would you want to build URLs using the URL reversing function251+:func:`~flask.url_for` instead of hard-coding them into your templates?252 234-(This also uses the :meth:`~flask.Flask.test_request_context` method, explained235-below. It tells Flask to behave as though it is handling a request, even236-though we are interacting with it through a Python shell. Have a look at the237-explanation below. :ref:`context-locals`).253+1. Reversing is often more descriptive than hard-coding the URLs.254+2. You can change your URLs in one go instead of needing to remember to255+ manually change hard-coded URLs.256+3. URL building handles escaping of special characters and Unicode data257+ transparently.258+4. If your application is placed outside the URL root, for example, in259+ ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly260+ handles that for you.261 239-Why would you want to build URLs using the URL reversing function :func:`~flask.url_for` 240-instead of hard-coding them into your templates? There are three good reasons 241-for this:262+For example, here we use the :meth:`~flask.Flask.test_request_context` method263+to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`264+tells Flask to behave as though it's handling a request even while we use a265+Python shell. See :ref:`context-locals`. ::266 243-1. 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.246-2. URL building will handle escaping of special characters and Unicode247- data transparently for you, so you don't have to deal with them.248-3. 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_for268 269+ app = Flask(__name__)270 271+ @app.route('/')272+ def index():273+ return 'index'274+275+ @app.route('/login')276+ def login():277+ return 'login'278+279+ @app.route('/user/<username>')280+ def profile(username):281+ return '{}'s profile'.format(username)282+283+ with app.test_request_context():284+ print(url_for('index'))285+ print(url_for('login'))286+ print(url_for('login', next='/'))287+ print(url_for('profile', username='John Doe'))288+289+ /290+ /login291+ /login?next=/292+ /user/John%20Doe293+294 HTTP Methods295 ````````````296 256-HTTP (the protocol web applications are speaking) knows different methods for257-accessing URLs. By default, a route only answers to `GET` requests, but that258-can be changed by providing the `methods` argument to the259-:meth:`~flask.Flask.route` decorator. Here are some examples::297+Web applications use different HTTP methods when accessing URLs. You should298+familiarize yourself with the HTTP methods as you work with Flask. By default,299+a route only answers to ``GET`` requests. You can use the ``methods`` argument300+of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.301+::302 261- from flask import request262-303 @app.route('/login', methods=['GET', 'POST'])304 def login():305 if request.method == 'POST':306 do_the_login()307 else:308 show_the_login_form()309 270-If `GET` is present, `HEAD` will be added automatically for you. You271-don't have to deal with that. It will also make sure that `HEAD` requests272-are handled as the `HTTP RFC`_ (the document describing the HTTP273-protocol) demands, so you can completely ignore that part of the HTTP274-specification. Likewise, as of Flask 0.6, `OPTIONS` is implemented for you275-automatically as well.310+If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method311+and handles ``HEAD`` requests according to the the `HTTP RFC`_. Likewise,312+``OPTIONS`` is automatically implemented for you.313 277-You have no idea what an HTTP method is? Worry not, here is a quick278-introduction to HTTP methods and why they matter:314+.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt315 280-The HTTP method (also often called "the verb") tells the server what the281-clients wants to *do* with the requested page. The following methods are282-very common:283-284-`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.287-288-`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.295-296-`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.301-302-`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.311-312-`DELETE`313- Remove the information at the given location.314-315-`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.319-320-Now the interesting part is that in HTML4 and XHTML1, the only methods a321-form can submit to the server are `GET` and `POST`. But with JavaScript322-and future HTML standards you can use the other methods as well. Furthermore323-HTTP has become quite popular lately and browsers are no longer the only324-clients that are using HTTP. For instance, many revision control systems325-use it.326-327-.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt328-316 Static Files317 ------------318 319 Dynamic web applications also need static files. That's usually where320 the CSS and JavaScript files are coming from. Ideally your web server is321 configured to serve them for you, but during development Flask can do that335-as well. Just create a folder called `static` in your package or next to336-your module and it will be available at `/static` on the application.322+as well. Just create a folder called :file:`static` in your package or next to323+your module and it will be available at ``/static`` on the application.324 325 To generate URLs for static files, use the special ``'static'`` endpoint name::326 327 url_for('static', filename='style.css')328 342-The file has to be stored on the filesystem as ``static/style.css``.329+The file has to be stored on the filesystem as :file:`static/style.css`.330 331 Rendering Templates332 -------------------333 334 Generating HTML from within Python is not fun, and actually pretty335 cumbersome because you have to do the HTML escaping on your own to keep336 the 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.338 339 To render a template you can use the :func:`~flask.render_template`340 method. All you have to do is provide the name of the template and the341 variables you want to pass to the template engine as keyword arguments.5 unmodified lines347 @app.route('/hello/<name>')348 def hello(name=None):349 return render_template('hello.html', name=name)350 364-Flask will look for templates in the `templates` folder. So if your351+Flask will look for templates in the :file:`templates` folder. So if your352 application is a module, this folder is next to that module, if it's a353 package it's actually inside your package:354 355 **Case 1**: a module::10 unmodified lines366 /hello.html367 368 For templates you can use the full power of Jinja2 templates. Head over369 to 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.371 372 Here is an example template:373 374 .. sourcecode:: html+jinja2 unmodified lines377 <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 %}383 384 Inside templates you also have access to the :class:`~flask.request`,385 :class:`~flask.session` and :class:`~flask.g` [#]_ objects3 unmodified lines389 know how that works, head over to the :ref:`template-inheritance` pattern390 documentation. Basically template inheritance makes it possible to keep391 certain elements on each page (like header, navigation and footer).392 406-Automatic escaping is enabled, so if `name` contains HTML it will be escaped393+Automatic escaping is enabled, so if ``name`` contains HTML it will be escaped394 automatically. If you can trust a variable and you know that it will be395 safe HTML (for example because it came from a module that converts wiki396 markup to HTML) you can mark it as safe by using the397 :class:`~jinja2.Markup` class or by using the ``|safe`` filter in the398 template. Head over to the Jinja 2 documentation for more examples.399 413-Here is a basic introduction to how the :class:`~jinja2.Markup` class works:400+Here is a basic introduction to how the :class:`~jinja2.Markup` class works::401 415->>> from flask import Markup416->>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'417-Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')418->>> Markup.escape('<blink>hacker</blink>')419-Markup(u'<blink>hacker</blink>')420->>> Markup('<em>Marked up</em> » HTML').striptags()421-u'Marked up \xbb HTML'402+ >>> from flask import Markup403+ >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'404+ Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')405+ >>> Markup.escape('<blink>hacker</blink>')406+ Markup(u'<blink>hacker</blink>')407+ >>> Markup('<em>Marked up</em> » HTML').striptags()408+ u'Marked up \xbb HTML'409 410 .. versionchanged:: 0.5411 412 Autoescaping is no longer enabled for all templates. The following9 unmodified lines422 423 Accessing Request Data424 ----------------------425 439-For web applications it's crucial to react to the data a client sent to426+For web applications it's crucial to react to the data a client sends to427 the server. In Flask this information is provided by the global428 :class:`~flask.request` object. If you have some experience with Python429 you might be wondering how that object can be global and how Flask430 manages to still be threadsafe. The answer is context locals:27 unmodified lines458 will notice that code which depends on a request object will suddenly break459 because there is no request object. The solution is creating a request460 object yourself and binding it to the context. The easiest solution for461 unit testing is to use the :meth:`~flask.Flask.test_request_context`475-context manager. In combination with the `with` statement it will bind a462+context manager. In combination with the ``with`` statement it will bind a463 test request so that you can interact with it. Here is an example::464 465 from flask import request466 14 unmodified lines481 The Request Object482 ``````````````````483 484 The request object is documented in the API section and we will not cover498-it here in detail (see :class:`~flask.request`). Here is a broad overview of485+it here in detail (see :class:`~flask.Request`). Here is a broad overview of486 some of the most common operations. First of all you have to import it from500-the `flask` module::487+the ``flask`` module::488 489 from flask import request490 491 The current request method is available by using the505-:attr:`~flask.request.method` attribute. To access form data (data506-transmitted 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 (data493+transmitted in a ``POST`` or ``PUT`` request) you can use the494+:attr:`~flask.Request.form` attribute. Here is a full example of the two495 attributes mentioned above::496 497 @app.route('/login', methods=['POST', 'GET'])498 def login():7 unmodified lines506 # the code below is executed if the request method507 # was GET or the credentials were invalid508 return render_template('login.html', error=error)509 523-What happens if the key does not exist in the `form` attribute? In that510+What happens if the key does not exist in the ``form`` attribute? In that511 case a special :exc:`KeyError` is raised. You can catch it like a512 standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request513 error page is shown instead. So for many situations you don't have to514 deal with that problem.515 516 To access parameters submitted in the URL (``?key=value``) you can use the530-:attr:`~flask.request.args` attribute::517+:attr:`~flask.Request.args` attribute::518 519 searchword = request.args.get('key', '')520 521 We recommend accessing URL parameters with `get` or by catching 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 400523 bad request page in that case is not user friendly.524 525 For a full list of methods and attributes of the request object, head over539-to the :class:`~flask.request` documentation.526+to the :class:`~flask.Request` documentation.527 528 529 File Uploads530 ````````````28 unmodified lines559 pass it through the :func:`~werkzeug.utils.secure_filename` function that560 Werkzeug provides for you::561 562 from flask import request576- from werkzeug import secure_filename563+ from werkzeug.utils import secure_filename564 565 @app.route('/upload', methods=['GET', 'POST'])566 def upload_file():567 if request.method == 'POST':80 unmodified lines648 Note the ``404`` after the :func:`~flask.render_template` call. This649 tells Flask that the status code of that page should be 404 which means650 not found. By default 200 is assumed which translates to: all went well.651 652+See :ref:`error-handlers` for more details.653+654 .. _about-responses:655 656 About Responses657 ---------------658 659 The return value from a view function is automatically converted into a660 response object for you. If the return value is a string it's converted661 into a response object with the string as response body, a ``200 OK``673-status code and a ``text/html`` mimetype. The logic that Flask applies to662+status code and a :mimetype:`text/html` mimetype. The logic that Flask applies to663 converting return values into response objects is as follows:664 665 1. If a response object of the correct type is returned it's directly666 returned from the view.1 unmodified line668 default parameters.669 3. 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.674 4. If none of that works, Flask will assume the return value is a675 valid WSGI application and convert that into a response object.676 677 If you want to get hold of the resulting response object inside the view678 you can use the :func:`~flask.make_response` function.679 691-Imagine you have a view like this:680+Imagine you have a view like this::681 693-.. sourcecode:: python694-682 @app.errorhandler(404)683 def not_found(error):684 return render_template('error.html'), 404685 686 You just need to wrap the return expression with687 :func:`~flask.make_response` and get the response object to modify it, then701-return it:688+return it::689 703-.. sourcecode:: python704-690 @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 lines723 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 lines746 747 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::751 767- >>> 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'755 771- 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.757 758 A note on cookie-based sessions: Flask will take the values you put into the759 session object and serialize them into a cookie. If you are finding some760 values do not persist across requests, cookies are indeed enabled, and you are761 not getting a clear error message, check the size of the cookie in your page762 responses compared to the size supported by web browsers.763 764+Besides the default client-side based sessions, if you want to handle765+sessions on the server-side instead, there are several766+Flask extensions that support this.767 768 Message Flashing769 ----------------770 34 unmodified lines805 app.logger.error('An error occurred')806 807 The attached :attr:`~flask.Flask.logger` is a standard logging808 :class:`~logging.Logger`, so head over to the official `logging821-documentation <http://docs.python.org/library/logging.html>`_ for more809+documentation <https://docs.python.org/library/logging.html>`_ for more810 information.811 812+Read more on :ref:`application-errors`.813+814 Hooking in WSGI Middlewares815 ---------------------------816 817 If you want to add a WSGI middleware to your application you can wrap the3 unmodified lines821 822 from werkzeug.contrib.fixers import LighttpdCGIRootFix823 app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)824 835-.. _quickstart_deployment:825+Using Flask Extensions826+----------------------827 828+Extensions are packages that help you accomplish common tasks. For829+example, Flask-SQLAlchemy provides SQLAlchemy support that makes it simple830+and easy to use with Flask.831+832+For more on Flask extensions, have a look at :ref:`extensions`.833+834 Deploying to a Web Server835 -------------------------836 840-Ready to deploy your new Flask app? To wrap up the quickstart, you can841-immediately deploy to a hosted platform, all of which offer a free plan for842-small projects:843-844-- `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/>`_847-848-Other places where you can host your Flask app:849-850-- `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/>`_853-854-If you manage your own hosts and would like to host yourself, see the chapter855-on :ref:`deployment`.837+Ready to deploy your new Flask app? Go to :ref:`deployment`.modified:docs/reqcontext.rst+4 added-4 removed
35 unmodified lines36 us a :class:`~flask.ctx.RequestContext`:37 38 >>> ctx = app.test_request_context('/?next=http://example.com/')39 40-This context can be used in two ways. Either with the `with` statement40+This context can be used in two ways. Either with the ``with`` statement41 or by calling the :meth:`~flask.ctx.RequestContext.push` and42 :meth:`~flask.ctx.RequestContext.pop` methods:43 44 >>> ctx.push()23 unmodified lines68 def wsgi_app(self, environ):69 with self.request_context(environ):70 try:71 response = self.full_dispatch_request()72- except Exception, e:72+ except Exception as e:73 response = self.make_response(self.handle_exception(e))74 return response(environ, start_response)75 76 The method :meth:`~Flask.request_context` returns a new77 :class:`~flask.ctx.RequestContext` object and uses it in combination with78-the `with` statement to bind the context. Everything that is called from79-the same thread from this point onwards until the end of the `with`78+the ``with`` statement to bind the context. Everything that is called from79+the same thread from this point onwards until the end of the ``with``80 statement will have access to the request globals (:data:`flask.request`81 and others).82 83 The request context internally works like a stack: The topmost level on140 unmodified linesmodified:docs/security.rst+13 added-82 removed
13 unmodified lines14 it JavaScript) into the context of a website. To remedy this, developers15 have to properly escape text so that it cannot include arbitrary HTML16 tags. For more information on that have a look at the Wikipedia article17 on `Cross-Site Scripting18-<http://en.wikipedia.org/wiki/Cross-site_scripting>`_.18+<https://en.wikipedia.org/wiki/Cross-site_scripting>`_.19 20 Flask configures Jinja2 to automatically escape all values unless21 explicitly told otherwise. This should rule out all XSS problems caused22 in templates, but there are still other places where you have to be1 unmodified line24 25 - 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 lines69 don't keep that in mind, some people might be able to trick your70 application's users with social engineering to do stupid things without71 them knowing.72 73-Say you have a specific URL that, when you sent `POST` requests to will74-delete a user's profile (say `http://example.com/user/delete`). If an73+Say you have a specific URL that, when you sent ``POST`` requests to will74+delete a user's profile (say ``http://example.com/user/delete``). If an75 attacker now creates a page that sends a post request to that page with76-some JavaScript they just has to trick some users to load that page and76+some JavaScript they just have to trick some users to load that page and77 their profiles will end up being deleted.78 79 Imagine you were to run Facebook with millions of concurrent users and80 someone would send out links to images of little kittens. When users13 unmodified lines94 95 JSON Security96 -------------97 98-.. admonition:: ECMAScript 5 Changes98+In Flask 0.10 and lower, :func:`~flask.jsonify` did not serialize top-level99+arrays to JSON. This was because of a security vulnerability in ECMAScript 4.100 100- Starting with ECMAScript 5 the behavior of literals changed. Now they101- are not constructed with the constructor of ``Array`` and others, but102- with the builtin constructor of ``Array`` which closes this particular103- attack vector.104-105-JSON itself is a high-level serialization format, so there is barely106-anything that could cause security problems, right? You can't declare107-recursive structures that could cause problems and the only thing that108-could possibly break are very large responses that can cause some kind of109-denial of service at the receiver's side.110-111-However there is a catch. Due to how browsers work the CSRF issue comes112-up with JSON unfortunately. Fortunately there is also a weird part of the113-JavaScript specification that can be used to solve that problem easily and114-Flask is kinda doing that for you by preventing you from doing dangerous115-stuff. Unfortunately that protection is only there for116-:func:`~flask.jsonify` so you are still at risk when using other ways to117-generate JSON.118-119-So what is the issue and how to avoid it? The problem are arrays at120-top-level in JSON. Imagine you send the following data out in a JSON121-request. Say that's exporting the names and email addresses of all your122-friends for a part of the user interface that is written in JavaScript.123-Not very uncommon:124-125-.. sourcecode:: javascript126-127- [128- {"username": "admin",129- "email": "admin@localhost"}130- ]131-132-And it is doing that of course only as long as you are logged in and only133-for you. And it is doing that for all `GET` requests to a certain URL,134-say the URL for that request is135-``http://example.com/api/get_friends.json``.136-137-So now what happens if a clever hacker is embedding this to his website138-and social engineers a victim to visiting his site:139-140-.. sourcecode:: html141-142- <script type=text/javascript>143- var captured = [];144- var oldArray = Array;145- function Array() {146- var obj = this, id = 0, capture = function(value) {147- obj.__defineSetter__(id++, capture);148- if (value)149- captured.push(value);150- };151- capture();152- }153- </script>154- <script type=text/javascript155- src=http://example.com/api/get_friends.json></script>156- <script type=text/javascript>157- Array = oldArray;158- // now we have all the data in the captured array.159- </script>160-161-If you know a bit of JavaScript internals you might know that it's162-possible to patch constructors and register callbacks for setters. An163-attacker can use this (like above) to get all the data you exported in164-your JSON file. The browser will totally ignore the ``application/json``165-mimetype if ``text/javascript`` is defined as content type in the script166-tag and evaluate that as JavaScript. Because top-level array elements are167-allowed (albeit useless) and we hooked in our own constructor, after that168-page loaded the data from the JSON response is in the `captured` array.169-170-Because it is a syntax error in JavaScript to have an object literal171-(``{...}``) toplevel an attacker could not just do a request to an172-external URL with the script tag to load up the data. So what Flask does173-is to only allow objects as toplevel elements when using174-:func:`~flask.jsonify`. Make sure to do the same when using an ordinary175-JSON generate function.101+ECMAScript 5 closed this vulnerability, so only extremely old browsers are102+still vulnerable. All of these browsers have `other more serious103+vulnerabilities104+<https://github.com/pallets/flask/issues/248#issuecomment-59934857>`_, so105+this behavior was changed and :func:`~flask.jsonify` now supports serializing106+arrays.added:docs/server.rst+52 added
1+.. _server:2+3+Development Server4+==================5+6+.. currentmodule:: flask7+8+Starting with Flask 0.11 there are multiple built-in ways to run a9+development server. The best one is the :command:`flask` command line utility10+but you can also continue using the :meth:`Flask.run` method.11+12+Command Line13+------------14+15+The :command:`flask` command line script (:ref:`cli`) is strongly recommended for16+development because it provides a superior reload experience due to how it17+loads the application. The basic usage is like this::18+19+ $ export FLASK_APP=my_application20+ $ export FLASK_DEBUG=121+ $ flask run22+23+This will enable the debugger, the reloader and then start the server on24+*http://localhost:5000/*.25+26+The individual features of the server can be controlled by passing more27+arguments to the ``run`` option. For instance the reloader can be28+disabled::29+30+ $ flask run --no-reload31+32+In Code33+-------34+35+The alternative way to start the application is through the36+:meth:`Flask.run` method. This will immediately launch a local server37+exactly the same way the :command:`flask` script does.38+39+Example::40+41+ if __name__ == '__main__':42+ app.run()43+44+This works well for the common case but it does not work well for45+development which is why from Flask 0.11 onwards the :command:`flask`46+method is recommended. The reason for this is that due to how the reload47+mechanism works there are some bizarre side-effects (like executing48+certain code twice, sometimes crashing without message or dying when a49+syntax or import error happens).50+51+It is however still a perfectly valid method for invoking a non automatic52+reloading application.modified:docs/shell.rst+12 added-2 removed
24 unmodified lines25 26 Generally it's recommended that you read the :ref:`request-context`27 chapter of the documentation first.28 29+Command Line Interface30+----------------------31+32+Starting with Flask 0.11 the recommended way to work with the shell is the33+``flask shell`` command which does a lot of this automatically for you.34+For instance the shell is automatically initialized with a loaded35+application context.36+37+For more information see :ref:`cli`.38+39 Creating a Request Context40 --------------------------41 42 The easiest way to create a proper request context from the shell is by1 unmodified line44 us a :class:`~flask.ctx.RequestContext`:45 46 >>> ctx = app.test_request_context()47 38-Normally you would use the `with` statement to make this request object48+Normally you would use the ``with`` statement to make this request object49 active, 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 lines97 with stuff you want to star import into your interactive session. There98 you could also define some more helper methods for common things such as99 initializing the database, dropping tables etc.100 91-Just put them into a module (like `shelltools` and import from there):101+Just put them into a module (like `shelltools`) and import from there:102 103 >>> from shelltools import *modified:docs/signals.rst+13 added-175 removed
17 unmodified lines18 more. Also keep in mind that signals are intended to notify subscribers19 and should not encourage subscribers to modify data. You will notice that20 there are signals that appear to do the same thing like some of the21 builtin decorators do (eg: :data:`~flask.request_started` is very similar22-to :meth:`~flask.Flask.before_request`). There are however difference in23-how they work. The core :meth:`~flask.Flask.before_request` handler for24-example is executed in a specific order and is able to abort the request22+to :meth:`~flask.Flask.before_request`). However, there are differences in23+how they work. The core :meth:`~flask.Flask.before_request` handler, for24+example, is executed in a specific order and is able to abort the request25 early by returning a response. In contrast all signal handlers are26 executed in undefined order and do not modify any data.27 28 The big advantage of signals over handlers is that you can safely29-subscribe to them for the split of a second. These temporary29+subscribe to them for just a split second. These temporary30 subscriptions are helpful for unittesting for example. Say you want to31 know what templates were rendered as part of a request: signals allow you32 to do exactly that.33 7 unmodified lines41 signal, you can use the :meth:`~blinker.base.Signal.disconnect` method.42 43 For all core Flask signals, the sender is the application that issued the44 signal. When you subscribe to a signal, be sure to also provide a sender45-unless you really want to listen for signals of all applications. This is45+unless you really want to listen for signals from all applications. This is46 especially true if you are developing an extension.47 48-Here for example a helper context manager that can be used to figure out49-in a unittest which templates were rendered and what variables were passed48+For example, here is a helper context manager that can be used in a unittest49+to determine which templates were rendered and what variables were passed50 to the template::51 52 from flask import template_rendered53 from contextlib import contextmanager22 unmodified lines76 Make sure to subscribe with an extra ``**extra`` argument so that your77 calls don't fail if Flask introduces new arguments to the signals.78 79 All the template rendering in the code issued by the application `app`80-in the body of the `with` block will now be recorded in the `templates`80+in the body of the ``with`` block will now be recorded in the `templates`81 variable. Whenever a template is rendered, the template object as well as82 context are appended to it.83 84 Additionally 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 to86 temporarily subscribe a function to a signal with a context manager on87 its own. Because the return value of the context manager cannot be88-specified that way one has to pass the list in as argument::88+specified that way, you have to pass the list in as an argument::89 90 from flask import template_rendered91 92 def captured_templates(app, recorded, **extra):54 unmodified lines147 def save(self):148 model_saved.send(self)149 150 Try to always pick a good sender. If you have a class that is emitting a151-signal, pass `self` as sender. If you emitting a signal from a random151+signal, pass ``self`` as sender. If you are emitting a signal from a random152 function, you can pass ``current_app._get_current_object()`` as sender.153 154 .. admonition:: Passing Proxies as Senders155 27 unmodified lines183 184 Core Signals185 ------------186 187-.. when modifying this list, also update the one in api.rst187+Take a look at :ref:`core-signals-list` for a list of all builtin signals.188 189-The following signals exist in Flask:189 191-.. data:: flask.template_rendered192- :noindex:193-194- 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`).197-198- Example subscriber::199-200- 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)204-205- from flask import template_rendered206- template_rendered.connect(log_template_renders, app)207-208-.. data:: flask.request_started209- :noindex:210-211- 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`.215-216- Example subscriber::217-218- def log_request(sender, **extra):219- sender.logger.debug('Request context is set up')220-221- from flask import request_started222- request_started.connect(log_request, app)223-224-.. data:: flask.request_finished225- :noindex:226-227- This signal is sent right before the response is sent to the client.228- It is passed the response to be sent named `response`.229-230- Example subscriber::231-232- def log_response(sender, response, **extra):233- sender.logger.debug('Request context is about to close down. '234- 'Response: %s', response)235-236- from flask import request_finished237- request_finished.connect(log_response, app)238-239-.. data:: flask.got_request_exception240- :noindex:241-242- 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`.246-247- Example subscriber::248-249- def log_exception(sender, exception, **extra):250- sender.logger.debug('Got exception during processing: %s', exception)251-252- from flask import got_request_exception253- got_request_exception.connect(log_exception, app)254-255-.. data:: flask.request_tearing_down256- :noindex:257-258- 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.262-263- Example subscriber::264-265- def close_db_connection(sender, **extra):266- session.close()267-268- from flask import request_tearing_down269- request_tearing_down.connect(close_db_connection, app)270-271- 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.274-275-.. data:: flask.appcontext_tearing_down276- :noindex:277-278- 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.282-283- Example subscriber::284-285- def close_db_connection(sender, **extra):286- session.close()287-288- from flask import appcontext_tearing_down289- appcontext_tearing_down.connect(close_db_connection, app)290-291- This will also be passed an `exc` keyword argument that has a reference292- to the exception that caused the teardown if there was one.293-294-.. data:: flask.appcontext_pushed295- :noindex:296-297- 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.301-302- Example usage::303-304- from contextlib import contextmanager305- from flask import appcontext_pushed306-307- @contextmanager308- def user_set(app, user):309- def handler(sender, **kwargs):310- g.user = user311- with appcontext_pushed.connected_to(handler, app):312- yield313-314- And in the testcode::315-316- 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'321-322- .. versionadded:: 0.10323-324-.. data:: flask.appcontext_popped325- :noindex:326-327- 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.330-331- .. versionadded:: 0.10332-333-334-.. data:: flask.message_flashed335- :noindex:336-337- This signal is sent when the application is flashing a message. The338- messages is sent as `message` keyword argument and the category as339- `category`.340-341- Example subscriber::342-343- recorded = []344- def record(sender, message, category, **extra):345- recorded.append((message, category))346-347- from flask import message_flashed348- message_flashed.connect(record, app)349-350- .. versionadded:: 0.10351-352-.. _blinker: http://pypi.python.org/pypi/blinker190+.. _blinker: https://pypi.python.org/pypi/blinkermodified:docs/styleguide.rst+2 added-2 removed
106 unmodified lines107 Comparisons: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)113 114 Negated containment checks:115 use ``foo not in bar`` instead of ``not foo in bar``50 unmodified lines166 is on its own line.167 """168 169 Module header:170- The module header consists of an utf-8 encoding declaration (if non170+ The module header consists of a utf-8 encoding declaration (if non171 ASCII letters are used, but it is recommended all the time) and a172 standard docstring::173 174 # -*- coding: utf-8 -*-26 unmodified linesmodified:docs/templating.rst+9 added-6 removed
7 unmodified lines8 9 This section only gives a very quick introduction into how Jinja210 is integrated into Flask. If you want information on the template11 engine's syntax itself, head over to the official `Jinja2 Template12-Documentation <http://jinja.pocoo.org/2/documentation/templates>`_ for12+Documentation <http://jinja.pocoo.org/docs/templates>`_ for13 more information.14 15 Jinja Setup16 -----------17 18 Unless customized, Jinja2 is configured by Flask as follows:19 20 - 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 by78 unmodified lines107 This function converts the given object into JSON representation. This108 is for example very helpful if you try to generate JavaScript on the109 fly.110 108- 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:114 115 .. sourcecode:: html+jinja116 117 <script type=text/javascript>3 unmodified lines121 Controlling Autoescaping122 ------------------------123 124 Autoescaping is the concept of automatically escaping special characters122-of you. Special characters in the sense of HTML (or XML, and thus XHTML)125+for you. Special characters in the sense of HTML (or XML, and thus XHTML)126 are ``&``, ``>``, ``<``, ``"`` as well as ``'``. Because these characters127 carry specific meanings in documents on their own you have to replace them128 by so called "entities" if you want to use them for text. Not doing so129 would not only cause user frustration by the inability to use these1 unmodified line131 :ref:`xss`)132 133 Sometimes however you will need to disable autoescaping in templates.134 This can be the case if you want to explicitly inject HTML into pages, for132-example if they come from a system that generate secure HTML like a135+example if they come from a system that generates secure HTML like a136 markdown to HTML converter.137 138 There are three ways to accomplish that:139 86 unmodified linesmodified:docs/testing.rst+45 added-40 removed
9 unmodified lines10 improve existing code and developers of untested applications tend to11 become pretty paranoid. If an application has automated tests, you can12 safely make changes and instantly know if anything breaks.13 14-Flask provides a way to test your application by exposing the Werkzeug 14+Flask provides a way to test your application by exposing the Werkzeug15 test :class:`~werkzeug.test.Client` and handling the context locals for you.16 You can then use that with your favourite testing solution. In this documentation17 we will use the :mod:`unittest` package that comes pre-installed with Python.18 19 The Application20 ---------------21 22-First, we need an application to test; we will use the application from 23-the :ref:`tutorial`. If you don't have that application yet, get the 22+First, we need an application to test; we will use the application from23+the :ref:`tutorial`. If you don't have that application yet, get the24 sources from `the examples`_.25 26 .. _the examples:27- http://github.com/mitsuhiko/flask/tree/master/examples/flaskr/27+ https://github.com/pallets/flask/tree/master/examples/flaskr/28 29 The Testing Skeleton30 --------------------31 32-In order to test the application, we add a second module 33-(`flaskr_tests.py`) and create a unittest skeleton there::32+In order to test the application, we add a second module33+(:file:`flaskr_tests.py`) and create a unittest skeleton there::34 35 import os36- import flaskr36+ from flaskr import flaskr37 import unittest38 import tempfile39 40 class FlaskrTestCase(unittest.TestCase):41 42 def setUp(self):43 self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()44- flaskr.app.config['TESTING'] = True44+ flaskr.app.testing = True45 self.app = flaskr.app.test_client()46+ with flaskr.app.app_context():46- flaskr.init_db()47+ flaskr.init_db()48 49 def tearDown(self):50 os.close(self.db_fd)51 os.unlink(flaskr.app.config['DATABASE'])2 unmodified lines54 unittest.main()55 56 The code in the :meth:`~unittest.TestCase.setUp` method creates a new test57 client and initializes a new database. This function is called before57-each individual test function is run. To delete the database after the 58+each individual test function is run. To delete the database after the59 test, we close the file and remove it from the filesystem in the60 :meth:`~unittest.TestCase.tearDown` method. Additionally during setup the60-``TESTING`` config flag is activated. What it does is disabling the error61+``TESTING`` config flag is activated. What it does is disable the error62 catching during request handling so that you get better error reports when63 performing test requests against the application.64 64-This test client will give us a simple interface to the application. We can 65-trigger test requests to the application, and the client will also keep track 65+This test client will give us a simple interface to the application. We can66+trigger test requests to the application, and the client will also keep track67 of cookies for us.68 69 Because SQLite3 is filesystem-based we can easily use the tempfile module70 to create a temporary database and initialize it. The17 unmodified lines88 89 The First Test90 --------------91 91-Now it's time to start testing the functionality of the application. 92-Let's check that the application shows "No entries here so far" if we 92+Now it's time to start testing the functionality of the application.93+Let's check that the application shows "No entries here so far" if we94 access the root of the application (``/``). To do this, we add a new95 test method to our class, like this::96 97 class FlaskrTestCase(unittest.TestCase):98 99 def setUp(self):100 self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()101+ flaskr.app.testing = True102 self.app = flaskr.app.test_client()103+ with flaskr.app.app_context():101- flaskr.init_db()104+ flaskr.init_db()105 106 def tearDown(self):107 os.close(self.db_fd)108 os.unlink(flaskr.app.config['DATABASE'])109 110 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.data113 111-Notice that our test functions begin with the word `test`; this allows 112-:mod:`unittest` to automatically identify the method as a test to run. 114+Notice that our test functions begin with the word `test`; this allows115+:mod:`unittest` to automatically identify the method as a test to run.116 114-By using `self.app.get` we can send an HTTP `GET` request to the application with 115-the given path. The return value will be a :class:`~flask.Flask.response_class` object. 117+By using `self.app.get` we can send an HTTP ``GET`` request to the application with118+the given path. The return value will be a :class:`~flask.Flask.response_class` object.119 We can now use the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect117-the return value (as string) from the application. In this case, we ensure that 120+the return value (as string) from the application. In this case, we ensure that121 ``'No entries here so far'`` is part of the output.122 123 Run it again and you should see one passing test::124 8 unmodified lines133 ------------------134 135 The majority of the functionality of our application is only available for136 the administrative user, so we need a way to log our test client in and out134-of the application. To do this, we fire some requests to the login and logout 135-pages with the required form data (username and password). And because the 137+of the application. To do this, we fire some requests to the login and logout138+pages with the required form data (username and password). And because the139 login and logout pages redirect, we tell the client to `follow_redirects`.140 141 Add the following two methods to your `FlaskrTestCase` class::142 10 unmodified lines153 invalid credentials. Add this new test to the class::154 155 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.data164 165 Test Adding Messages166 --------------------167 5 unmodified lines173 rv = self.app.post('/add', data=dict(174 title='<Hello>',175 text='<strong>HTML</strong> allowed here'176 ), follow_redirects=True)174- assert 'No entries here so far' not in rv.data175- assert '<Hello>' 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'<Hello>' in rv.data179+ assert b'<strong>HTML</strong> allowed here' in rv.data180 181 Here we check that HTML is allowed in the text but not in the title,182 which is the intended behavior.183 11 unmodified lines195 suite.196 197 198 .. _MiniTwit Example:196- http://github.com/mitsuhiko/flask/tree/master/examples/minitwit/199+ https://github.com/pallets/flask/tree/master/examples/minitwit/200 201 202 Other Testing Tricks203 --------------------204 205 Besides using the test client as shown above, there is also the206 :meth:`~flask.Flask.test_request_context` method that can be used204-in combination with the `with` statement to activate a request context207+in combination with the ``with`` statement to activate a request context208 temporarily. With this you can access the :class:`~flask.request`,209 :class:`~flask.g` and :class:`~flask.session` objects like in view210 functions. Here is a full example that demonstrates this approach::211 212+ import flask213+214 app = flask.Flask(__name__)215 216 with app.test_request_context('/?name=Peter'):217 assert flask.request.path == '/'6 unmodified lines224 there does not seem to be a good way to do that, consider switching to225 application factories (see :ref:`app-factories`).226 227 Note however that if you are using a test request context, the223-:meth:`~flask.Flask.before_request` functions are not automatically called224-same for :meth:`~flask.Flask.after_request` functions. However228+:meth:`~flask.Flask.before_request` and :meth:`~flask.Flask.after_request`229+functions are not called automatically. However230 :meth:`~flask.Flask.teardown_request` functions are indeed executed when226-the test request context leaves the `with` block. If you do want the231+the test request context leaves the ``with`` block. If you do want the232 :meth:`~flask.Flask.before_request` functions to be called as well, you233 need to call :meth:`~flask.Flask.preprocess_request` yourself::234 235 app = flask.Flask(__name__)39 unmodified lines275 g.user = user276 return user277 278 For a test it would be nice to override this user from the outside without274-having to change some code. This can trivially be accomplished with279+having to change some code. This can be accomplished with280 hooking the :data:`flask.appcontext_pushed` signal::281 282 from contextlib import contextmanager278- from flask import appcontext_pushed283+ from flask import appcontext_pushed, g284 285 @contextmanager286 def user_set(app, user):287 def handler(sender, **kwargs):23 unmodified lines311 312 Sometimes it is helpful to trigger a regular request but still keep the313 context around for a little longer so that additional introspection can314 happen. 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::316 317 app = flask.Flask(__name__)318 319 with app.test_client() as c:320 rv = c.get('/?tequila=42')321 assert request.args['tequila'] == '42'322 323 If you were to use just the :meth:`~flask.Flask.test_client` without319-the `with` block, the `assert` would fail with an error because `request`324+the ``with`` block, the ``assert`` would fail with an error because `request`325 is no longer available (because you are trying to use it outside of the actual request).326 327 328 Accessing and Modifying Sessions29 unmodified linesmodified:docs/upgrading.rst+124 added-24 removed
12 unmodified lines13 This section of the documentation enumerates all the changes in Flask from14 release to release and how you can change your code to have a painless15 updating experience.16 17-If you want to use the `easy_install` command to upgrade your Flask18-installation, make sure to pass it the ``-U`` parameter::17+Use the :command:`pip` command to upgrade your existing Flask installation by18+providing the ``--upgrade`` parameter::19 20- $ easy_install -U Flask20+ $ pip install --upgrade Flask21 22+.. _upgrading-to-012:23+24+Version 0.1225+------------26+27+Changes to send_file28+````````````````````29+30+The ``filename`` is no longer automatically inferred from file-like objects.31+This means that the following code will no longer automatically have32+``X-Sendfile`` support, etag generation or MIME-type guessing::33+34+ response = send_file(open('/path/to/file.txt'))35+36+Any of the following is functionally equivalent::37+38+ fname = '/path/to/file.txt'39+40+ # Just pass the filepath directly41+ response = send_file(fname)42+43+ # Set the MIME-type and ETag explicitly44+ response = send_file(open(fname), mimetype='text/plain')45+ response.set_etag(...)46+47+ # Set `attachment_filename` for MIME-type guessing48+ # ETag still needs to be manually set49+ response = send_file(open(fname), attachment_filename=fname)50+ response.set_etag(...)51+52+The reason for this is that some file-like objects have an invalid or even53+misleading ``name`` attribute. Silently swallowing errors in such cases was not54+a satisfying solution.55+56+Additionally the default of falling back to ``application/octet-stream`` has57+been restricted. If Flask can't guess one or the user didn't provide one, the58+function fails if no filename information was provided.59+60+.. _upgrading-to-011:61+62+Version 0.1163+------------64+65+0.11 is an odd release in the Flask release cycle because it was supposed66+to be the 1.0 release. However because there was such a long lead time up67+to the release we decided to push out a 0.11 release first with some68+changes removed to make the transition easier. If you have been tracking69+the master branch which was 1.0 you might see some unexpected changes.70+71+In case you did track the master branch you will notice that :command:`flask --app`72+is removed now. You need to use the environment variable to specify an73+application.74+75+Debugging76+`````````77+78+Flask 0.11 removed the ``debug_log_format`` attribute from Flask79+applications. Instead the new ``LOGGER_HANDLER_POLICY`` configuration can80+be used to disable the default log handlers and custom log handlers can be81+set up.82+83+Error handling84+``````````````85+86+The behavior of error handlers was changed.87+The precedence of handlers used to be based on the decoration/call order of88+:meth:`~flask.Flask.errorhandler` and89+:meth:`~flask.Flask.register_error_handler`, respectively.90+Now the inheritance hierarchy takes precedence and handlers for more91+specific exception classes are executed instead of more general ones.92+See :ref:`error-handlers` for specifics.93+94+Trying to register a handler on an instance now raises :exc:`ValueError`.95+96+.. note::97+98+ There used to be a logic error allowing you to register handlers99+ only for exception *instances*. This was unintended and plain wrong,100+ and therefore was replaced with the intended behavior of registering101+ handlers only using exception classes and HTTP error codes.102+103+Templating104+``````````105+106+The :func:`~flask.templating.render_template_string` function has changed to107+autoescape template variables by default. This better matches the behavior108+of :func:`~flask.templating.render_template`.109+110+Extension imports111+`````````````````112+113+Extension imports of the form ``flask.ext.foo`` are deprecated, you should use114+``flask_foo``.115+116+The old form still works, but Flask will issue a117+``flask.exthook.ExtDeprecationWarning`` for each extension you import the old118+way. We also provide a migration utility called `flask-ext-migrate119+<https://github.com/pallets/flask-ext-migrate>`_ that is supposed to120+automatically rewrite your imports for this.121+122 .. _upgrading-to-010:123 124 Version 0.10125 ------------16 unmodified lines142 when there is no request context yet but an application context. The old143 ``flask.Flask.request_globals_class`` attribute was renamed to144 :attr:`flask.Flask.app_ctx_globals_class`.145 46-.. _Flask-OldSessions: http://packages.python.org/Flask-OldSessions/146+.. _Flask-OldSessions: https://pythonhosted.org/Flask-OldSessions/147 148 Version 0.9149 -----------150 12 unmodified lines163 If you maintain an extension that was using :data:`~flask._request_ctx_stack`164 before, please consider changing to :data:`~flask._app_ctx_stack` if it makes165 sense for your extension. For instance, the app context stack makes sense for166 extensions which connect to databases. Using the app context stack instead of67-the request context stack will make extensions more readily handle use cases 167+the request context stack will make extensions more readily handle use cases168 outside of requests.169 170 Version 0.8171 -----------172 173 Flask introduced a new session interface system. We also noticed that74-there was a naming collision between `flask.session` the module that174+there was a naming collision between ``flask.session`` the module that175 implements sessions and :data:`flask.session` which is the global session176 object. With that introduction we moved the implementation details for177 the session system into a new module called :mod:`flask.sessions`. If you178 used the previously undocumented session support we urge you to upgrade.2 unmodified lines181 :exc:`~werkzeug.exceptions.BadRequest` exception instead of letting the182 default :exc:`ValueError` bubble up. This has the advantage that you no183 longer have to handle that error to avoid an internal server error showing184 up for the user. If you were catching this down explicitly in the past85-as `ValueError` you will need to change this.185+as :exc:`ValueError` you will need to change this.186 187 Due to a bug in the test client Flask 0.7 did not trigger teardown188 handlers when the test client was used in a with statement. This was89-since fixed but might require some changes in your testsuites if you189+since fixed but might require some changes in your test suites if you190 relied on this behavior.191 192 Version 0.7193 -----------3 unmodified lines197 applications with Flask. Because we want to make upgrading as easy as198 possible we tried to counter the problems arising from these changes by199 providing a script that can ease the transition.200 101-The script scans your whole application and generates an unified diff with201+The script scans your whole application and generates a unified diff with202 changes it assumes are safe to apply. However as this is an automated203 tool it won't be able to find all use cases and it might miss some. We204 internally spread a lot of deprecation warnings all over the place to make205 it easy to find pieces of code that it was unable to upgrade.8 unmodified lines214 215 To apply the upgrade script do the following:216 217 1. Download the script: `flask-07-upgrade.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>`_219 2. Run it in the directory of your application::220 221 python flask-07-upgrade.py > patchfile.diff222 2 unmodified lines225 226 patch -p1 < patchfile.diff227 228 5. 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.235 236 Please note that deprecation warnings are disabled by default starting237 with Python 2.7. In order to see the deprecation warnings that might be238 emitted you have to enabled them with the :mod:`warnings` module.239 140-If you are working with windows and you lack the `patch` command line240+If you are working with windows and you lack the ``patch`` command line241 utility you can get it as part of various Unix runtime environments for242 windows including cygwin, msysgit or ming32. Also source control systems243 like svn, hg or git have builtin support for applying unified diffs as244 generated by the tool. Check the manual of your version control system8 unmodified lines253 before, you should catch them with :exc:`RuntimeError` now.254 255 Additionally the :func:`~flask.send_file` function is now issuing256 deprecation warnings if you depend on functionality that will be removed157-in Flask 1.0. Previously it was possible to use etags and mimetypes257+in Flask 0.11. Previously it was possible to use etags and mimetypes258 when file objects were passed. This was unreliable and caused issues259 for a few setups. If you get a deprecation warning, make sure to260 update your application to work with either filenames there or disable261 etag attaching and attach them yourself.85 unmodified lines347 applications automatically, but there might be some cases where it fails348 to upgrade. What changed?349 350 - 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.374 275-If you continue to use the `Module` object which is deprecated, Flask will375+If you continue to use the ``Module`` object which is deprecated, Flask will376 restore the previous behavior as good as possible. However we strongly377 recommend upgrading to the new blueprints as they provide a lot of useful378 improvement such as the ability to attach a blueprint multiple times,379 blueprint specific error handlers and a lot more.5 unmodified lines385 Flask 0.6 comes with a backwards incompatible change which affects the386 order of after-request handlers. Previously they were called in the order387 of the registration, now they are called in reverse order. This change388 was made so that Flask behaves more like people expected it to work and289-how other systems handle request pre- and postprocessing. If you389+how other systems handle request pre- and post-processing. If you390 depend on the order of execution of post-request functions, be sure to391 change the order.392 393 Another change that breaks backwards compatibility is that context394 processors will no longer override values passed directly to the template295-rendering function. If for example `request` is as variable passed395+rendering function. If for example ``request`` is as variable passed396 directly to the template, the default context processor will not override397 it with the current request object. This makes it easier to extend398 context processors later to inject additional variables without breaking399 existing template not expecting them.17 unmodified lines417 functionality might come back in future releases if there is demand418 for this feature. Removing support for this makes the Flask internal419 code easier to understand and fixes a couple of small issues that make420 debugging harder than necessary.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.424 425 Version 0.447 unmodified linesmodified:docs/views.rst+2 added-2 removed
44 unmodified lines45 :meth:`~flask.views.View.as_view` class method. The string you pass to46 that function is the name of the endpoint that view will then have. But47 this by itself is not helpful, so let's refactor the code a bit::48 49- 49+50 from flask.views import View51 52 class ListView(View):53 16 unmodified lines70 return User.query.all()71 72 This of course is not that helpful for such a small example, but it's good73 enough to explain the basic principle. When you have a class-based view74-the question comes up what `self` points to. The way this works is that74+the question comes up what ``self`` points to. The way this works is that75 whenever the request is dispatched a new instance of the class is created76 and the :meth:`~flask.views.View.dispatch_request` method is called with77 the parameters from the URL rule. The class itself is instantiated with78 the parameters passed to the :meth:`~flask.views.View.as_view` function.159 unmodified linesmodified: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 linesdeleted:examples/blueprintexample/blueprintexample_test.py-36 removed
1-# -*- coding: utf-8 -*-2-"""3- Blueprint Example Tests4- ~~~~~~~~~~~~~~5-6- Tests the Blueprint example app7-"""8-import blueprintexample9-import unittest10-11-12-class BlueprintExampleTestCase(unittest.TestCase):13-14- 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- 35-if __name__ == '__main__':36- unittest.main()modified:examples/blueprintexample/blueprintexample.py+3 added-4 removed
2 unmodified lines3 4 app = Flask(__name__)5 app.register_blueprint(simple_page)6 # Blueprint can be registered many times7-app.register_blueprint(simple_page, url_prefix='/pages') 7+app.register_blueprint(simple_page, url_prefix='/pages')8 9-10-if __name__ == '__main__':11- app.run(debug=True)9+if __name__=='__main__':10+ app.run()added:examples/blueprintexample/test_blueprintexample.py+33 added
1+# -*- coding: utf-8 -*-2+"""3+ Blueprint Example Tests4+ ~~~~~~~~~~~~~~5+6+ Tests the Blueprint example app7+"""8+import pytest9+10+import blueprintexample11+12+13+@pytest.fixture14+def client():15+ return blueprintexample.app.test_client()16+17+18+def test_urls(client):19+ r = client.get('/')20+ assert r.status_code == 20021+22+ r = client.get('/hello')23+ assert r.status_code == 20024+25+ r = client.get('/world')26+ assert r.status_code == 20027+28+ # second blueprint instance29+ r = client.get('/pages/hello')30+ assert r.status_code == 20031+32+ r = client.get('/pages/world')33+ assert r.status_code == 200added:examples/flaskr/flaskr/static/style.css+18 added
1+body { font-family: sans-serif; background: #eee; }2+a, h1, h2 { color: #377BA8; }3+h1, h2 { font-family: 'Georgia', serif; margin: 0; }4+h1 { border-bottom: 2px solid #eee; }5+h2 { font-size: 1.2em; }6+7+.page { margin: 2em auto; width: 35em; border: 5px solid #ccc;8+ padding: 0.8em; background: white; }9+.entries { list-style: none; margin: 0; padding: 0; }10+.entries li { margin: 0.8em 1.2em; }11+.entries li h2 { margin-left: -1em; }12+.add-entry { font-size: 0.9em; border-bottom: 1px solid #ccc; }13+.add-entry dl { font-weight: bold; }14+.metanav { text-align: right; font-size: 0.8em; padding: 0.3em;15+ margin-bottom: 1em; background: #fafafa; }16+.flash { background: #CEE5F5; padding: 0.5em;17+ border: 1px solid #AACBE2; }18+.error { background: #F0D6D6; padding: 0.5em; }added:examples/flaskr/flaskr/templates/layout.html+17 added
1+<!doctype html>2+<title>Flaskr</title>3+<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">4+<div class="page">5+ <h1>Flaskr</h1>6+ <div class="metanav">7+ {% if not session.logged_in %}8+ <a href="{{ url_for('login') }}">log in</a>9+ {% else %}10+ <a href="{{ url_for('logout') }}">log out</a>11+ {% endif %}12+ </div>13+ {% for message in get_flashed_messages() %}14+ <div class="flash">{{ message }}</div>15+ {% endfor %}16+ {% block body %}{% endblock %}17+</div>added:examples/flaskr/flaskr/templates/login.html+14 added
1+{% extends "layout.html" %}2+{% block body %}3+ <h2>Login</h2>4+ {% if error %}<p class="error"><strong>Error:</strong> {{ error }}{% endif %}5+ <form action="{{ url_for('login') }}" method="post">6+ <dl>7+ <dt>Username:8+ <dd><input type="text" name="username">9+ <dt>Password:10+ <dd><input type="password" name="password">11+ <dd><input type="submit" value="Login">12+ </dl>13+ </form>14+{% endblock %}added:examples/flaskr/flaskr/templates/show_entries.html+21 added
1+{% extends "layout.html" %}2+{% block body %}3+ {% if session.logged_in %}4+ <form action="{{ url_for('add_entry') }}" method="post" class="add-entry">5+ <dl>6+ <dt>Title:7+ <dd><input type="text" size="30" name="title">8+ <dt>Text:9+ <dd><textarea name="text" rows="5" cols="40"></textarea>10+ <dd><input type="submit" value="Share">11+ </dl>12+ </form>13+ {% endif %}14+ <ul class="entries">15+ {% for entry in entries %}16+ <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}</li>17+ {% else %}18+ <li><em>Unbelievable. No entries here so far</em></li>19+ {% endfor %}20+ </ul>21+{% endblock %}added:examples/flaskr/flaskr/__init__.py+1 added
1+from .flaskr import appadded:examples/flaskr/flaskr/flaskr.py+110 added
1+# -*- coding: utf-8 -*-2+"""3+ Flaskr4+ ~~~~~~5+6+ A microblog example application written as Flask tutorial with7+ Flask and sqlite3.8+9+ :copyright: (c) 2015 by Armin Ronacher.10+ :license: BSD, see LICENSE for more details.11+"""12+13+import os14+from sqlite3 import dbapi2 as sqlite315+from flask import Flask, request, session, g, redirect, url_for, abort, \16+ render_template, flash17+18+19+# create our little application :)20+app = Flask(__name__)21+22+# Load default config and override config from an environment variable23+app.config.update(dict(24+ DATABASE=os.path.join(app.root_path, 'flaskr.db'),25+ DEBUG=True,26+ SECRET_KEY='development key',27+ USERNAME='admin',28+ PASSWORD='default'29+))30+app.config.from_envvar('FLASKR_SETTINGS', silent=True)31+32+33+def connect_db():34+ """Connects to the specific database."""35+ rv = sqlite3.connect(app.config['DATABASE'])36+ rv.row_factory = sqlite3.Row37+ return rv38+39+40+def init_db():41+ """Initializes the database."""42+ db = get_db()43+ with app.open_resource('schema.sql', mode='r') as f:44+ db.cursor().executescript(f.read())45+ db.commit()46+47+48+@app.cli.command('initdb')49+def initdb_command():50+ """Creates the database tables."""51+ init_db()52+ print('Initialized the database.')53+54+55+def get_db():56+ """Opens a new database connection if there is none yet for the57+ current application context.58+ """59+ if not hasattr(g, 'sqlite_db'):60+ g.sqlite_db = connect_db()61+ return g.sqlite_db62+63+64+@app.teardown_appcontext65+def close_db(error):66+ """Closes the database again at the end of the request."""67+ if hasattr(g, 'sqlite_db'):68+ g.sqlite_db.close()69+70+71+@app.route('/')72+def show_entries():73+ db = get_db()74+ cur = db.execute('select title, text from entries order by id desc')75+ entries = cur.fetchall()76+ return render_template('show_entries.html', entries=entries)77+78+79+@app.route('/add', methods=['POST'])80+def add_entry():81+ if not session.get('logged_in'):82+ abort(401)83+ db = get_db()84+ db.execute('insert into entries (title, text) values (?, ?)',85+ [request.form['title'], request.form['text']])86+ db.commit()87+ flash('New entry was successfully posted')88+ return redirect(url_for('show_entries'))89+90+91+@app.route('/login', methods=['GET', 'POST'])92+def login():93+ error = None94+ if request.method == 'POST':95+ if request.form['username'] != app.config['USERNAME']:96+ error = 'Invalid username'97+ elif request.form['password'] != app.config['PASSWORD']:98+ error = 'Invalid password'99+ else:100+ session['logged_in'] = True101+ flash('You were logged in')102+ return redirect(url_for('show_entries'))103+ return render_template('login.html', error=error)104+105+106+@app.route('/logout')107+def logout():108+ session.pop('logged_in', None)109+ flash('You were logged out')110+ return redirect(url_for('show_entries'))added:examples/flaskr/flaskr/schema.sql+6 added
1+drop table if exists entries;2+create table entries (3+ id integer primary key autoincrement,4+ title text not null,5+ 'text' text not null6+);deleted:examples/flaskr/static/style.css-18 removed
1-body { font-family: sans-serif; background: #eee; }2-a, h1, h2 { color: #377BA8; }3-h1, h2 { font-family: 'Georgia', serif; margin: 0; }4-h1 { border-bottom: 2px solid #eee; }5-h2 { font-size: 1.2em; }6-7-.page { margin: 2em auto; width: 35em; border: 5px solid #ccc;8- padding: 0.8em; background: white; }9-.entries { list-style: none; margin: 0; padding: 0; }10-.entries li { margin: 0.8em 1.2em; }11-.entries li h2 { margin-left: -1em; }12-.add-entry { font-size: 0.9em; border-bottom: 1px solid #ccc; }13-.add-entry dl { font-weight: bold; }14-.metanav { text-align: right; font-size: 0.8em; padding: 0.3em;15- margin-bottom: 1em; background: #fafafa; }16-.flash { background: #CEE5F5; padding: 0.5em;17- border: 1px solid #AACBE2; }18-.error { background: #F0D6D6; padding: 0.5em; }deleted:examples/flaskr/templates/layout.html-17 removed
1-<!doctype html>2-<title>Flaskr</title>3-<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">4-<div class=page>5- <h1>Flaskr</h1>6- <div class=metanav>7- {% if not session.logged_in %}8- <a href="{{ url_for('login') }}">log in</a>9- {% else %}10- <a href="{{ url_for('logout') }}">log out</a>11- {% endif %}12- </div>13- {% for message in get_flashed_messages() %}14- <div class=flash>{{ message }}</div>15- {% endfor %}16- {% block body %}{% endblock %}17-</div>deleted:examples/flaskr/templates/login.html-14 removed
1-{% extends "layout.html" %}2-{% block body %}3- <h2>Login</h2>4- {% if error %}<p class=error><strong>Error:</strong> {{ error }}{% endif %}5- <form action="{{ url_for('login') }}" method=post>6- <dl>7- <dt>Username:8- <dd><input type=text name=username>9- <dt>Password:10- <dd><input type=password name=password>11- <dd><input type=submit value=Login>12- </dl>13- </form>14-{% endblock %}deleted:examples/flaskr/templates/show_entries.html-21 removed
1-{% extends "layout.html" %}2-{% block body %}3- {% if session.logged_in %}4- <form action="{{ url_for('add_entry') }}" method=post class=add-entry>5- <dl>6- <dt>Title:7- <dd><input type=text size=30 name=title>8- <dt>Text:9- <dd><textarea name=text rows=5 cols=40></textarea>10- <dd><input type=submit value=Share>11- </dl>12- </form>13- {% endif %}14- <ul class=entries>15- {% for entry in entries %}16- <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}17- {% else %}18- <li><em>Unbelievable. No entries here so far</em>19- {% endfor %}20- </ul>21-{% endblock %}added:examples/flaskr/tests/test_flaskr.py+76 added
1+# -*- coding: utf-8 -*-2+"""3+ Flaskr Tests4+ ~~~~~~~~~~~~5+6+ Tests the Flaskr application.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import os13+import tempfile14+import pytest15+from flaskr import flaskr16+17+18+@pytest.fixture19+def client(request):20+ db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()21+ flaskr.app.config['TESTING'] = True22+ client = flaskr.app.test_client()23+ with flaskr.app.app_context():24+ flaskr.init_db()25+26+ def teardown():27+ os.close(db_fd)28+ os.unlink(flaskr.app.config['DATABASE'])29+ request.addfinalizer(teardown)30+31+ return client32+33+34+def login(client, username, password):35+ return client.post('/login', data=dict(36+ username=username,37+ password=password38+ ), follow_redirects=True)39+40+41+def logout(client):42+ return client.get('/logout', follow_redirects=True)43+44+45+def test_empty_db(client):46+ """Start with a blank database."""47+ rv = client.get('/')48+ assert b'No entries here so far' in rv.data49+50+51+def test_login_logout(client):52+ """Make sure login and logout works"""53+ rv = login(client, flaskr.app.config['USERNAME'],54+ flaskr.app.config['PASSWORD'])55+ assert b'You were logged in' in rv.data56+ rv = logout(client)57+ assert b'You were logged out' in rv.data58+ rv = login(client, flaskr.app.config['USERNAME'] + 'x',59+ flaskr.app.config['PASSWORD'])60+ assert b'Invalid username' in rv.data61+ rv = login(client, flaskr.app.config['USERNAME'],62+ flaskr.app.config['PASSWORD'] + 'x')63+ assert b'Invalid password' in rv.data64+65+66+def test_messages(client):67+ """Test that messages work"""68+ login(client, flaskr.app.config['USERNAME'],69+ flaskr.app.config['PASSWORD'])70+ rv = client.post('/add', data=dict(71+ title='<Hello>',72+ text='<strong>HTML</strong> allowed here'73+ ), follow_redirects=True)74+ assert b'No entries here so far' not in rv.data75+ assert b'<Hello>' in rv.data76+ assert b'<strong>HTML</strong> allowed here' in rv.dataadded:examples/flaskr/.gitignore+2 added
1+flaskr.db2+.eggs/deleted:examples/flaskr/flaskr_tests.py-75 removed
1-# -*- coding: utf-8 -*-2-"""3- Flaskr Tests4- ~~~~~~~~~~~~5-6- Tests the Flaskr application.7-8- :copyright: (c) 2014 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-import os12-import flaskr13-import unittest14-import tempfile15-16-17-class FlaskrTestCase(unittest.TestCase):18-19- 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()25-26- 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'])30-31- def login(self, username, password):32- return self.app.post('/login', data=dict(33- username=username,34- password=password35- ), follow_redirects=True)36-37- def logout(self):38- return self.app.get('/logout', follow_redirects=True)39-40- # testing functions41-42- 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.data46-47- 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.data60-61- 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'<Hello>' in rv.data71- assert b'<strong>HTML</strong> allowed here' in rv.data72-73-74-if __name__ == '__main__':75- unittest.main()deleted:examples/flaskr/flaskr.py-109 removed
1-# -*- coding: utf-8 -*-2-"""3- Flaskr4- ~~~~~~5-6- A microblog example application written as Flask tutorial with7- Flask and sqlite3.8-9- :copyright: (c) 2014 by Armin Ronacher.10- :license: BSD, see LICENSE for more details.11-"""12-13-import os14-from sqlite3 import dbapi2 as sqlite315-from flask import Flask, request, session, g, redirect, url_for, abort, \16- render_template, flash17-18-19-# create our little application :)20-app = Flask(__name__)21-22-# Load default config and override config from an environment variable23-app.config.update(dict(24- DATABASE=os.path.join(app.root_path, 'flaskr.db'),25- DEBUG=True,26- SECRET_KEY='development key',27- USERNAME='admin',28- PASSWORD='default'29-))30-app.config.from_envvar('FLASKR_SETTINGS', silent=True)31-32-33-def connect_db():34- """Connects to the specific database."""35- rv = sqlite3.connect(app.config['DATABASE'])36- rv.row_factory = sqlite3.Row37- return rv38-39-40-def init_db():41- """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()47-48-49-def 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_db56-57-58-@app.teardown_appcontext59-def 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()63-64-65-@app.route('/')66-def 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)71-72-73-@app.route('/add', methods=['POST'])74-def 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'))83-84-85-@app.route('/login', methods=['GET', 'POST'])86-def 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)98-99-100-@app.route('/logout')101-def logout():102- session.pop('logged_in', None)103- flash('You were logged out')104- return redirect(url_for('show_entries'))105-106-107-if __name__ == '__main__':108- init_db()109- app.run()added:examples/flaskr/MANIFEST.in+3 added
1+graft flaskr/templates2+graft flaskr/static3+include flaskr/schema.sqlmodified:examples/flaskr/README+20 added-5 removed
11 unmodified lines12 1. edit the configuration in the flaskr.py file or13 export an FLASKR_SETTINGS environment variable14 pointing to a configuration file.15 16- 2. 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 directory17+18+ pip install --editable .19+20+ 3. Instruct flask to use the right application21+22+ export FLASK_APP=flaskr23+24+ 4. initialize the database with this command:25+26+ flask initdb27+28+ 5. now you can run flaskr:29+30+ flask run31+32+ the application will greet you on33+ http://localhost:5000/34+35 ~ Is it tested?36 22- 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
1-drop table if exists entries;2-create table entries (3- id integer primary key autoincrement,4- title text not null,5- 'text' text not null6-);added:examples/flaskr/setup.cfg+2 added
1+[tool:pytest]2+test=pytestadded:examples/flaskr/setup.py+16 added
1+from setuptools import setup2+3+setup(4+ name='flaskr',5+ packages=['flaskr'],6+ include_package_data=True,7+ install_requires=[8+ 'flask',9+ ],10+ setup_requires=[11+ 'pytest-runner',12+ ],13+ tests_require=[14+ 'pytest',15+ ],16+)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 lines25 });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 lines4 ~~~~~~~~~~~~~~5 6 A simple application that shows how Flask and jQuery get along.7 8- :copyright: (c) 2014 by Armin Ronacher.8+ :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 from flask import Flask, jsonify, render_template, request12 app = Flask(__name__)10 unmodified lines23 @app.route('/')24 def index():25 return render_template('index.html')26 27-27 if __name__ == '__main__':28 app.run()added:examples/minitwit/minitwit/static/style.css+178 added
1+body {2+ background: #CAECE9;3+ font-family: 'Trebuchet MS', sans-serif;4+ font-size: 14px;5+}6+7+a {8+ color: #26776F;9+}10+11+a:hover {12+ color: #333;13+}14+15+input[type="text"],16+input[type="password"] {17+ background: white;18+ border: 1px solid #BFE6E2;19+ padding: 2px;20+ font-family: 'Trebuchet MS', sans-serif;21+ font-size: 14px;22+ -moz-border-radius: 2px;23+ -webkit-border-radius: 2px;24+ color: #105751;25+}26+27+input[type="submit"] {28+ background: #105751;29+ border: 1px solid #073B36;30+ padding: 1px 3px;31+ font-family: 'Trebuchet MS', sans-serif;32+ font-size: 14px;33+ font-weight: bold;34+ -moz-border-radius: 2px;35+ -webkit-border-radius: 2px;36+ color: white;37+}38+39+div.page {40+ background: white;41+ border: 1px solid #6ECCC4;42+ width: 700px;43+ margin: 30px auto;44+}45+46+div.page h1 {47+ background: #6ECCC4;48+ margin: 0;49+ padding: 10px 14px;50+ color: white;51+ letter-spacing: 1px;52+ text-shadow: 0 0 3px #24776F;53+ font-weight: normal;54+}55+56+div.page div.navigation {57+ background: #DEE9E8;58+ padding: 4px 10px;59+ border-top: 1px solid #ccc;60+ border-bottom: 1px solid #eee;61+ color: #888;62+ font-size: 12px;63+ letter-spacing: 0.5px;64+}65+66+div.page div.navigation a {67+ color: #444;68+ font-weight: bold;69+}70+71+div.page h2 {72+ margin: 0 0 15px 0;73+ color: #105751;74+ text-shadow: 0 1px 2px #ccc;75+}76+77+div.page div.body {78+ padding: 10px;79+}80+81+div.page div.footer {82+ background: #eee;83+ color: #888;84+ padding: 5px 10px;85+ font-size: 12px;86+}87+88+div.page div.followstatus {89+ border: 1px solid #ccc;90+ background: #E3EBEA;91+ -moz-border-radius: 2px;92+ -webkit-border-radius: 2px;93+ padding: 3px;94+ font-size: 13px;95+}96+97+div.page ul.messages {98+ list-style: none;99+ margin: 0;100+ padding: 0;101+}102+103+div.page ul.messages li {104+ margin: 10px 0;105+ padding: 5px;106+ background: #F0FAF9;107+ border: 1px solid #DBF3F1;108+ -moz-border-radius: 5px;109+ -webkit-border-radius: 5px;110+ min-height: 48px;111+}112+113+div.page ul.messages p {114+ margin: 0;115+}116+117+div.page ul.messages li img {118+ float: left;119+ padding: 0 10px 0 0;120+}121+122+div.page ul.messages li small {123+ font-size: 0.9em;124+ color: #888;125+}126+127+div.page div.twitbox {128+ margin: 10px 0;129+ padding: 5px;130+ background: #F0FAF9;131+ border: 1px solid #94E2DA;132+ -moz-border-radius: 5px;133+ -webkit-border-radius: 5px;134+}135+136+div.page div.twitbox h3 {137+ margin: 0;138+ font-size: 1em;139+ color: #2C7E76;140+}141+142+div.page div.twitbox p {143+ margin: 0;144+}145+146+div.page div.twitbox input[type="text"] {147+ width: 585px;148+}149+150+div.page div.twitbox input[type="submit"] {151+ width: 70px;152+ margin-left: 5px;153+}154+155+ul.flashes {156+ list-style: none;157+ margin: 10px 10px 0 10px;158+ padding: 0;159+}160+161+ul.flashes li {162+ background: #B9F3ED;163+ border: 1px solid #81CEC6;164+ -moz-border-radius: 2px;165+ -webkit-border-radius: 2px;166+ padding: 4px;167+ font-size: 13px;168+}169+170+div.error {171+ margin: 10px 0;172+ background: #FAE4E4;173+ border: 1px solid #DD6F6F;174+ -moz-border-radius: 2px;175+ -webkit-border-radius: 2px;176+ padding: 4px;177+ font-size: 13px;178+}added:examples/minitwit/minitwit/templates/layout.html+32 added
1+<!doctype html>2+<title>{% block title %}Welcome{% endblock %} | MiniTwit</title>3+<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">4+<div class="page">5+ <h1>MiniTwit</h1>6+ <div class="navigation">7+ {% if g.user %}8+ <a href="{{ url_for('timeline') }}">my timeline</a> |9+ <a href="{{ url_for('public_timeline') }}">public timeline</a> |10+ <a href="{{ url_for('logout') }}">sign out [{{ g.user.username }}]</a>11+ {% else %}12+ <a href="{{ url_for('public_timeline') }}">public timeline</a> |13+ <a href="{{ url_for('register') }}">sign up</a> |14+ <a href="{{ url_for('login') }}">sign in</a>15+ {% endif %}16+ </div>17+ {% with flashes = get_flashed_messages() %}18+ {% if flashes %}19+ <ul class="flashes">20+ {% for message in flashes %}21+ <li>{{ message }}22+ {% endfor %}23+ </ul>24+ {% endif %}25+ {% endwith %}26+ <div class="body">27+ {% block body %}{% endblock %}28+ </div>29+ <div class="footer">30+ MiniTwit — A Flask Application31+ </div>32+</div>added:examples/minitwit/minitwit/templates/login.html+16 added
1+{% extends "layout.html" %}2+{% block title %}Sign In{% endblock %}3+{% block body %}4+ <h2>Sign In</h2>5+ {% if error %}<div class="error"><strong>Error:</strong> {{ error }}</div>{% endif %}6+ <form action="" method="post">7+ <dl>8+ <dt>Username:9+ <dd><input type="text" name="username" size="30" value="{{ request.form.username }}">10+ <dt>Password:11+ <dd><input type="password" name="password" size="30">12+ </dl>13+ <div class="actions"><input type="submit" value="Sign In"></div>14+ </form>15+{% endblock %}16+added:examples/minitwit/minitwit/templates/register.html+19 added
1+{% extends "layout.html" %}2+{% block title %}Sign Up{% endblock %}3+{% block body %}4+ <h2>Sign Up</h2>5+ {% if error %}<div class="error"><strong>Error:</strong> {{ error }}</div>{% endif %}6+ <form action="" method="post">7+ <dl>8+ <dt>Username:9+ <dd><input type="text" name="username" size="30" value="{{ request.form.username }}">10+ <dt>E-Mail:11+ <dd><input type="text" name="email" size="30" value="{{ request.form.email }}">12+ <dt>Password:13+ <dd><input type="password" name="password" size="30">14+ <dt>Password <small>(repeat)</small>:15+ <dd><input type="password" name="password2" size="30">16+ </dl>17+ <div class="actions"><input type="submit" value="Sign Up"></div>18+ </form>19+{% endblock %}added:examples/minitwit/minitwit/templates/timeline.html+49 added
1+{% extends "layout.html" %}2+{% block title %}3+ {% if request.endpoint == 'public_timeline' %}4+ Public Timeline5+ {% elif request.endpoint == 'user_timeline' %}6+ {{ profile_user.username }}'s Timeline7+ {% else %}8+ My Timeline9+ {% endif %}10+{% endblock %}11+{% block body %}12+ <h2>{{ self.title() }}</h2>13+ {% if g.user %}14+ {% if request.endpoint == 'user_timeline' %}15+ <div class="followstatus">16+ {% if g.user.user_id == profile_user.user_id %}17+ This is you!18+ {% elif followed %}19+ You are currently following this user.20+ <a class="unfollow" href="{{ url_for('unfollow_user', username=profile_user.username)21+ }}">Unfollow user</a>.22+ {% else %}23+ You are not yet following this user.24+ <a class="follow" href="{{ url_for('follow_user', username=profile_user.username)25+ }}">Follow user</a>.26+ {% endif %}27+ </div>28+ {% elif request.endpoint == 'timeline' %}29+ <div class="twitbox">30+ <h3>What's on your mind {{ g.user.username }}?</h3>31+ <form action="{{ url_for('add_message') }}" method="post">32+ <p><input type="text" name="text" size="60"><!--33+ --><input type="submit" value="Share">34+ </form>35+ </div>36+ {% endif %}37+ {% endif %}38+ <ul class="messages">39+ {% for message in messages %}40+ <li><img src="{{ message.email|gravatar(size=48) }}"><p>41+ <strong><a href="{{ url_for('user_timeline', username=message.username)42+ }}">{{ message.username }}</a></strong>43+ {{ message.text }}44+ <small>— {{ message.pub_date|datetimeformat }}</small>45+ {% else %}46+ <li><em>There's no message so far.</em>47+ {% endfor %}48+ </ul>49+{% endblock %}added:examples/minitwit/minitwit/__init__.py+1 added
1+from .minitwit import appadded:examples/minitwit/minitwit/minitwit.py+256 added
1+# -*- coding: utf-8 -*-2+"""3+ MiniTwit4+ ~~~~~~~~5+6+ A microblogging application written with Flask and sqlite3.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import time13+from sqlite3 import dbapi2 as sqlite314+from hashlib import md515+from datetime import datetime16+from flask import Flask, request, session, url_for, redirect, \17+ render_template, abort, g, flash, _app_ctx_stack18+from werkzeug import check_password_hash, generate_password_hash19+20+21+# configuration22+DATABASE = '/tmp/minitwit.db'23+PER_PAGE = 3024+DEBUG = True25+SECRET_KEY = 'development key'26+27+# create our little application :)28+app = Flask(__name__)29+app.config.from_object(__name__)30+app.config.from_envvar('MINITWIT_SETTINGS', silent=True)31+32+33+def get_db():34+ """Opens a new database connection if there is none yet for the35+ current application context.36+ """37+ top = _app_ctx_stack.top38+ if not hasattr(top, 'sqlite_db'):39+ top.sqlite_db = sqlite3.connect(app.config['DATABASE'])40+ top.sqlite_db.row_factory = sqlite3.Row41+ return top.sqlite_db42+43+44+@app.teardown_appcontext45+def close_database(exception):46+ """Closes the database again at the end of the request."""47+ top = _app_ctx_stack.top48+ if hasattr(top, 'sqlite_db'):49+ top.sqlite_db.close()50+51+52+def init_db():53+ """Initializes the database."""54+ db = get_db()55+ with app.open_resource('schema.sql', mode='r') as f:56+ db.cursor().executescript(f.read())57+ db.commit()58+59+60+@app.cli.command('initdb')61+def initdb_command():62+ """Creates the database tables."""63+ init_db()64+ print('Initialized the database.')65+66+67+def query_db(query, args=(), one=False):68+ """Queries the database and returns a list of dictionaries."""69+ cur = get_db().execute(query, args)70+ rv = cur.fetchall()71+ return (rv[0] if rv else None) if one else rv72+73+74+def get_user_id(username):75+ """Convenience method to look up the id for a username."""76+ rv = query_db('select user_id from user where username = ?',77+ [username], one=True)78+ return rv[0] if rv else None79+80+81+def format_datetime(timestamp):82+ """Format a timestamp for display."""83+ return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d @ %H:%M')84+85+86+def gravatar_url(email, size=80):87+ """Return the gravatar image for the given email address."""88+ return 'https://www.gravatar.com/avatar/%s?d=identicon&s=%d' % \89+ (md5(email.strip().lower().encode('utf-8')).hexdigest(), size)90+91+92+@app.before_request93+def before_request():94+ g.user = None95+ if 'user_id' in session:96+ g.user = query_db('select * from user where user_id = ?',97+ [session['user_id']], one=True)98+99+100+@app.route('/')101+def timeline():102+ """Shows a users timeline or if no user is logged in it will103+ redirect to the public timeline. This timeline shows the user's104+ messages as well as all the messages of followed users.105+ """106+ if not g.user:107+ return redirect(url_for('public_timeline'))108+ return render_template('timeline.html', messages=query_db('''109+ select message.*, user.* from message, user110+ where message.author_id = user.user_id and (111+ user.user_id = ? or112+ user.user_id in (select whom_id from follower113+ where who_id = ?))114+ order by message.pub_date desc limit ?''',115+ [session['user_id'], session['user_id'], PER_PAGE]))116+117+118+@app.route('/public')119+def public_timeline():120+ """Displays the latest messages of all users."""121+ return render_template('timeline.html', messages=query_db('''122+ select message.*, user.* from message, user123+ where message.author_id = user.user_id124+ order by message.pub_date desc limit ?''', [PER_PAGE]))125+126+127+@app.route('/<username>')128+def user_timeline(username):129+ """Display's a users tweets."""130+ profile_user = query_db('select * from user where username = ?',131+ [username], one=True)132+ if profile_user is None:133+ abort(404)134+ followed = False135+ if g.user:136+ followed = query_db('''select 1 from follower where137+ follower.who_id = ? and follower.whom_id = ?''',138+ [session['user_id'], profile_user['user_id']],139+ one=True) is not None140+ return render_template('timeline.html', messages=query_db('''141+ select message.*, user.* from message, user where142+ user.user_id = message.author_id and user.user_id = ?143+ order by message.pub_date desc limit ?''',144+ [profile_user['user_id'], PER_PAGE]), followed=followed,145+ profile_user=profile_user)146+147+148+@app.route('/<username>/follow')149+def follow_user(username):150+ """Adds the current user as follower of the given user."""151+ if not g.user:152+ abort(401)153+ whom_id = get_user_id(username)154+ if whom_id is None:155+ abort(404)156+ db = get_db()157+ db.execute('insert into follower (who_id, whom_id) values (?, ?)',158+ [session['user_id'], whom_id])159+ db.commit()160+ flash('You are now following "%s"' % username)161+ return redirect(url_for('user_timeline', username=username))162+163+164+@app.route('/<username>/unfollow')165+def unfollow_user(username):166+ """Removes the current user as follower of the given user."""167+ if not g.user:168+ abort(401)169+ whom_id = get_user_id(username)170+ if whom_id is None:171+ abort(404)172+ db = get_db()173+ db.execute('delete from follower where who_id=? and whom_id=?',174+ [session['user_id'], whom_id])175+ db.commit()176+ flash('You are no longer following "%s"' % username)177+ return redirect(url_for('user_timeline', username=username))178+179+180+@app.route('/add_message', methods=['POST'])181+def add_message():182+ """Registers a new message for the user."""183+ if 'user_id' not in session:184+ abort(401)185+ if request.form['text']:186+ db = get_db()187+ db.execute('''insert into message (author_id, text, pub_date)188+ values (?, ?, ?)''', (session['user_id'], request.form['text'],189+ int(time.time())))190+ db.commit()191+ flash('Your message was recorded')192+ return redirect(url_for('timeline'))193+194+195+@app.route('/login', methods=['GET', 'POST'])196+def login():197+ """Logs the user in."""198+ if g.user:199+ return redirect(url_for('timeline'))200+ error = None201+ if request.method == 'POST':202+ user = query_db('''select * from user where203+ username = ?''', [request.form['username']], one=True)204+ if user is None:205+ error = 'Invalid username'206+ elif not check_password_hash(user['pw_hash'],207+ request.form['password']):208+ error = 'Invalid password'209+ else:210+ flash('You were logged in')211+ session['user_id'] = user['user_id']212+ return redirect(url_for('timeline'))213+ return render_template('login.html', error=error)214+215+216+@app.route('/register', methods=['GET', 'POST'])217+def register():218+ """Registers the user."""219+ if g.user:220+ return redirect(url_for('timeline'))221+ error = None222+ if request.method == 'POST':223+ if not request.form['username']:224+ error = 'You have to enter a username'225+ elif not request.form['email'] or \226+ '@' not in request.form['email']:227+ error = 'You have to enter a valid email address'228+ elif not request.form['password']:229+ error = 'You have to enter a password'230+ elif request.form['password'] != request.form['password2']:231+ error = 'The two passwords do not match'232+ elif get_user_id(request.form['username']) is not None:233+ error = 'The username is already taken'234+ else:235+ db = get_db()236+ db.execute('''insert into user (237+ username, email, pw_hash) values (?, ?, ?)''',238+ [request.form['username'], request.form['email'],239+ generate_password_hash(request.form['password'])])240+ db.commit()241+ flash('You were successfully registered and can login now')242+ return redirect(url_for('login'))243+ return render_template('register.html', error=error)244+245+246+@app.route('/logout')247+def logout():248+ """Logs the user out."""249+ flash('You were logged out')250+ session.pop('user_id', None)251+ return redirect(url_for('public_timeline'))252+253+254+# add some filters to jinja255+app.jinja_env.filters['datetimeformat'] = format_datetime256+app.jinja_env.filters['gravatar'] = gravatar_urladded:examples/minitwit/minitwit/schema.sql+21 added
1+drop table if exists user;2+create table user (3+ user_id integer primary key autoincrement,4+ username text not null,5+ email text not null,6+ pw_hash text not null7+);8+9+drop table if exists follower;10+create table follower (11+ who_id integer,12+ whom_id integer13+);14+15+drop table if exists message;16+create table message (17+ message_id integer primary key autoincrement,18+ author_id integer not null,19+ text text not null,20+ pub_date integer21+);deleted:examples/minitwit/static/style.css-178 removed
1-body {2- background: #CAECE9;3- font-family: 'Trebuchet MS', sans-serif;4- font-size: 14px;5-}6-7-a {8- color: #26776F;9-}10-11-a:hover {12- color: #333;13-}14-15-input[type="text"],16-input[type="password"] {17- background: white;18- border: 1px solid #BFE6E2;19- padding: 2px;20- font-family: 'Trebuchet MS', sans-serif;21- font-size: 14px;22- -moz-border-radius: 2px;23- -webkit-border-radius: 2px;24- color: #105751;25-}26-27-input[type="submit"] {28- background: #105751;29- border: 1px solid #073B36;30- padding: 1px 3px;31- font-family: 'Trebuchet MS', sans-serif;32- font-size: 14px;33- font-weight: bold;34- -moz-border-radius: 2px;35- -webkit-border-radius: 2px;36- color: white;37-}38-39-div.page {40- background: white;41- border: 1px solid #6ECCC4;42- width: 700px;43- margin: 30px auto;44-}45-46-div.page h1 {47- background: #6ECCC4;48- margin: 0;49- padding: 10px 14px;50- color: white;51- letter-spacing: 1px;52- text-shadow: 0 0 3px #24776F;53- font-weight: normal;54-}55-56-div.page div.navigation {57- background: #DEE9E8;58- padding: 4px 10px;59- border-top: 1px solid #ccc;60- border-bottom: 1px solid #eee;61- color: #888;62- font-size: 12px;63- letter-spacing: 0.5px;64-}65-66-div.page div.navigation a {67- color: #444;68- font-weight: bold;69-}70-71-div.page h2 {72- margin: 0 0 15px 0;73- color: #105751;74- text-shadow: 0 1px 2px #ccc;75-}76-77-div.page div.body {78- padding: 10px;79-}80-81-div.page div.footer {82- background: #eee;83- color: #888;84- padding: 5px 10px;85- font-size: 12px;86-}87-88-div.page div.followstatus {89- border: 1px solid #ccc;90- background: #E3EBEA;91- -moz-border-radius: 2px;92- -webkit-border-radius: 2px;93- padding: 3px;94- font-size: 13px;95-}96-97-div.page ul.messages {98- list-style: none;99- margin: 0;100- padding: 0;101-}102-103-div.page ul.messages li {104- margin: 10px 0;105- padding: 5px;106- background: #F0FAF9;107- border: 1px solid #DBF3F1;108- -moz-border-radius: 5px;109- -webkit-border-radius: 5px;110- min-height: 48px;111-}112-113-div.page ul.messages p {114- margin: 0;115-}116-117-div.page ul.messages li img {118- float: left;119- padding: 0 10px 0 0;120-}121-122-div.page ul.messages li small {123- font-size: 0.9em;124- color: #888;125-}126-127-div.page div.twitbox {128- margin: 10px 0;129- padding: 5px;130- background: #F0FAF9;131- border: 1px solid #94E2DA;132- -moz-border-radius: 5px;133- -webkit-border-radius: 5px;134-}135-136-div.page div.twitbox h3 {137- margin: 0;138- font-size: 1em;139- color: #2C7E76;140-}141-142-div.page div.twitbox p {143- margin: 0;144-}145-146-div.page div.twitbox input[type="text"] {147- width: 585px;148-}149-150-div.page div.twitbox input[type="submit"] {151- width: 70px;152- margin-left: 5px;153-}154-155-ul.flashes {156- list-style: none;157- margin: 10px 10px 0 10px;158- padding: 0;159-}160-161-ul.flashes li {162- background: #B9F3ED;163- border: 1px solid #81CEC6;164- -moz-border-radius: 2px;165- -webkit-border-radius: 2px;166- padding: 4px;167- font-size: 13px;168-}169-170-div.error {171- margin: 10px 0;172- background: #FAE4E4;173- border: 1px solid #DD6F6F;174- -moz-border-radius: 2px;175- -webkit-border-radius: 2px;176- padding: 4px;177- font-size: 13px;178-}deleted:examples/minitwit/templates/layout.html-32 removed
1-<!doctype html>2-<title>{% block title %}Welcome{% endblock %} | MiniTwit</title>3-<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">4-<div class=page>5- <h1>MiniTwit</h1>6- <div class=navigation>7- {% if g.user %}8- <a href="{{ url_for('timeline') }}">my timeline</a> |9- <a href="{{ url_for('public_timeline') }}">public timeline</a> |10- <a href="{{ url_for('logout') }}">sign out [{{ g.user.username }}]</a>11- {% else %}12- <a href="{{ url_for('public_timeline') }}">public timeline</a> |13- <a href="{{ url_for('register') }}">sign up</a> |14- <a href="{{ url_for('login') }}">sign in</a>15- {% endif %}16- </div>17- {% with flashes = get_flashed_messages() %}18- {% if flashes %}19- <ul class=flashes>20- {% for message in flashes %}21- <li>{{ message }}22- {% endfor %}23- </ul>24- {% endif %}25- {% endwith %}26- <div class=body>27- {% block body %}{% endblock %}28- </div>29- <div class=footer>30- MiniTwit — A Flask Application31- </div>32-</div>deleted:examples/minitwit/templates/login.html-16 removed
1-{% extends "layout.html" %}2-{% block title %}Sign In{% endblock %}3-{% block body %}4- <h2>Sign In</h2>5- {% if error %}<div class=error><strong>Error:</strong> {{ error }}</div>{% endif %}6- <form action="" method=post>7- <dl>8- <dt>Username:9- <dd><input type=text name=username size=30 value="{{ request.form.username }}">10- <dt>Password:11- <dd><input type=password name=password size=30>12- </dl>13- <div class=actions><input type=submit value="Sign In"></div>14- </form>15-{% endblock %}16-deleted:examples/minitwit/templates/register.html-19 removed
1-{% extends "layout.html" %}2-{% block title %}Sign Up{% endblock %}3-{% block body %}4- <h2>Sign Up</h2>5- {% if error %}<div class=error><strong>Error:</strong> {{ error }}</div>{% endif %}6- <form action="" method=post>7- <dl>8- <dt>Username:9- <dd><input type=text name=username size=30 value="{{ request.form.username }}">10- <dt>E-Mail:11- <dd><input type=text name=email size=30 value="{{ request.form.email }}">12- <dt>Password:13- <dd><input type=password name=password size=30>14- <dt>Password <small>(repeat)</small>:15- <dd><input type=password name=password2 size=30>16- </dl>17- <div class=actions><input type=submit value="Sign Up"></div>18- </form>19-{% endblock %}deleted:examples/minitwit/templates/timeline.html-49 removed
1-{% extends "layout.html" %}2-{% block title %}3- {% if request.endpoint == 'public_timeline' %}4- Public Timeline5- {% elif request.endpoint == 'user_timeline' %}6- {{ profile_user.username }}'s Timeline7- {% else %}8- My Timeline9- {% endif %}10-{% endblock %}11-{% block body %}12- <h2>{{ self.title() }}</h2>13- {% if g.user %}14- {% if request.endpoint == 'user_timeline' %}15- <div class=followstatus>16- {% if g.user.user_id == profile_user.user_id %}17- This is you!18- {% elif followed %}19- You are currently following this user.20- <a class=unfollow href="{{ url_for('unfollow_user', username=profile_user.username)21- }}">Unfollow user</a>.22- {% else %}23- You are not yet following this user.24- <a class=follow href="{{ url_for('follow_user', username=profile_user.username)25- }}">Follow user</a>.26- {% endif %}27- </div>28- {% elif request.endpoint == 'timeline' %}29- <div class=twitbox>30- <h3>What's on your mind {{ g.user.username }}?</h3>31- <form action="{{ url_for('add_message') }}" method=post>32- <p><input type=text name=text size=60><!--33- --><input type=submit value="Share">34- </form>35- </div>36- {% endif %}37- {% endif %}38- <ul class=messages>39- {% for message in messages %}40- <li><img src="{{ message.email|gravatar(size=48) }}"><p>41- <strong><a href="{{ url_for('user_timeline', username=message.username)42- }}">{{ message.username }}</a></strong>43- {{ message.text }}44- <small>— {{ message.pub_date|datetimeformat }}</small>45- {% else %}46- <li><em>There's no message so far.</em>47- {% endfor %}48- </ul>49-{% endblock %}added:examples/minitwit/tests/test_minitwit.py+151 added
1+# -*- coding: utf-8 -*-2+"""3+ MiniTwit Tests4+ ~~~~~~~~~~~~~~5+6+ Tests the MiniTwit application.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+import os12+import tempfile13+import pytest14+from minitwit import minitwit15+16+17+@pytest.fixture18+def client(request):19+ db_fd, minitwit.app.config['DATABASE'] = tempfile.mkstemp()20+ client = minitwit.app.test_client()21+ with minitwit.app.app_context():22+ minitwit.init_db()23+24+ def teardown():25+ """Get rid of the database again after each test."""26+ os.close(db_fd)27+ os.unlink(minitwit.app.config['DATABASE'])28+ request.addfinalizer(teardown)29+ return client30+31+32+def register(client, username, password, password2=None, email=None):33+ """Helper function to register a user"""34+ if password2 is None:35+ password2 = password36+ if email is None:37+ email = username + '@example.com'38+ return client.post('/register', data={39+ 'username': username,40+ 'password': password,41+ 'password2': password2,42+ 'email': email,43+ }, follow_redirects=True)44+45+46+def login(client, username, password):47+ """Helper function to login"""48+ return client.post('/login', data={49+ 'username': username,50+ 'password': password51+ }, follow_redirects=True)52+53+54+def register_and_login(client, username, password):55+ """Registers and logs in in one go"""56+ register(client, username, password)57+ return login(client, username, password)58+59+60+def logout(client):61+ """Helper function to logout"""62+ return client.get('/logout', follow_redirects=True)63+64+65+def add_message(client, text):66+ """Records a message"""67+ rv = client.post('/add_message', data={'text': text},68+ follow_redirects=True)69+ if text:70+ assert b'Your message was recorded' in rv.data71+ return rv72+73+74+def test_register(client):75+ """Make sure registering works"""76+ rv = register(client, 'user1', 'default')77+ assert b'You were successfully registered ' \78+ b'and can login now' in rv.data79+ rv = register(client, 'user1', 'default')80+ assert b'The username is already taken' in rv.data81+ rv = register(client, '', 'default')82+ assert b'You have to enter a username' in rv.data83+ rv = register(client, 'meh', '')84+ assert b'You have to enter a password' in rv.data85+ rv = register(client, 'meh', 'x', 'y')86+ assert b'The two passwords do not match' in rv.data87+ rv = register(client, 'meh', 'foo', email='broken')88+ assert b'You have to enter a valid email address' in rv.data89+90+91+def test_login_logout(client):92+ """Make sure logging in and logging out works"""93+ rv = register_and_login(client, 'user1', 'default')94+ assert b'You were logged in' in rv.data95+ rv = logout(client)96+ assert b'You were logged out' in rv.data97+ rv = login(client, 'user1', 'wrongpassword')98+ assert b'Invalid password' in rv.data99+ rv = login(client, 'user2', 'wrongpassword')100+ assert b'Invalid username' in rv.data101+102+103+def test_message_recording(client):104+ """Check if adding messages works"""105+ register_and_login(client, 'foo', 'default')106+ add_message(client, 'test message 1')107+ add_message(client, '<test message 2>')108+ rv = client.get('/')109+ assert b'test message 1' in rv.data110+ assert b'<test message 2>' in rv.data111+112+113+def test_timelines(client):114+ """Make sure that timelines work"""115+ register_and_login(client, 'foo', 'default')116+ add_message(client, 'the message by foo')117+ logout(client)118+ register_and_login(client, 'bar', 'default')119+ add_message(client, 'the message by bar')120+ rv = client.get('/public')121+ assert b'the message by foo' in rv.data122+ assert b'the message by bar' in rv.data123+124+ # bar's timeline should just show bar's message125+ rv = client.get('/')126+ assert b'the message by foo' not in rv.data127+ assert b'the message by bar' in rv.data128+129+ # now let's follow foo130+ rv = client.get('/foo/follow', follow_redirects=True)131+ assert b'You are now following "foo"' in rv.data132+133+ # we should now see foo's message134+ rv = client.get('/')135+ assert b'the message by foo' in rv.data136+ assert b'the message by bar' in rv.data137+138+ # but on the user's page we only want the user's message139+ rv = client.get('/bar')140+ assert b'the message by foo' not in rv.data141+ assert b'the message by bar' in rv.data142+ rv = client.get('/foo')143+ assert b'the message by foo' in rv.data144+ assert b'the message by bar' not in rv.data145+146+ # now unfollow and check if that worked147+ rv = client.get('/foo/unfollow', follow_redirects=True)148+ assert b'You are no longer following "foo"' in rv.data149+ rv = client.get('/')150+ assert b'the message by foo' not in rv.data151+ assert b'the message by bar' in rv.dataadded:examples/minitwit/.gitignore+2 added
1+minitwit.db2+.eggs/added:examples/minitwit/MANIFEST.in+3 added
1+graft minitwit/templates2+graft minitwit/static3+include minitwit/schema.sqldeleted:examples/minitwit/minitwit_tests.py-149 removed
1-# -*- coding: utf-8 -*-2-"""3- MiniTwit Tests4- ~~~~~~~~~~~~~~5-6- Tests the MiniTwit application.7-8- :copyright: (c) 2014 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-import os12-import minitwit13-import unittest14-import tempfile15-16-17-class MiniTwitTestCase(unittest.TestCase):18-19- 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()24-25- 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'])29-30- # helper functions31-32- 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)44-45- 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)51-52- 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)56-57- def logout(self):58- """Helper function to logout"""59- return self.app.get('/logout', follow_redirects=True)60-61- 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 rv68-69- # testing functions70-71- 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.data86-87- 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.data97-98- 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'<test message 2>' in rv.data106-107- 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.data117-118- # 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.data122-123- # now let's follow foo124- rv = self.app.get('/foo/follow', follow_redirects=True)125- assert b'You are now following "foo"' in rv.data126-127- # 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.data131-132- # 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.data139-140- # now unfollow and check if that worked141- rv = self.app.get('/foo/unfollow', follow_redirects=True)142- assert b'You are no longer following "foo"' 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.data146-147-148-if __name__ == '__main__':149- unittest.main()deleted:examples/minitwit/minitwit.py-255 removed
1-# -*- coding: utf-8 -*-2-"""3- MiniTwit4- ~~~~~~~~5-6- A microblogging application written with Flask and sqlite3.7-8- :copyright: (c) 2014 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-12-import time13-from sqlite3 import dbapi2 as sqlite314-from hashlib import md515-from datetime import datetime16-from flask import Flask, request, session, url_for, redirect, \17- render_template, abort, g, flash, _app_ctx_stack18-from werkzeug import check_password_hash, generate_password_hash19-20-21-# configuration22-DATABASE = '/tmp/minitwit.db'23-PER_PAGE = 3024-DEBUG = True25-SECRET_KEY = 'development key'26-27-# create our little application :)28-app = Flask(__name__)29-app.config.from_object(__name__)30-app.config.from_envvar('MINITWIT_SETTINGS', silent=True)31-32-33-def get_db():34- """Opens a new database connection if there is none yet for the35- current application context.36- """37- top = _app_ctx_stack.top38- if not hasattr(top, 'sqlite_db'):39- top.sqlite_db = sqlite3.connect(app.config['DATABASE'])40- top.sqlite_db.row_factory = sqlite3.Row41- return top.sqlite_db42-43-44-@app.teardown_appcontext45-def close_database(exception):46- """Closes the database again at the end of the request."""47- top = _app_ctx_stack.top48- if hasattr(top, 'sqlite_db'):49- top.sqlite_db.close()50-51-52-def init_db():53- """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()59-60-61-def 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 rv66-67-68-def 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 None73-74-75-def format_datetime(timestamp):76- """Format a timestamp for display."""77- return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d @ %H:%M')78-79-80-def 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)84-85-86-@app.before_request87-def 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)92-93-94-@app.route('/')95-def 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]))110-111-112-@app.route('/public')113-def 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]))119-120-121-@app.route('/<username>')122-def 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)140-141-142-@app.route('/<username>/follow')143-def 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))156-157-158-@app.route('/<username>/unfollow')159-def 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))172-173-174-@app.route('/add_message', methods=['POST'])175-def 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'))187-188-189-@app.route('/login', methods=['GET', 'POST'])190-def 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)208-209-210-@app.route('/register', methods=['GET', 'POST'])211-def 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)238-239-240-@app.route('/logout')241-def 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'))246-247-248-# add some filters to jinja249-app.jinja_env.filters['datetimeformat'] = format_datetime250-app.jinja_env.filters['gravatar'] = gravatar_url251-252-253-if __name__ == '__main__':254- init_db()255- app.run()modified:examples/minitwit/README+18 added-7 removed
12 unmodified lines13 1. edit the configuration in the minitwit.py file or14 export an MINITWIT_SETTINGS environment variable15 pointing to a configuration file.16 17- 2. fire up a python shell and run this:17+ 2. install the app from the root of the project directory18 19- >>> from minitwit import init_db; init_db()19+ pip install --editable .20 21- 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:22+23+ export FLASK_APP=minitwit24+25+ 4. fire up a shell and run this:26+27+ flask initdb28+29+ 5. now you can run minitwit:30+31+ flask run32+33+ the application will greet you on34+ http://localhost:5000/35+36 ~ Is it tested?37 27- 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
1-drop table if exists user;2-create table user (3- user_id integer primary key autoincrement,4- username text not null,5- email text not null,6- pw_hash text not null7-);8-9-drop table if exists follower;10-create table follower (11- who_id integer,12- whom_id integer13-);14-15-drop table if exists message;16-create table message (17- message_id integer primary key autoincrement,18- author_id integer not null,19- text text not null,20- pub_date integer21-);added:examples/minitwit/setup.cfg+2 added
1+[aliases]2+test=pytestadded:examples/minitwit/setup.py+16 added
1+from setuptools import setup2+3+setup(4+ name='minitwit',5+ packages=['minitwit'],6+ include_package_data=True,7+ install_requires=[8+ 'flask',9+ ],10+ setup_requires=[11+ 'pytest-runner',12+ ],13+ tests_require=[14+ 'pytest',15+ ],16+)added:examples/patterns/largerapp/tests/test_largerapp.py+12 added
1+from yourapplication import app2+import pytest3+4+@pytest.fixture5+def client():6+ app.config['TESTING'] = True7+ client = app.test_client()8+ return client9+10+def test_index(client):11+ rv = client.get('/')12+ assert b"Hello World!" in rv.dataadded:examples/patterns/largerapp/yourapplication/static/style.css
added:examples/patterns/largerapp/yourapplication/templates/index.html
added:examples/patterns/largerapp/yourapplication/templates/layout.html
added:examples/patterns/largerapp/yourapplication/templates/login.html
added:examples/patterns/largerapp/yourapplication/__init__.py+4 added
1+from flask import Flask2+app = Flask(__name__)3+4+import yourapplication.viewsadded:examples/patterns/largerapp/yourapplication/views.py+5 added
1+from yourapplication import app2+3+@app.route('/')4+def index():5+ return 'Hello World!'added:examples/patterns/largerapp/setup.py+10 added
1+from setuptools import setup2+3+setup(4+ name='yourapplication',5+ packages=['yourapplication'],6+ include_package_data=True,7+ install_requires=[8+ 'flask',9+ ],10+)deleted:examples/persona/static/persona.js-52 removed
1-$(function() {2- /* convert the links into clickable buttons that go to the3- persona service */4- $('a.signin').on('click', function() {5- navigator.id.request({6- siteName: 'Flask Persona Example'7- });8- return false;9- });10-11- $('a.signout').on('click', function() {12- navigator.id.logout();13- return false;14- });15-16- /* watch persona state changes */17- navigator.id.watch({18- loggedInUser: $CURRENT_USER,19- onlogin: function(assertion) {20- /* because the login needs to verify the provided assertion21- with the persona service which requires an HTTP request,22- this could take a bit. To not confuse the user we show23- a progress box */24- var box = $('<div class=signinprogress></div>')25- .hide()26- .text('Please wait ...')27- .appendTo('body')28- .fadeIn('fast');29- $.ajax({30- type: 'POST',31- url: $URL_ROOT + '_auth/login',32- data: {assertion: assertion},33- success: function(res, status, xhr) { window.location.reload(); },34- error: function(xhr, status, err) {35- box.remove();36- navigator.id.logout();37- alert('Login failure: ' + err);38- }39- });40- },41- onlogout: function() {42- $.ajax({43- type: 'POST',44- url: $URL_ROOT + '_auth/logout',45- success: function(res, status, xhr) { window.location.reload(); },46- error: function(xhr, status, err) {47- alert('Logout failure: ' + err);48- }49- });50- }51- });52-});deleted:examples/persona/static/spinner.pngbinary
A binary file, deleted.
deleted:examples/persona/static/style.css-39 removed
1-html {2- background: #eee;3-}4-5-body {6- font-family: 'Verdana', sans-serif;7- font-size: 15px;8- margin: 30px auto;9- width: 720px;10- background: white;11- padding: 30px;12-}13-14-h1 {15- margin: 0;16-}17-18-h1, h2, a {19- color: #d00;20-}21-22-div.authbar {23- background: #eee;24- padding: 0 15px;25- margin: 10px -15px;26- line-height: 25px;27- height: 25px;28- vertical-align: middle;29-}30-31-div.signinprogress {32- position: fixed;33- top: 0;34- left: 0;35- right: 0;36- bottom: 0;37- background: rgba(255, 255, 255, 0.8) url(spinner.png) center center no-repeat;38- font-size: 0;39-}deleted:examples/persona/templates/index.html-23 removed
1-{% extends "layout.html" %}2-{% block title %}Welcome{% endblock %}3-{% block body %}4- <h2>Welcome</h2>5- <p>6- This is a small example application that shows how to integrate7- Mozilla's persona signin service into a Flask application.8- <p>9- The advantage of persona over your own login system is that the10- password is managed outside of your application and you get11- a verified mail address as primary identifier for your user.12- <p>13- In this example nothing is actually stored on the server, it14- just takes over the email address from the persona verifier15- and stores it in a session.16- {% if g.user %}17- <p>18- You are now logged in as <strong>{{ g.user }}</strong>19- {% else %}20- <p>21- To sign in click the sign in button above.22- {% endif %}23-{% endblock %}deleted:examples/persona/templates/layout.html-27 removed
1-<!doctype html>2-<title>{% block title %}{% endblock %} | Flask Persona Example</title>3-<meta http-equiv="X-UA-Compatible" content="IE=Edge">4-<script src="{{ config.PERSONA_JS }}"></script>5-<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>6-<script>7- /* the url root is useful for doing HTTP requests */8- var $URL_ROOT = {{ request.url_root|tojson }};9-10- /* we store the current user here so that the persona11- javascript support knows about the current user */12- var $CURRENT_USER = {{ g.user|tojson }};13-</script>14-<script src="{{ url_for('static', filename='persona.js') }}"></script>15-<link rel=stylesheet href="{{ url_for('static', filename='style.css') }}">16-<header>17- <h1>Mozilla Persona Example</h1>18- <div class=authbar>19- {% if g.user %}20- Signed in as <em>{{ g.user }}</em>21- (<a href="#" class=signout>Sign out</a>)22- {% else %}23- Not signed in. <a href="#" class=signin>Sign in</a>24- {% endif %}25- </div>26-</header>27-{% block body %}{% endblock %}deleted:examples/persona/persona.py-59 removed
1-from flask import Flask, render_template, session, request, abort, g2-3-import requests4-5-6-app = Flask(__name__)7-app.config.update(8- DEBUG=True,9- SECRET_KEY='my development key',10- PERSONA_JS='https://login.persona.org/include.js',11- PERSONA_VERIFIER='https://verifier.login.persona.org/verify',12-)13-app.config.from_envvar('PERSONA_SETTINGS', silent=True)14-15-16-@app.before_request17-def get_current_user():18- g.user = None19- email = session.get('email')20- if email is not None:21- g.user = email22-23-24-@app.route('/')25-def index():26- """Just a generic index page to show."""27- return render_template('index.html')28-29-30-@app.route('/_auth/login', methods=['GET', 'POST'])31-def login_handler():32- """This is used by the persona.js file to kick off the33- verification securely from the server side. If all is okay34- the email address is remembered on the server.35- """36- resp = requests.post(app.config['PERSONA_VERIFIER'], data={37- 'assertion': request.form['assertion'],38- 'audience': request.host_url,39- }, verify=True)40- if resp.ok:41- verification_data = resp.json()42- if verification_data['status'] == 'okay':43- session['email'] = verification_data['email']44- return 'OK'45-46- abort(400)47-48-49-@app.route('/_auth/logout', methods=['POST'])50-def logout_handler():51- """This is what persona.js will call to sign the user52- out again.53- """54- session.clear()55- return 'OK'56-57-58-if __name__ == '__main__':59- app.run()modified:flask/ext/__init__.py+1 added-1 removed
12 unmodified lines13 14 We're switching from namespace packages because it was just too painful for15 everybody involved.16 17- :copyright: (c) 2014 by Armin Ronacher.17+ :copyright: (c) 2015 by Armin Ronacher.18 :license: BSD, see LICENSE for more details.19 """20 21 8 unmodified linesdeleted: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
1-I'm nesteddeleted: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}} Maildeleted: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
1-Admin Filedeleted:flask/testsuite/test_apps/blueprintapp/apps/admin/templates/admin/index.html-1 removed
1-Hello from the Admindeleted:flask/testsuite/test_apps/blueprintapp/apps/admin/__init__.py-15 removed
1-from flask import Blueprint, render_template2-3-admin = Blueprint('admin', __name__, url_prefix='/admin',4- template_folder='templates',5- static_folder='static')6-7-8-@admin.route('/')9-def index():10- return render_template('admin/index.html')11-12-13-@admin.route('/index2')14-def index2():15- return render_template('./admin/index.html')deleted:flask/testsuite/test_apps/blueprintapp/apps/frontend/templates/frontend/index.html-1 removed
1-Hello from the Frontenddeleted:flask/testsuite/test_apps/blueprintapp/apps/frontend/__init__.py-8 removed
1-from flask import Blueprint, render_template2-3-frontend = Blueprint('frontend', __name__, template_folder='templates')4-5-6-@frontend.route('/')7-def 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
1-from flask import Flask2-3-app = Flask(__name__)4-from blueprintapp.apps.admin import admin5-from blueprintapp.apps.frontend import frontend6-app.register_blueprint(admin)7-app.register_blueprint(frontend)deleted:flask/testsuite/test_apps/config_package_app/__init__.py-4 removed
1-import os2-import flask3-here = os.path.abspath(os.path.dirname(__file__))4-app = flask.Flask(__name__)deleted:flask/testsuite/test_apps/flask_broken/__init__.py-2 removed
1-import flask.ext.broken.b2-import missing_moduledeleted:flask/testsuite/test_apps/flask_broken/b.py
deleted:flask/testsuite/test_apps/flask_newext_package/__init__.py-1 removed
1-ext_id = 'newext_package'deleted:flask/testsuite/test_apps/flask_newext_package/submodule.py-2 removed
1-def test_function():2- return 42deleted:flask/testsuite/test_apps/flaskext/oldext_package/__init__.py-1 removed
1-ext_id = 'oldext_package'deleted:flask/testsuite/test_apps/flaskext/oldext_package/submodule.py-2 removed
1-def test_function():2- return 42deleted:flask/testsuite/test_apps/flaskext/__init__.py
deleted:flask/testsuite/test_apps/flaskext/oldext_simple.py-1 removed
1-ext_id = 'oldext_simple'deleted:flask/testsuite/test_apps/lib/python2.5/site-packages/site_package/__init__.py-3 removed
1-import flask2-3-app = flask.Flask(__name__)deleted:flask/testsuite/test_apps/lib/python2.5/site-packages/site_app.py-3 removed
1-import flask2-3-app = 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
1-Admin Filedeleted:flask/testsuite/test_apps/moduleapp/apps/admin/templates/index.html-1 removed
1-Hello from the Admindeleted:flask/testsuite/test_apps/moduleapp/apps/admin/__init__.py-14 removed
1-from flask import Module, render_template2-3-4-admin = Module(__name__, url_prefix='/admin')5-6-7-@admin.route('/')8-def index():9- return render_template('admin/index.html')10-11-12-@admin.route('/index2')13-def index2():14- return render_template('./admin/index.html')deleted:flask/testsuite/test_apps/moduleapp/apps/frontend/templates/index.html-1 removed
1-Hello from the Frontenddeleted:flask/testsuite/test_apps/moduleapp/apps/frontend/__init__.py-9 removed
1-from flask import Module, render_template2-3-4-frontend = Module(__name__)5-6-7-@frontend.route('/')8-def 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
1-from flask import Flask2-3-app = Flask(__name__)4-from moduleapp.apps.admin import admin5-from moduleapp.apps.frontend import frontend6-app.register_module(admin)7-app.register_module(frontend)deleted:flask/testsuite/test_apps/path/installed_package/__init__.py-3 removed
1-import flask2-3-app = flask.Flask(__name__)deleted:flask/testsuite/test_apps/subdomaintestmodule/static/hello.txt-1 removed
1-Hello Subdomaindeleted:flask/testsuite/test_apps/subdomaintestmodule/__init__.py-4 removed
1-from flask import Module2-3-4-mod = Module(__name__, 'foo', subdomain='foo')deleted:flask/testsuite/test_apps/config_module_app.py-4 removed
1-import os2-import flask3-here = os.path.abspath(os.path.dirname(__file__))4-app = flask.Flask(__name__)deleted:flask/testsuite/test_apps/flask_newext_simple.py-1 removed
1-ext_id = 'newext_simple'deleted:flask/testsuite/test_apps/importerror.py-2 removed
1-# NoImportsTestCase2-raise NotImplementedErrordeleted:flask/testsuite/test_apps/main_app.py-4 removed
1-import flask2-3-# Test Flask initialization with main module.4-app = flask.Flask('__main__')deleted:flask/testsuite/__init__.py-252 removed
1-# -*- coding: utf-8 -*-2-"""3- flask.testsuite4- ~~~~~~~~~~~~~~~5-6- Tests Flask itself. The majority of Flask is already tested7- as part of Werkzeug.8-9- :copyright: (c) 2014 by Armin Ronacher.10- :license: BSD, see LICENSE for more details.11-"""12-13-from __future__ import print_function14-15-import os16-import sys17-import flask18-import warnings19-import unittest20-from functools import update_wrapper21-from contextlib import contextmanager22-from werkzeug.utils import import_string, find_modules23-from flask._compat import reraise, StringIO24-25-26-def 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')33-34- 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)44-45-46-def 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()52-53-54-def 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- )67-68-69-@contextmanager70-def 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)74-75- 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_showwarning87-88-89-@contextmanager90-def 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_stderr98-99-100-def 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)108-109-110-class 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- """115-116- 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, [])123-124- def setup(self):125- pass126-127- def teardown(self):128- pass129-130- def setUp(self):131- self.setup()132-133- def tearDown(self):134- unittest.TestCase.tearDown(self)135- self.ensure_clean_request_context()136- self.teardown()137-138- def assert_equal(self, x, y):139- return self.assertEqual(x, y)140-141- 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)147-148- def assert_true(self, x, msg=None):149- self.assertTrue(x, msg)150-151- def assert_false(self, x, msg=None):152- self.assertFalse(x, msg)153-154- def assert_in(self, x, y):155- self.assertIn(x, y)156-157- def assert_not_in(self, x, y):158- self.assertNotIn(x, y)159-160- def assert_isinstance(self, obj, cls):161- self.assertIsInstance(obj, cls)162-163- 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)166-167- def assertNotIn(self, x, y):168- assert x not in y, "%r unexpectedly in %r" % (x, y)169-170- def assertIsInstance(self, x, y):171- assert isinstance(x, y), "not isinstance(%r, %r)" % (x, y)172-173-174-class _ExceptionCatcher(object):175-176- def __init__(self, test_case, exc_type):177- self.test_case = test_case178- self.exc_type = exc_type179-180- def __enter__(self):181- return self182-183- 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 True191-192-193-class 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- """201-202- def getRootSuite(self):203- return suite()204-205- def loadTestsFromName(self, name, module=None):206- root = self.getRootSuite()207- if name == 'suite':208- return root209-210- 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)217-218- if not all_tests:219- raise LookupError('could not find test case for "%s"' % name)220-221- 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 rv227-228-229-def setup_path():230- add_to_path(os.path.abspath(os.path.join(231- os.path.dirname(__file__), 'test_apps')))232-233-234-def 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 suite245-246-247-def 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- ~~~~~~~~~~~~~~~~~~~~~~5-6- Tests the application context.7-8- :copyright: (c) 2014 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-12-import flask13-import unittest14-from flask.testsuite import FlaskTestCase15-16-17-class AppContextTestCase(FlaskTestCase):18-19- def test_basic_url_generation(self):20- app = flask.Flask(__name__)21- app.config['SERVER_NAME'] = 'localhost'22- app.config['PREFERRED_URL_SCHEME'] = 'https'23-24- @app.route('/')25- def index():26- pass27-28- with app.app_context():29- rv = flask.url_for('index')30- self.assert_equal(rv, 'https://localhost/')31-32- 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')37-38- def test_url_generation_without_context_fails(self):39- with self.assert_raises(RuntimeError):40- flask.url_for('index')41-42- 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)47-48- 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)53-54- 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)60-61- with app.app_context():62- pass63-64- self.assert_equal(cleanup_stuff, [None])65-66- 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)72-73- try:74- raise Exception('dummy')75- except Exception:76- pass77-78- with app.app_context():79- pass80-81- self.assert_equal(cleanup_stuff, [None])82-83- 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')92-93- 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'])113-114-115-def suite():116- suite = unittest.TestSuite()117- suite.addTest(unittest.makeSuite(AppContextTestCase))118- return suitedeleted:flask/testsuite/basic.py-1405 removed
1-# -*- coding: utf-8 -*-2-"""3- flask.testsuite.basic4- ~~~~~~~~~~~~~~~~~~~~~5-6- The basic functionality.7-8- :copyright: (c) 2014 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-12-import re13-import uuid14-import time15-import flask16-import pickle17-import unittest18-from datetime import datetime19-from threading import Thread20-from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning21-from flask._compat import text_type22-from werkzeug.exceptions import BadRequest, NotFound23-from werkzeug.http import parse_date24-from werkzeug.routing import BuildError25-26-27-class BasicFunctionalityTestCase(FlaskTestCase):28-29- 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'')37-38- 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'])48-49- 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)57-58- 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'])65-66- 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.method74-75- 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'])88-89- 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"95-96- def test_url_mapping(self):97- app = flask.Flask(__name__)98- def index():99- return flask.request.method100- def more():101- return flask.request.method102-103- app.add_url_rule('/', 'index', index)104- app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])105-106- 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'])119-120- 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'] = index133-134- 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')137-138- 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- ]))145-146- @app.endpoint('bar')147- def bar():148- return 'bar'149-150- @app.endpoint('index')151- def index():152- return 'index'153-154- 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')157-158- 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']168-169- 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')172-173- 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())186-187- 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())200-201- 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())216-217- 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)225-226- 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())238-239- 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)260-261- 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')274-275- 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 ''284-285- @app.route('/test')286- def test():287- return text_type(flask.session.permanent)288-289- 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)298-299- rv = client.get('/test')300- self.assert_equal(rv.data, b'True')301-302- 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)307-308- def test_session_stored_last(self):309- app = flask.Flask(__name__)310- app.secret_key = 'development-key'311- app.testing = True312-313- @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'))320-321- c = app.test_client()322- self.assert_equal(c.get('/').data, b'None')323- self.assert_equal(c.get('/').data, b'42')324-325- 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()331-332- @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 response340-341- @app.route('/')342- def dump_session_contents():343- return pickle.dumps(dict(flask.session))344-345- 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))355-356- def test_session_cookie_setting(self):357- app = flask.Flask(__name__)358- app.testing = True359- app.secret_key = 'dev key'360- is_permanent = True361-362- @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)367-368- @app.route('/read')369- def read():370- return str(flask.session.get('foo', 0))371-372- 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')377-378- 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')382-383- is_permanent = True384- app.config['SESSION_REFRESH_EACH_REQUEST'] = True385- run_test(expect_header=True)386-387- is_permanent = True388- app.config['SESSION_REFRESH_EACH_REQUEST'] = False389- run_test(expect_header=False)390-391- is_permanent = False392- app.config['SESSION_REFRESH_EACH_REQUEST'] = True393- run_test(expect_header=False)394-395- is_permanent = False396- app.config['SESSION_REFRESH_EACH_REQUEST'] = False397- run_test(expect_header=False)398-399- def test_session_vary_cookie(self):400-401- app = flask.Flask(__name__)402- app.secret_key = 'testkey'403-404- @app.route('/set-session')405- def set_session():406-407- flask.session['test'] = 'test'408- return ''409-410- @app.route('/get-session')411- def get_session():412-413- s = flask.session.get('test')414- return ''415-416- @app.route('/get-session-with-dictionary')417- def get_session_with_dictionary():418-419- s = flask.session['test']420- return ''421-422- @app.route('/no-vary-header')423- def no_vary_header():424-425- return ''426-427- c = app.test_client()428-429- rv = c.get('/set-session')430-431- self.assert_in('Vary', rv.headers)432- self.assert_equal('Cookie', rv.headers['Vary'])433-434- rv = c.get('/get-session')435-436- self.assert_in('Vary', rv.headers)437- self.assert_equal('Cookie', rv.headers['Vary'])438-439- rv = c.get('/get-session-with-dictionary')440-441- self.assert_in('Vary', rv.headers)442- self.assert_equal('Cookie', rv.headers['Vary'])443-444- rv = c.get('/no-vary-header')445-446- self.assert_not_in('Vary', rv.headers)447-448-449- def test_flashes(self):450- app = flask.Flask(__name__)451- app.secret_key = 'testkey'452-453- 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'])460-461- 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.467-468- app = flask.Flask(__name__)469- app.secret_key = 'testkey'470- app.testing = True471-472- @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 ''478-479- @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 ''487-488- @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 ''496-497- @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 ''503-504- @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 ''511-512- @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 ''519-520- # Create new test client on each test to clean flashed messages.521-522- c = app.test_client()523- c.get('/')524- c.get('/test/')525-526- c = app.test_client()527- c.get('/')528- c.get('/test_with_categories/')529-530- c = app.test_client()531- c.get('/')532- c.get('/test_filter/')533-534- c = app.test_client()535- c.get('/')536- c.get('/test_filters/')537-538- c = app.test_client()539- c.get('/')540- c.get('/test_filters_without_returning_categories/')541-542- 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')562-563- 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')577-578- 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)592-593- 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)608-609- 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)641-642- 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])671-672- 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)693-694- 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')705-706- def test_user_error_handling(self):707- class MyException(Exception):708- pass709-710- 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()718-719- c = app.test_client()720- self.assert_equal(c.get('/').data, b'42')721-722- 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)730-731- 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')739-740- 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)747-748- c = app.test_client()749- try:750- c.get('/fail')751- except NotFound as e:752- pass753- else:754- self.fail('Expected exception')755-756- 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'].filename763-764- # 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')775-776- 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- }805-806- 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)828-829- 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')836-837- 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')841-842- 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')846-847- 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')855-856- 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')861-862- 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')868-869- 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')878-879- def test_build_error_handler(self):880- app = flask.Flask(__name__)881-882- # Test base case, a URL which results in a BuildError.883- with app.test_request_context():884- self.assertRaises(BuildError, flask.url_for, 'spam')885-886- # 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', {})896-897- # 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/')904-905- 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')920-921- 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()931-932- 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")944-945- def test_request_locals(self):946- self.assert_equal(repr(flask.g), '<LocalProxy unbound>')947- self.assertFalse(flask.g)948-949- 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'957-958- @app.route('/', subdomain='foo')959- def subdomain():960- return 'Foo SubDomain'961-962- rv = app.test_client().get('/')963- self.assert_equal(rv.data, b'Foo')964-965- rv = app.test_client().get('/', 'http://localhost.localdomain:5000')966- self.assert_equal(rv.data, b'Foo')967-968- rv = app.test_client().get('/', 'https://localhost.localdomain:5000')969- self.assert_equal(rv.data, b'Foo')970-971- app.config.update(SERVER_NAME='localhost.localdomain')972- rv = app.test_client().get('/', 'https://localhost.localdomain')973- self.assert_equal(rv.data, b'Foo')974-975- 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')")985-986- 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')")996-997- rv = app.test_client().get('/', 'http://foo.localhost.localdomain')998- self.assert_equal(rv.data, b'Foo SubDomain')999-1000- 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)1017-1018- # 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()1026-1027- 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'1041-1042- c = app.test_client()1043- rv = c.post('/accept', data={'myfile': 'foo' * 100})1044- self.assert_equal(rv.data, b'42')1045-1046- def test_url_processors(self):1047- app = flask.Flask(__name__)1048-1049- @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)1054-1055- @app.url_value_preprocessor1056- def pull_lang_code(endpoint, values):1057- flask.g.lang_code = values.pop('lang_code', None)1058-1059- @app.route('/<lang_code>/')1060- def index():1061- return flask.url_for('about')1062-1063- @app.route('/<lang_code>/about')1064- def about():1065- return flask.url_for('something_else')1066-1067- @app.route('/foo')1068- def something_else():1069- return flask.url_for('about', lang_code='en')1070-1071- c = app.test_client()1072-1073- 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')1076-1077- def test_inject_blueprint_url_defaults(self):1078- app = flask.Flask(__name__)1079- bp = flask.Blueprint('foo.bar.baz', __name__,1080- template_folder='template')1081-1082- @bp.url_defaults1083- def bp_defaults(endpoint, values):1084- values['page'] = 'login'1085- @bp.route('/<page>')1086- def view(page): pass1087-1088- app.register_blueprint(bp)1089-1090- values = dict()1091- app.inject_url_defaults('foo.bar.baz.view', values)1092- expected = dict(page='login')1093- self.assert_equal(values, expected)1094-1095- with app.test_request_context('/somepage'):1096- url = flask.url_for('foo.bar.baz.view')1097- expected = '/login'1098- self.assert_equal(url, expected)1099-1100- def test_nonascii_pathinfo(self):1101- app = flask.Flask(__name__)1102- app.testing = True1103-1104- @app.route(u'/киртест')1105- def index():1106- return 'Hello World!'1107-1108- c = app.test_client()1109- rv = c.get(u'/киртест')1110- self.assert_equal(rv.data, b'Hello World!')1111-1112- 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')1128-1129- 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)1135-1136- 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)1148-1149- def test_before_first_request_functions_concurrent(self):1150- got = []1151- app = flask.Flask(__name__)1152-1153- @app.before_first_request1154- def foo():1155- time.sleep(0.2)1156- got.append(42)1157-1158- c = app.test_client()1159- def get_and_assert():1160- c.get("/")1161- self.assert_equal(got, [42])1162-1163- t = Thread(target=get_and_assert)1164- t.start()1165- get_and_assert()1166- t.join()1167- self.assert_true(app.got_first_request)1168-1169- 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')1184-1185- rv = c.get('/foo', data={}, follow_redirects=True)1186- self.assert_equal(rv.data, b'success')1187-1188- 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')1192-1193- def test_route_decorator_custom_endpoint(self):1194- app = flask.Flask(__name__)1195- app.debug = True1196-1197- @app.route('/foo/')1198- def foo():1199- return flask.request.endpoint1200-1201- @app.route('/bar/', endpoint='bar')1202- def for_bar():1203- return flask.request.endpoint1204-1205- @app.route('/bar/123', endpoint='123')1206- def for_bar_foo():1207- return flask.request.endpoint1208-1209- 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'1213-1214- 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')1218-1219- def test_preserve_only_once(self):1220- app = flask.Flask(__name__)1221- app.debug = True1222-1223- @app.route('/fail')1224- def fail_func():1225- 1 // 01226-1227- c = app.test_client()1228- for x in range(3):1229- with self.assert_raises(ZeroDivisionError):1230- c.get('/fail')1231-1232- 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)1238-1239- def test_preserve_remembers_exception(self):1240- app = flask.Flask(__name__)1241- app.debug = True1242- errors = []1243-1244- @app.route('/fail')1245- def fail_func():1246- 1 // 01247-1248- @app.route('/success')1249- def success_func():1250- return 'Okay'1251-1252- @app.teardown_request1253- def teardown_handler(exc):1254- errors.append(exc)1255-1256- c = app.test_client()1257-1258- # 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, [])1262-1263- # 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))1267-1268- # 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)1272-1273- def test_get_method_on_g(self):1274- app = flask.Flask(__name__)1275- app.testing = True1276-1277- 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)1283-1284- def test_g_iteration_protocol(self):1285- app = flask.Flask(__name__)1286- app.testing = True1287-1288- 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'])1294-1295-1296-class SubdomainTestCase(FlaskTestCase):1297-1298- 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'1307-1308- c = app.test_client()1309- rv = c.get('/', 'http://localhost/')1310- self.assert_equal(rv.data, b'normal index')1311-1312- rv = c.get('/', 'http://test.localhost/')1313- self.assert_equal(rv.data, b'test index')1314-1315- @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()1326-1327- 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' % user1333-1334- c = app.test_client()1335- rv = c.get('/', 'http://mitsuhiko.localhost/')1336- self.assert_equal(rv.data, b'index for mitsuhiko')1337-1338- 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' % user1344-1345- c = app.test_client()1346- rv = c.get('/', 'http://mitsuhiko.localhost:3000/')1347- self.assert_equal(rv.data, b'index for mitsuhiko')1348-1349- @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'1354-1355- @mod.route('/test')1356- def test():1357- return 'Test'1358-1359- @mod.route('/outside', subdomain='xtesting')1360- def bar():1361- return 'Outside'1362-1363- app.register_module(mod)1364-1365- 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')1370-1371- def test_multi_route_rules(self):1372- app = flask.Flask(__name__)1373-1374- @app.route('/')1375- @app.route('/<test>/')1376- def index(test='a'):1377- return test1378-1379- 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')1383-1384- 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)1389-1390- def index(self, test='a'):1391- return test1392-1393- 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')1399-1400-1401-def suite():1402- suite = unittest.TestSuite()1403- suite.addTest(unittest.makeSuite(BasicFunctionalityTestCase))1404- suite.addTest(unittest.makeSuite(SubdomainTestCase))1405- return suitedeleted:flask/testsuite/blueprints.py-823 removed
1-# -*- coding: utf-8 -*-2-"""3- flask.testsuite.blueprints4- ~~~~~~~~~~~~~~~~~~~~~~~~~~5-6- Blueprints (and currently modules)7-8- :copyright: (c) 2014 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-12-import flask13-import unittest14-import warnings15-from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning16-from flask._compat import text_type17-from werkzeug.exceptions import NotFound18-from werkzeug.http import parse_cache_control_header19-from jinja2 import TemplateNotFound20-21-22-# import moduleapp here because it uses deprecated features and we don't23-# want to see the warnings24-warnings.simplefilter('ignore', DeprecationWarning)25-from moduleapp import app as moduleapp26-warnings.simplefilter('default', DeprecationWarning)27-28-29-class ModuleTestCase(FlaskTestCase):30-31- @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')53-54- @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'), '/')66-67- @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()94-95- self.assert_equal(c.get('/').data, b'the index')96- self.assert_equal(catched, ['before-app', 'after-app'])97- del catched[:]98-99- self.assert_equal(c.get('/admin/').data, b'the admin')100- self.assert_equal(catched, ['before-app', 'before-admin',101- 'after-admin', 'after-app'])102-103- @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')126-127- @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')136-137- @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)161-162- def test_templates_and_static(self):163- app = moduleapp164- app.testing = True165- c = app.test_client()166-167- 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()179-180- with app.test_request_context():181- self.assert_equal(flask.url_for('admin.static', filename='test.txt'),182- '/admin/static/test.txt')183-184- 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')191-192- with flask.Flask(__name__).test_request_context():193- self.assert_equal(flask.render_template('nested/nested.txt'), 'I\'m nested')194-195- def test_safe_access(self):196- app = moduleapp197-198- with app.test_request_context():199- f = app.view_functions['admin.static']200-201- 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')213-214- # 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_path228-229- @emits_module_deprecation_warning230- def test_endpoint_decorator(self):231- from werkzeug.routing import Submount, Rule232- from flask import Module233-234- 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__)241-242- @module.endpoint('bar')243- def bar():244- return 'bar'245-246- @module.endpoint('index')247- def index():248- return 'index'249-250- app.register_module(module)251-252- 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')255-256-257-class BlueprintTestCase(FlaskTestCase):258-259- 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__)263-264- @frontend.errorhandler(403)265- def frontend_forbidden(e):266- return 'frontend says no', 403267-268- @frontend.route('/frontend-no')269- def frontend_no():270- flask.abort(403)271-272- @backend.errorhandler(403)273- def backend_forbidden(e):274- return 'backend says no', 403275-276- @backend.route('/backend-no')277- def backend_no():278- flask.abort(403)279-280- @sideend.route('/what-is-a-sideend')281- def sideend_no():282- flask.abort(403)283-284- app = flask.Flask(__name__)285- app.register_blueprint(frontend)286- app.register_blueprint(backend)287- app.register_blueprint(sideend)288-289- @app.errorhandler(403)290- def app_forbidden(e):291- return 'application itself says no', 403292-293- c = app.test_client()294-295- 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')298-299- def test_blueprint_specific_user_error_handling(self):300- class MyDecoratorException(Exception):301- pass302- class MyFunctionException(Exception):303- pass304-305- blue = flask.Blueprint('blue', __name__)306-307- @blue.errorhandler(MyDecoratorException)308- def my_decorator_exception_handler(e):309- self.assert_true(isinstance(e, MyDecoratorException))310- return 'boom'311-312- 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)316-317- @blue.route('/decorator')318- def blue_deco_test():319- raise MyDecoratorException()320- @blue.route('/function')321- def blue_func_test():322- raise MyFunctionException()323-324- app = flask.Flask(__name__)325- app.register_blueprint(blue)326-327- c = app.test_client()328-329- self.assert_equal(c.get('/decorator').data, b'boom')330- self.assert_equal(c.get('/function').data, b'bam')331-332- def test_blueprint_url_definitions(self):333- bp = flask.Blueprint('test', __name__)334-335- @bp.route('/foo', defaults={'baz': 42})336- def foo(bar, baz):337- return '%s/%d' % (bar, baz)338-339- @bp.route('/bar')340- def bar(bar):341- return text_type(bar)342-343- 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})346-347- 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')352-353- def test_blueprint_url_processors(self):354- bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')355-356- @bp.url_defaults357- def add_language_code(endpoint, values):358- values.setdefault('lang_code', flask.g.lang_code)359-360- @bp.url_value_preprocessor361- def pull_lang_code(endpoint, values):362- flask.g.lang_code = values.pop('lang_code')363-364- @bp.route('/')365- def index():366- return flask.url_for('.about')367-368- @bp.route('/about')369- def about():370- return flask.url_for('.index')371-372- app = flask.Flask(__name__)373- app.register_blueprint(bp)374-375- c = app.test_client()376-377- self.assert_equal(c.get('/de/').data, b'/de/about')378- self.assert_equal(c.get('/de/about').data, b'/de/')379-380- def test_templates_and_static(self):381- from blueprintapp import app382- c = app.test_client()383-384- 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()396-397- # 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_default410-411- with app.test_request_context():412- self.assert_equal(flask.url_for('admin.static', filename='test.txt'),413- '/admin/static/test.txt')414-415- 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')422-423- with flask.Flask(__name__).test_request_context():424- self.assert_equal(flask.render_template('nested/nested.txt'), 'I\'m nested')425-426- 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 100431-432- blueprint = MyBlueprint('blueprint', __name__, static_folder='static')433- app.register_blueprint(blueprint)434-435- # 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_default449-450- 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'])455-456- def test_dotted_names(self):457- frontend = flask.Blueprint('myapp.frontend', __name__)458- backend = flask.Blueprint('myapp.backend', __name__)459-460- @frontend.route('/fe')461- def frontend_index():462- return flask.url_for('myapp.backend.backend_index')463-464- @frontend.route('/fe2')465- def frontend_page2():466- return flask.url_for('.frontend_index')467-468- @backend.route('/be')469- def backend_index():470- return flask.url_for('myapp.frontend.frontend_index')471-472- app = flask.Flask(__name__)473- app.register_blueprint(frontend)474- app.register_blueprint(backend)475-476- 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')480-481- def test_dotted_names_from_app(self):482- app = flask.Flask(__name__)483- app.testing = True484- test = flask.Blueprint('test', __name__)485-486- @app.route('/')487- def app_index():488- return flask.url_for('test.index')489-490- @test.route('/test/')491- def index():492- return flask.url_for('app_index')493-494- app.register_blueprint(test)495-496- with app.test_client() as c:497- rv = c.get('/')498- self.assert_equal(rv.data, b'/test/')499-500- def test_empty_url_defaults(self):501- bp = flask.Blueprint('bp', __name__)502-503- @bp.route('/', defaults={'page': 1})504- @bp.route('/page/<int:page>')505- def something(page):506- return str(page)507-508- app = flask.Flask(__name__)509- app.register_blueprint(bp)510-511- c = app.test_client()512- self.assert_equal(c.get('/').data, b'1')513- self.assert_equal(c.get('/page/2').data, b'2')514-515- def test_route_decorator_custom_endpoint(self):516-517- bp = flask.Blueprint('bp', __name__)518-519- @bp.route('/foo')520- def foo():521- return flask.request.endpoint522-523- @bp.route('/bar', endpoint='bar')524- def foo_bar():525- return flask.request.endpoint526-527- @bp.route('/bar/123', endpoint='123')528- def foo_bar_foo():529- return flask.request.endpoint530-531- @bp.route('/bar/foo')532- def bar_foo():533- return flask.request.endpoint534-535- app = flask.Flask(__name__)536- app.register_blueprint(bp, url_prefix='/py')537-538- @app.route('/')539- def index():540- return flask.request.endpoint541-542- 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')548-549- def test_route_decorator_custom_endpoint_with_dots(self):550- bp = flask.Blueprint('bp', __name__)551-552- @bp.route('/foo')553- def foo():554- return flask.request.endpoint555-556- 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')564-565- 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')573-574- def foo_foo_foo():575- pass576-577- self.assertRaises(578- AssertionError,579- lambda: bp.add_url_rule(580- '/bar/123', endpoint='bar.123', view_func=foo_foo_foo581- )582- )583-584- self.assertRaises(585- AssertionError,586- bp.route('/bar/123', endpoint='bar.123'),587- lambda: None588- )589-590- app = flask.Flask(__name__)591- app.register_blueprint(bp, url_prefix='/py')592-593- 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 == 404600-601- 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')611-612- 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')622-623- 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')633-634- 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')644-645- 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')657-658- 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')670-671- 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')683-684- 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')696-697- 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')709-710- 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))720-721- 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))731-732- 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))742-743- 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))753-754- 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)766-767- 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)779-780- 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)792-793- 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)805-806- 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)818-819-def suite():820- suite = unittest.TestSuite()821- suite.addTest(unittest.makeSuite(BlueprintTestCase))822- suite.addTest(unittest.makeSuite(ModuleTestCase))823- return suitedeleted:flask/testsuite/config.py-356 removed
1-# -*- coding: utf-8 -*-2-"""3- flask.testsuite.config4- ~~~~~~~~~~~~~~~~~~~~~~5-6- Configuration and instances.7-8- :copyright: (c) 2014 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-12-import os13-import sys14-import flask15-import pkgutil16-import unittest17-from contextlib import contextmanager18-from flask.testsuite import FlaskTestCase19-from flask._compat import PY220-21-22-# config keys used for the ConfigTestCase23-TEST_KEY = 'foo'24-SECRET_KEY = 'devkey'25-26-27-class ConfigTestCase(FlaskTestCase):28-29- 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)33-34- 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)38-39- def test_config_from_object(self):40- app = flask.Flask(__name__)41- app.config.from_object(__name__)42- self.common_object_test(app)43-44- 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)49-50- 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)58-59- 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))71-72- 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 = env77-78- 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 = env95-96- 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))108-109- 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))121-122- 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)131-132- 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)136-137- 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'])151-152-153-class LimitedLoaderMockWrapper(object):154- def __init__(self, loader):155- self.loader = loader156-157- 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)162-163-164-@contextmanager165-def patch_pkgutil_get_loader(wrapper_class=LimitedLoaderMockWrapper):166- """Patch pkgutil.get_loader to give loader without get_filename or archive.167-168- 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_loader180-181-182-class InstanceTestCase(FlaskTestCase):183-184- 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')192-193- app = flask.Flask(__name__, instance_path=here)194- self.assert_equal(app.instance_path, here)195-196- 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']203-204- 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'))208-209- 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'))213-214- 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']230-231- 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']248-249- 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']265-266- 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']283-284- 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']300-301- 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']318-319- 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']338-339- 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()350-351-352-def suite():353- suite = unittest.TestSuite()354- suite.addTest(unittest.makeSuite(ConfigTestCase))355- suite.addTest(unittest.makeSuite(InstanceTestCase))356- return suitedeleted:flask/testsuite/deprecations.py-24 removed
1-# -*- coding: utf-8 -*-2-"""3- flask.testsuite.deprecations4- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~5-6- Tests deprecation support.7-8- :copyright: (c) 2014 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-12-import flask13-import unittest14-from flask.testsuite import FlaskTestCase, catch_warnings15-16-17-class DeprecationsTestCase(FlaskTestCase):18- """not used currently"""19-20-21-def suite():22- suite = unittest.TestSuite()23- suite.addTest(unittest.makeSuite(DeprecationsTestCase))24- return suitedeleted:flask/testsuite/examples.py-38 removed
1-# -*- coding: utf-8 -*-2-"""3- flask.testsuite.examples4- ~~~~~~~~~~~~~~~~~~~~~~~~5-6- Tests the examples.7-8- :copyright: (c) 2014 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-import os12-import unittest13-from flask.testsuite import add_to_path14-15-16-def 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'))21-22-23-def 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 suitedeleted:flask/testsuite/ext.py-136 removed
1-# -*- coding: utf-8 -*-2-"""3- flask.testsuite.ext4- ~~~~~~~~~~~~~~~~~~~5-6- Tests the extension import thing.7-8- :copyright: (c) 2014 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-12-import sys13-import unittest14-try:15- from imp import reload as reload_module16-except ImportError:17- reload_module = reload18-from flask.testsuite import FlaskTestCase19-from flask._compat import PY220-21-class ExtImportHookTestCase(FlaskTestCase):22-23- 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)36-37- # 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)45-46- def teardown(self):47- from flask import ext48- for key in ext.__dict__:49- self.assert_not_in('.', key)50-51- def test_flaskext_new_simple_import_normal(self):52- from flask.ext.newext_simple import ext_id53- self.assert_equal(ext_id, 'newext_simple')54-55- 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')59-60- def test_flaskext_new_package_import_normal(self):61- from flask.ext.newext_package import ext_id62- self.assert_equal(ext_id, 'newext_package')63-64- 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')68-69- 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)72-73- 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)77-78- def test_flaskext_old_simple_import_normal(self):79- from flask.ext.oldext_simple import ext_id80- self.assert_equal(ext_id, 'oldext_simple')81-82- 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')86-87- def test_flaskext_old_package_import_normal(self):88- from flask.ext.oldext_package import ext_id89- self.assert_equal(ext_id, 'oldext_package')90-91- 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')95-96- 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)100-101- 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)104-105- 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.broken109-110- 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())122-123- # 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)131-132-133-def suite():134- suite = unittest.TestSuite()135- suite.addTest(unittest.makeSuite(ExtImportHookTestCase))136- return suitedeleted:flask/testsuite/helpers.py-658 removed
1-# -*- coding: utf-8 -*-2-"""3- flask.testsuite.helpers4- ~~~~~~~~~~~~~~~~~~~~~~~5-6- Various helpers.7-8- :copyright: (c) 2014 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-12-import os13-import flask14-import unittest15-from logging import StreamHandler16-from flask.testsuite import FlaskTestCase, catch_warnings, catch_stderr17-from werkzeug.http import parse_cache_control_header, parse_options_header18-from flask._compat import StringIO, text_type19-20-21-def has_encoding(name):22- try:23- import codecs24- codecs.lookup(name)25- return True26- except LookupError:27- return False28-29-30-class JSONTestCase(FlaskTestCase):31-32- 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)40-41- 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')49-50- 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()56-57- 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'))61-62- 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)76-77- def test_json_as_unicode(self):78- app = flask.Flask(__name__)79-80- app.config['JSON_AS_ASCII'] = True81- with app.app_context():82- rv = flask.json.dumps(u'\N{SNOWMAN}')83- self.assert_equal(rv, '"\\u2603"')84-85- 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"')89-90- 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')100-101- 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>')122-123- 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>"')152-153- 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'160-161- @app.route('/')162- def index():163- return flask.request.args['foo']164-165- 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'))168-169- if not has_encoding('euc-kr'):170- test_modified_url_encoding = None171-172- 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')177-178- @app.route('/')179- def index():180- return flask.jsonify(values=d)181-182- 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- ]237-238- try:239- self.assert_equal(lines, sorted_by_int)240- except AssertionError:241- self.assert_equal(lines, sorted_by_str)242-243-class SendfileTestCase(FlaskTestCase):244-245- 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()255-256- 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()267-268- 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)281-282- 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)294-295- 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)330-331- 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)340-341- 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)352-353- 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()360-361- 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()370-371- 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()412-413- 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()423-424-425-class LoggingTestCase(FlaskTestCase):426-427- 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)434-435- def test_debug_log(self):436- app = flask.Flask(__name__)437- app.debug = True438-439- @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 ''444-445- @app.route('/exc')446- def exc():447- 1 // 0448-449- 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)457-458- 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')465-466- 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)472-473- 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))478-479- @app.route('/')480- def index():481- 1 // 0482-483- rv = app.test_client().get('/')484- self.assert_equal(rv.status_code, 500)485- self.assert_in(b'Internal Server Error', rv.data)486-487- 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)492-493- 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')514-515- 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')523-524- 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/')534-535- 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')545-546- 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)563-564- 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')571-572-573-class NoImportsTestCase(FlaskTestCase):574- """Test Flasks are created without import.575-576- 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- """583-584- 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.')589-590-591-class StreamingTestCase(FlaskTestCase):592-593- 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!')606-607- 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!')621-622- 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])648-649-650-def 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 suitedeleted:flask/testsuite/regression.py-116 removed
1-# -*- coding: utf-8 -*-2-"""3- flask.testsuite.regression4- ~~~~~~~~~~~~~~~~~~~~~~~~~~5-6- Tests regressions.7-8- :copyright: (c) 2014 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-12-import os13-import gc14-import sys15-import flask16-import threading17-import unittest18-from werkzeug.exceptions import NotFound19-from flask.testsuite import FlaskTestCase20-21-22-_gc_lock = threading.Lock()23-24-25-class _NoLeakAsserter(object):26-27- def __init__(self, testcase):28- self.testcase = testcase29-30- def __enter__(self):31- gc.disable()32- _gc_lock.acquire()33- loc = flask._request_ctx_stack._local34-35- # 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]40-41- gc.collect()42- self.old_objects = len(gc.get_objects())43-44- 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()52-53-54-class MemoryTestCase(FlaskTestCase):55-56- def assert_no_leak(self):57- return _NoLeakAsserter(self)58-59- 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)64-65- 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>')70-71- # Trigger caches72- fire()73-74- # 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()80-81- def test_safe_join_toplevel_pardir(self):82- from flask.helpers import safe_join83- with self.assert_raises(NotFound):84- safe_join('/foo', '..')85-86-87-class ExceptionTestCase(FlaskTestCase):88-89- 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()103-104- 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')109-110-111-def 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 suitedeleted:flask/testsuite/reqctx.py-201 removed
1-# -*- coding: utf-8 -*-2-"""3- flask.testsuite.reqctx4- ~~~~~~~~~~~~~~~~~~~~~~5-6- Tests the request context.7-8- :copyright: (c) 2014 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-12-import flask13-import unittest14-try:15- from greenlet import greenlet16-except ImportError:17- greenlet = None18-from flask.testsuite import FlaskTestCase19-20-21-class RequestContextTestCase(FlaskTestCase):22-23- 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)29-30- ctx = app.test_request_context()31- ctx.push()32- self.assert_equal(buffer, [])33- ctx.pop()34- self.assert_equal(buffer, [None])35-36- 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)42-43- try:44- raise Exception('dummy')45- except Exception:46- pass47-48- with app.test_request_context():49- self.assert_equal(buffer, [])50- self.assert_equal(buffer, [None])51-52- def test_proper_test_request_context(self):53- app = flask.Flask(__name__)54- app.config.update(55- SERVER_NAME='localhost.localdomain:5000'56- )57-58- @app.route('/')59- def index():60- return None61-62- @app.route('/', subdomain='foo')63- def sub():64- return None65-66- with app.test_request_context('/'):67- self.assert_equal(flask.url_for('index', _external=True), 'http://localhost.localdomain:5000/')68-69- with app.test_request_context('/'):70- self.assert_equal(flask.url_for('sub', _external=True), 'http://foo.localhost.localdomain:5000/')71-72- 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')")80-81- 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- )89-90- 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- )98-99- 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.url107-108- 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)113-114- 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()125-126- 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']131-132- 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')142-143- def test_greenlet_context_copying(self):144- app = flask.Flask(__name__)145- greenlets = []146-147- @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!'162-163- rv = app.test_client().get('/?foo=bar')164- self.assert_equal(rv.data, b'Hello World!')165-166- result = greenlets[0].run()167- self.assert_equal(result, 42)168-169- def test_greenlet_context_copying_api(self):170- app = flask.Flask(__name__)171- greenlets = []172-173- @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!'185-186- rv = app.test_client().get('/?foo=bar')187- self.assert_equal(rv.data, b'Hello World!')188-189- result = greenlets[0].run()190- self.assert_equal(result, 42)191-192- # Disable test if we don't have greenlets available193- if greenlet is None:194- test_greenlet_context_copying = None195- test_greenlet_context_copying_api = None196-197-198-def suite():199- suite = unittest.TestSuite()200- suite.addTest(unittest.makeSuite(RequestContextTestCase))201- return suitedeleted:flask/testsuite/signals.py-153 removed
1-# -*- coding: utf-8 -*-2-"""3- flask.testsuite.signals4- ~~~~~~~~~~~~~~~~~~~~~~~5-6- Signalling.7-8- :copyright: (c) 2014 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-12-import flask13-import unittest14-from flask.testsuite import FlaskTestCase15-16-17-class SignalsTestCase(FlaskTestCase):18-19- def test_template_rendered(self):20- app = flask.Flask(__name__)21-22- @app.route('/')23- def index():24- return flask.render_template('simple_template.html', whiskey=42)25-26- recorded = []27- def record(sender, template, context):28- recorded.append((template, context))29-30- 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)39-40- def test_request_signals(self):41- app = flask.Flask(__name__)42- calls = []43-44- def before_request_signal(sender):45- calls.append('before-signal')46-47- def after_request_signal(sender, response):48- self.assert_equal(response.data, b'stuff')49- calls.append('after-signal')50-51- @app.before_request52- def before_request_handler():53- calls.append('before-handler')54-55- @app.after_request56- def after_request_handler(response):57- calls.append('after-handler')58- response.data = 'stuff'59- return response60-61- @app.route('/')62- def index():63- calls.append('handler')64- return 'ignored anyway'65-66- flask.request_started.connect(before_request_signal, app)67- flask.request_finished.connect(after_request_signal, app)68-69- try:70- rv = app.test_client().get('/')71- self.assert_equal(rv.data, b'stuff')72-73- 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)79-80- def test_request_exception_signal(self):81- app = flask.Flask(__name__)82- recorded = []83-84- @app.route('/')85- def index():86- 1 // 087-88- def record(sender, exception):89- recorded.append(exception)90-91- 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)98-99- 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')106-107- @app.route('/')108- def index():109- return 'Hello'110-111- 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)122-123- def test_flash_signal(self):124- app = flask.Flask(__name__)125- app.config['SECRET_KEY'] = 'secret'126-127- @app.route('/')128- def index():129- flask.flash('This is a flash message', category='notice')130- return flask.redirect('/other')131-132- recorded = []133- def record(sender, message, category):134- recorded.append((message, category))135-136- 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)147-148-149-def suite():150- suite = unittest.TestSuite()151- if flask.signals_available:152- suite.addTest(unittest.makeSuite(SignalsTestCase))153- return suitedeleted:flask/testsuite/subclassing.py-46 removed
1-# -*- coding: utf-8 -*-2-"""3- flask.testsuite.subclassing4- ~~~~~~~~~~~~~~~~~~~~~~~~~~~5-6- Test that certain behavior of flask can be customized by7- subclasses.8-9- :copyright: (c) 2014 by Armin Ronacher.10- :license: BSD, see LICENSE for more details.11-"""12-import flask13-import unittest14-from logging import StreamHandler15-from flask.testsuite import FlaskTestCase16-from flask._compat import StringIO17-18-19-class FlaskSubclassingTestCase(FlaskTestCase):20-21- def test_suppressed_exception_logging(self):22- class SuppressedFlask(flask.Flask):23- def log_exception(self, exc_info):24- pass25-26- out = StringIO()27- app = SuppressedFlask(__name__)28- app.logger_name = 'flask_tests/test_suppressed_exception_logging'29- app.logger.addHandler(StreamHandler(out))30-31- @app.route('/')32- def index():33- 1 // 034-35- rv = app.test_client().get('/')36- self.assert_equal(rv.status_code, 500)37- self.assert_in(b'Internal Server Error', rv.data)38-39- err = out.getvalue()40- self.assert_equal(err, '')41-42-43-def suite():44- suite = unittest.TestSuite()45- suite.addTest(unittest.makeSuite(FlaskSubclassingTestCase))46- return suitedeleted:flask/testsuite/templating.py-310 removed
1-# -*- coding: utf-8 -*-2-"""3- flask.testsuite.templating4- ~~~~~~~~~~~~~~~~~~~~~~~~~~5-6- Template functionality7-8- :copyright: (c) 2014 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-12-import flask13-import unittest14-from flask.testsuite import FlaskTestCase15-16-17-class TemplatingTestCase(FlaskTestCase):18-19- 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')29-30- 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')37-38- 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)44-45- 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')49-50- 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'])65-66- 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'<p>Hello World!',76- b'<p>Hello World!',77- b'<p>Hello World!',78- b'<p>Hello World!',79- b'<p>Hello World!',80- b'<p>Hello World!'81- ])82-83- 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')90-91- 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!')96-97- 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')105-106- 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')114-115- 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')123-124- 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')132-133- 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')143-144- 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')154-155- 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')165-166- 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')176-177- 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))185-186- 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))194-195- 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))203-204- 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))212-213- 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)223-224- 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)234-235- 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)245-246- 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)256-257- 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')268-269- 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!')281-282- 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)294-295- rv = app.test_client().get('/')296- self.assert_equal(rv.data, b'<h1>Jameson</h1>')297-298- 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)305-306-307-def suite():308- suite = unittest.TestSuite()309- suite.addTest(unittest.makeSuite(TemplatingTestCase))310- return suitedeleted:flask/testsuite/testing.py-256 removed
1-# -*- coding: utf-8 -*-2-"""3- flask.testsuite.testing4- ~~~~~~~~~~~~~~~~~~~~~~~5-6- Test client and more.7-8- :copyright: (c) 2014 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-12-import flask13-import unittest14-from flask.testsuite import FlaskTestCase15-from flask._compat import text_type16-17-18-class TestToolsTestCase(FlaskTestCase):19-20- 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.url28-29- 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/')34-35- def test_environ_defaults(self):36- app = flask.Flask(__name__)37- app.testing = True38- @app.route('/')39- def index():40- return flask.request.url41-42- 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/')47-48- def test_redirect_keep_session(self):49- app = flask.Flask(__name__)50- app.secret_key = 'testing'51-52- @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'58-59- @app.route('/getsession')60- def get_session():61- return flask.session.get('data', '<missing>')62-63- with app.test_client() as c:64- rv = c.get('/getsession')65- assert rv.data == b'<missing>'66-67- 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'72-73- # This support requires a new Werkzeug version74- if not hasattr(c, 'redirect_client'):75- assert flask.session.get('data') == 'foo'76-77- rv = c.get('/getsession')78- assert rv.data == b'foo'79-80- def test_session_transactions(self):81- app = flask.Flask(__name__)82- app.testing = True83- app.secret_key = 'testing'84-85- @app.route('/')86- def index():87- return text_type(flask.session['foo'])88-89- 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])99-100- def test_session_transactions_no_null_sessions(self):101- app = flask.Flask(__name__)102- app.testing = True103-104- 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')112-113- def test_session_transactions_keep_context(self):114- app = flask.Flask(__name__)115- app.testing = True116- app.secret_key = 'testing'117-118- 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())124-125- 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')136-137- 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!'143-144- @app.route('/other')145- def other():146- 1 // 0147-148- 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)153-154- 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 = 23159-160- try:161- flask.g.value162- except (AttributeError, RuntimeError):163- pass164- else:165- raise AssertionError('some kind of exception expected')166-167- def test_reuse_client(self):168- app = flask.Flask(__name__)169- c = app.test_client()170-171- with c:172- self.assert_equal(c.get('/').status_code, 404)173-174- with c:175- self.assert_equal(c.get('/').status_code, 404)176-177- 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)183-184- 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])189-190- 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])198-199- def test_full_url_request(self):200- app = flask.Flask(__name__)201- app.testing = True202-203- @app.route('/action', methods=['POST'])204- def action():205- return 'x'206-207- 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)212-213-214-class SubdomainTestCase(FlaskTestCase):215-216- def setUp(self):217- self.app = flask.Flask(__name__)218- self.app.config['SERVER_NAME'] = 'example.com'219- self.client = self.app.test_client()220-221- self._ctx = self.app.test_request_context()222- self._ctx.push()223-224- def tearDown(self):225- if self._ctx is not None:226- self._ctx.pop()227-228- def test_subdomain(self):229- @self.app.route('/', subdomain='<company_id>')230- def view(company_id):231- return company_id232-233- url = flask.url_for('view', company_id='xxx')234- response = self.client.get(url)235-236- self.assert_equal(200, response.status_code)237- self.assert_equal(b'xxx', response.data)238-239-240- def test_nosubdomain(self):241- @self.app.route('/<company_id>')242- def view(company_id):243- return company_id244-245- url = flask.url_for('view', company_id='xxx')246- response = self.client.get(url)247-248- self.assert_equal(200, response.status_code)249- self.assert_equal(b'xxx', response.data)250-251-252-def suite():253- suite = unittest.TestSuite()254- suite.addTest(unittest.makeSuite(TestToolsTestCase))255- suite.addTest(unittest.makeSuite(SubdomainTestCase))256- return suitedeleted:flask/testsuite/views.py-169 removed
1-# -*- coding: utf-8 -*-2-"""3- flask.testsuite.views4- ~~~~~~~~~~~~~~~~~~~~~5-6- Pluggable views.7-8- :copyright: (c) 2014 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-12-import flask13-import flask.views14-import unittest15-from flask.testsuite import FlaskTestCase16-from werkzeug.http import parse_set_header17-18-class ViewTestCase(FlaskTestCase):19-20- def common_test(self, app):21- c = app.test_client()22-23- 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'])28-29- def test_basic_view(self):30- app = flask.Flask(__name__)31-32- class Index(flask.views.View):33- methods = ['GET', 'POST']34- def dispatch_request(self):35- return flask.request.method36-37- app.add_url_rule('/', view_func=Index.as_view('index'))38- self.common_test(app)39-40- def test_method_based_view(self):41- app = flask.Flask(__name__)42-43- class Index(flask.views.MethodView):44- def get(self):45- return 'GET'46- def post(self):47- return 'POST'48-49- app.add_url_rule('/', view_func=Index.as_view('index'))50-51- self.common_test(app)52-53- def test_view_patching(self):54- app = flask.Flask(__name__)55-56- class Index(flask.views.MethodView):57- def get(self):58- 1 // 059- def post(self):60- 1 // 061-62- class Other(Index):63- def get(self):64- return 'GET'65- def post(self):66- return 'POST'67-68- view = Index.as_view('index')69- view.view_class = Other70- app.add_url_rule('/', view_func=view)71- self.common_test(app)72-73- def test_view_inheritance(self):74- app = flask.Flask(__name__)75-76- class Index(flask.views.MethodView):77- def get(self):78- return 'GET'79- def post(self):80- return 'POST'81-82- class BetterIndex(Index):83- def delete(self):84- return 'DELETE'85-86- app.add_url_rule('/', view_func=BetterIndex.as_view('index'))87- c = app.test_client()88-89- meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])90- self.assert_equal(sorted(meths), ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST'])91-92- def test_view_decorators(self):93- app = flask.Flask(__name__)94-95- 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_function101-102- class Index(flask.views.View):103- decorators = [add_x_parachute]104- def dispatch_request(self):105- return 'Awesome'106-107- 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')112-113- def test_implicit_head(self):114- app = flask.Flask(__name__)115-116- class Index(flask.views.MethodView):117- def get(self):118- return flask.Response('Blub', headers={119- 'X-Method': flask.request.method120- })121-122- 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')130-131- def test_explicit_head(self):132- app = flask.Flask(__name__)133-134- class Index(flask.views.MethodView):135- def get(self):136- return 'GET'137- def head(self):138- return flask.Response('', headers={'X-Method': 'HEAD'})139-140- 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')147-148- def test_endpoint_override(self):149- app = flask.Flask(__name__)150- app.debug = True151-152- class Index(flask.views.View):153- methods = ['GET', 'POST']154- def dispatch_request(self):155- return flask.request.method156-157- app.add_url_rule('/', view_func=Index.as_view('index'))158-159- with self.assert_raises(AssertionError):160- app.add_url_rule('/', view_func=Index.as_view('index'))161-162- # But these tests should still pass. We just log a warning.163- self.common_test(app)164-165-166-def suite():167- suite = unittest.TestSuite()168- suite.addTest(unittest.makeSuite(ViewTestCase))169- return suitemodified:flask/__init__.py+6 added-7 removed
4 unmodified lines5 6 A microframework based on Werkzeug. It's extensively documented7 and follows best practice patterns.8 9- :copyright: (c) 2014 by Armin Ronacher.9+ :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11 """12 13-__version__ = '0.11-dev'13+__version__ = '0.13-dev'14 15 # utilities we import from Werkzeug and Jinja2 that are unused16 # in the module but are exported as public interface.17 from werkzeug.exceptions import abort2 unmodified lines20 21 from .app import Flask, Request, Response22 from .config import Config23 from .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_context26 from .globals import current_app, g, request, session, _request_ctx_stack, \27 _app_ctx_stack28 from .ctx import has_request_context, has_app_context, \29 after_this_request, copy_current_request_context30-from .module import Module30 from .blueprints import Blueprint31 from .templating import render_template, render_template_string32 33 # the signals34 from .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_template38 39 # We're not exposing the actual json module but a convenient wrapper around40 # it.41 from . import json42 44-# This was the only thing that flask used to export at one point and it had43+# This was the only thing that Flask used to export at one point and it had44 # a more generic name.45 jsonify = json.jsonify46 47 # backwards compat, goes away in 1.02 unmodified linesadded:flask/__main__.py+15 added
1+# -*- coding: utf-8 -*-2+"""3+ flask.__main__4+ ~~~~~~~~~~~~~~5+6+ Alias for flask.run for the command line.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+13+if __name__ == '__main__':14+ from .cli import main15+ main(as_module=True)modified:flask/_compat.py+19 added-20 removed
5 unmodified lines6 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.9 10- :copyright: (c) 2014 by Armin Ronacher.10+ :copyright: (c) 2015 by Armin Ronacher.11 :license: BSD, see LICENSE for more details.12 """13 import sys14 3 unmodified lines18 19 if not PY2:20 text_type = str21 string_types = (str,)22- integer_types = (int, )22+ integer_types = (int,)23 24 iterkeys = lambda d: iter(d.keys())25 itervalues = lambda d: iter(d.values())26 iteritems = lambda d: iter(d.items())26 unmodified lines53 return cls54 55 56 def 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', (), {})65 66 67 # 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.78 BROKEN_PYPY_CTXMGR_EXIT = False79 if hasattr(sys, 'pypy_version_info'):80 class _Mgr(object):81 def __enter__(self):82 return self83 def __exit__(self, *args):84+ if hasattr(sys, 'exc_clear'):85+ # Python 3 (PyPy3) doesn't have exc_clear87- sys.exc_clear()86+ sys.exc_clear()87 try:88 try:89 with _Mgr():90 raise AssertionError()6 unmodified linesmodified:flask/app.py+475 added-274 removed
3 unmodified lines4 ~~~~~~~~~5 6 This module implements the central WSGI application object.7 8- :copyright: (c) 2014 by Armin Ronacher.8+ :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11-11 import os12 import sys14-from threading import Lock13 from datetime import timedelta16-from itertools import chain14 from functools import update_wrapper15+from itertools import chain16+from threading import Lock17 19-from werkzeug.datastructures import ImmutableDict20-from werkzeug.routing import Map, Rule, RequestRedirect, BuildError21-from werkzeug.exceptions import HTTPException, InternalServerError, \22- MethodNotAllowed, BadRequest18+from werkzeug.datastructures import ImmutableDict, Headers19+from werkzeug.exceptions import BadRequest, HTTPException, \20+ InternalServerError, MethodNotAllowed, default_exceptions21+from werkzeug.routing import BuildError, Map, RequestRedirect, Rule22 24-from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \25- locked_cached_property, _endpoint_from_view_func, find_package26-from . import json27-from .wrappers import Request, Response28-from .config import ConfigAttribute, Config29-from .ctx import RequestContext, AppContext, _AppCtxGlobals30-from .globals import _request_ctx_stack, request, session, g23+from . import cli, json24+from ._compat import integer_types, reraise, string_types, text_type25+from .config import Config, ConfigAttribute26+from .ctx import AppContext, RequestContext, _AppCtxGlobals27+from .globals import _request_ctx_stack, g, request, session28+from .helpers import _PackageBoundObject, \29+ _endpoint_from_view_func, find_package, get_debug_flag, \30+ get_flashed_messages, locked_cached_property, url_for31 from .sessions import SecureCookieSessionInterface32-from .module import blueprint_is_module32+from .signals import appcontext_tearing_down, got_request_exception, \33+ request_finished, request_started, request_tearing_down34 from .templating import DispatchingJinjaLoader, Environment, \34- _default_template_ctx_processor35-from .signals import request_started, request_finished, got_request_exception, \36- request_tearing_down, appcontext_tearing_down37-from ._compat import reraise, string_types, text_type, integer_types35+ _default_template_ctx_processor36+from .wrappers import Request, Response37 38 # a lock used for logger initialization39 _logger_lock = Lock()40 41+# a singleton sentinel value for parameter defaults42+_sentinel = object()43 44+45 def _make_timedelta(value):46 if not isinstance(value, timedelta):47 return timedelta(seconds=value)48 return value24 unmodified lines73 74 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).78 79 For more information about resource loading, see :func:`open_resource`.80 81 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::83 84 from flask import Flask85 app = Flask(__name__)86 87 .. admonition:: About the First Parameter88 87- 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.93 94 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.98 97- 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::101 102 app = Flask('yourapplication')103 app = Flask(__name__.split('.')[0])15 unmodified lines119 .. versionadded:: 0.8120 The `instance_path` and `instance_relative_config` parameters were121 added.122 121- .. versionadded:: 1.0123+ .. versionadded:: 0.11124 The `root_path` parameter was added.125 126+ .. versionadded:: 0.13127+ The `host_matching` and `static_host` parameters were added.128+129 :param import_name: the name of the application package130 :param static_url_path: can be used to specify a different path for the131 static files on the web. Defaults to the name132 of the `static_folder` folder.133 :param static_folder: the folder with static files that should be served134 at `static_url_path`. Defaults to the ``'static'``135 folder in the root path of the application.136+ folder in the root path of the application. Defaults137+ to None.138+ :param host_matching: sets the app's ``url_map.host_matching`` to the given139+ given value. Defaults to False.140+ :param static_host: the host to use when adding the static route. Defaults141+ to None. Required when using ``host_matching=True``142+ with a ``static_folder`` configured.143 :param template_folder: the folder that contains the templates that should144 be used by the application. Defaults to145 ``'templates'`` folder in the root path of the146 application.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 path10 unmodified lines166 #: The class that is used for response objects. See167 #: :class:`~flask.Response` for more information.168 response_class = Response169 170+ #: The class that is used for the Jinja environment.171+ #:172+ #: .. versionadded:: 0.11173+ jinja_environment = Environment174+175 #: 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 lines207 #: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 = Config213 197- #: 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')222 206- #: 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')234 235 #: 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')242 243 #: 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')248 249 #: 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)258 259+ #: 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)268+269 #: 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')278 279 #: 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')284 258- #: 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 = True262-263- #: 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- )274-285 #: The JSON encoder class to use. Defaults to :class:`~flask.json.JSONEncoder`.286 #:287 #: .. versionadded:: 0.10288 json_encoder = json.JSONEncoder9 unmodified lines298 )299 300 #: Default configuration parameters.301 default_config = ImmutableDict({292- 'DEBUG': False,302+ 'DEBUG': get_debug_flag(default=False),303 'TESTING': False,304 'PROPAGATE_EXCEPTIONS': None,305 'PRESERVE_CONTEXT_ON_EXCEPTION': None,306 'SECRET_KEY': None,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 line316 '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 })331 332 #: 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 lines346 #: .. versionadded:: 0.8347 session_interface = SecureCookieSessionInterface()348 349 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 lines393 # support for the now deprecated `error_handlers` attribute. The394 # :attr:`error_handler_spec` shall be used now.395 self._error_handlers = {}396 383- #: 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}408 409 #: 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 = []417 404- #: 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 = {}424 412- #: 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 = []431 432 #: 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 = {}438 439 #: 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 lines455 #:456 #: .. versionadded:: 0.9457 self.teardown_appcontext_funcs = []458 447- #: 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 = {}467 468 #: 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 also4 unmodified lines478 self.url_default_functions = {}479 480 #: 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 }489 490+ #: 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 = []495+496 #: 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 = []503 504 #: 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 register19 unmodified lines526 #: 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()536 537+ self.url_map.host_matching = host_matching538+539 # tracks internally if the application already handled at least one540 # request.541 self._got_first_request = False542 self._before_request_lock = Lock()543 524- # 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)554 555+ #: 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)562+563 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 lines589 return self.import_name590 591 @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.595 596 .. versionadded:: 0.7597 """3 unmodified lines601 return self.testing or self.debug602 603 @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.608 609 .. versionadded:: 0.731 unmodified lines641 return self.create_jinja_environment()642 643 @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.647 648 .. versionadded:: 0.8649 """44 unmodified lines694 the Jinja2 globals and filters after initialization. Override695 this function to customize the behavior.696 697 .. 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 lines744 :meth:`create_jinja_environment` instead.745 """746 747 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`.750 751 .. versionadded:: 0.5752 """753 if filename is None:723- return False754+ return True755 return filename.endswith(('.html', '.htm', '.xml', '.xhtml'))756 757 def update_template_context(self, context):758 """Update the template context with some commonly used variables.19 unmodified lines778 # easier add new variables in context processors without breaking779 # existing views.780 context.update(orig_ctx)781 782+ 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.786+787+ .. versionadded:: 0.11788+ """789+ rv = {'app': self, 'g': g}790+ for processor in self.shell_context_processors:791+ rv.update(processor())792+ return rv793+794 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.796+797+ 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.800+801+ If the :attr:`debug` flag is set the server will automatically reload802 for code changes and show a debugger in case an exception happened.803 804 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.808 809+ 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.812+813 .. admonition:: Keep in Mind814 815 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.822 823 .. versionchanged:: 0.10824 The default port is now picked from the ``SERVER_NAME`` variable.825 826 :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to827 have the server available externally as well. Defaults 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 lines836 Werkzeug server. See837 :func:`werkzeug.serving.run_simple` for more838 information.839 """840+ # Change this into a no-op if the server is invoked from the841+ # command line. Have a look at cli.py for more information.842+ if os.environ.get('FLASK_RUN_FROM_CLI_SERVER') == '1':843+ from .debughelpers import explain_ignored_app_run844+ explain_ignored_app_run()845+ return846+847 from werkzeug.serving import run_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 = False867 808- 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`.871 872 Note that if you are testing for assertions or exceptions in your6 unmodified lines879 880 app.testing = True881 client = app.test_client()882 823- 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::886 887 with app.test_client() as c:888 rv = c.get('/?vodka=42')889 assert request.args['vodka'] == '42'890 891+ Additionally, you may pass optional keyword arguments that will then892+ be passed to the application's :attr:`test_client_class` constructor.893+ For example::894+895+ from flask.testing import FlaskClient896+897+ class CustomClient(FlaskClient):898+ def __init__(self, *args, **kwargs):899+ self._authentication = kwargs.pop("authentication")900+ super(CustomClient,self).__init__( *args, **kwargs)901+902+ app.test_client_class = CustomClient903+ client = app.test_client(authentication='Basic ....')904+905 See :class:`~flask.testing.FlaskClient` for more information.906 907 .. versionchanged:: 0.4834- added support for `with` block usage for the client.908+ added support for ``with`` block usage for the client.909 910 .. 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.914+915+ .. 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)923 924 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 the23 unmodified lines950 .. versionadded:: 0.7951 """952 return self.session_interface.make_null_session(self)953 876- 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.881-882- .. 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)899-900- self.register_blueprint(module, **options)901-954 @setupmethod955 def register_blueprint(self, blueprint, **options):956 """Registers a blueprint on the application.957 7 unmodified lines965 '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)972 973+ def iter_blueprints(self):974+ """Iterates over all blueprints by the order they were registered.975+976+ .. versionadded:: 0.11977+ """978+ return iter(self._blueprint_order)979+980 @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 lines1009 .. versionchanged:: 0.21010 `view_func` parameter added.1011 1012 .. versionchanged:: 0.6953- `OPTIONS` is added automatically as method.1013+ ``OPTIONS`` is added automatically as method.1014 1015 :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 line1037 methods = options.pop('methods', None)1038 1039 # 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)1048 1049 # Methods that should always be added1050 required_methods = set(getattr(view_func, 'required_methods', ()))1051 1052 # starting with Flask 0.8 the view_func object can disable and1053 # force-enable the automatic options handling.1054+ if provide_automatic_options is None:990- provide_automatic_options = getattr(view_func,991- 'provide_automatic_options', None)1055+ provide_automatic_options = getattr(view_func,1056+ 'provide_automatic_options', None)1057 1058 if provide_automatic_options is None:1059 if 'OPTIONS' not in methods:1060 provide_automatic_options = True33 unmodified lines1094 :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 lines1121 self.view_functions[endpoint] = f1122 return f1123 return decorator1124 1125+ @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_code1132+1133+ assert issubclass(exc_class, Exception)1134+1135+ if issubclass(exc_class, HTTPException):1136+ return exc_class, exc_class.code1137+ else:1138+ return exc_class, None1139+1140 @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::1144 1145 @app.errorhandler(404)1146 def page_not_found(error):16 unmodified lines1163 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.1166 1087- 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.1169 1170 .. versionadded:: 0.71171 Use :meth:`register_error_handler` instead of modifying1172 :attr:`error_handler_spec` directly, for application wide error1173 handlers.1094- 1174+1175 .. 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.1179 1100- :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 f9 unmodified lines1195 self._register_error_handler(None, code_or_exception, f)1196 1197 @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))1209 1210+ exc_class, code = self._get_exc_class_and_code(code_or_exception)1211+1212+ handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})1213+ handlers[exc_class] = f1214+1215 @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 function91 unmodified lines1310 self.jinja_env.globals[name or f.__name__] = f1311 1312 @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.1318+1319+ The function will be called without any arguments. If it returns a1320+ non-None value, the value is handled as if it was the return value from1321+ the view, and further request handling is stopped.1322+ """1323 self.before_request_funcs.setdefault(None, []).append(f)1324 return f1325 1326 @setupmethod1327 def before_first_request(self, f):1328 """Registers a function to be run before the first request to this1329 instance of the application.1330 1331+ The function will be called without any arguments and its return1332+ value is ignored.1333+1334 .. versionadded:: 0.81335 """1336 self.before_first_request_funcs.append(f)1337 return f35 unmodified lines1373 that they will fail. If they do execute code that might fail they1374 will have to surround the execution of these code by try/except1375 statements and log occurring errors.1376 1280- When a teardown function was called because of a exception it will1377+ When a teardown function was called because of an exception it will1378 be passed an error object.1379 1380+ The return values of teardown functions are ignored.1381+1382 .. admonition:: Debug Note1383 1384 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 lines1412 1413 When a teardown function was called because of an exception it will1414 be passed an error object.1415 1416+ The return values of teardown functions are ignored.1417+1418 .. versionadded:: 0.91419 """1420 self.teardown_appcontext_funcs.append(f)1421 return f4 unmodified lines1426 self.template_context_processors[None].append(f)1427 return f1428 1429 @setupmethod1430+ def shell_context_processor(self, f):1431+ """Registers a shell context processor function.1432+1433+ .. versionadded:: 0.111434+ """1435+ self.shell_context_processors.append(f)1436+ return f1437+1438+ @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 lines1460 """1461 self.url_default_functions.setdefault(None, []).append(f)1462 return f1463 1464+ 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))1470+1471+ 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 handler1480+1481+ # try blueprint handlers1482+ handler = find_handler(self.error_handler_spec1483+ .get(request.blueprint, {})1484+ .get(code))1485+ if handler is not None:1486+ return handler1487+1488+ # fall back to app handlers1489+ return find_handler(self.error_handler_spec[None].get(code))1490+1491 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.1495 1496 .. 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)1502+1503+ handler = self._find_error_handler(e)1504 if handler is None:1505 return e1506 return handler(e)1507 1508 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``.1513 1514 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 lines1541 # 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.1545+1546 if isinstance(e, HTTPException) and not self.trap_http_exception(e):1547 return self.handle_http_exception(e)1548 1406- 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)1550 1551+ if handler is None:1415- reraise(exc_type, exc_value, tb)1552+ reraise(exc_type, exc_value, tb)1553+ return handler(e)1554 1555 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 will5 unmodified lines1563 """1564 exc_type, exc_value, tb = sys.exc_info()1565 1566 got_request_exception.send(self, exception=e)1429- handler = self.error_handler_spec[None].get(500)1567+ handler = self._find_error_handler(InternalServerError())1568 1569 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 that6 unmodified lines1578 1579 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)1583 1584 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 lines1646 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)1651+1652+ 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.1657+1658+ 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.1662+1663+ :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 response1675 1676 def try_trigger_before_first_request_functions(self):1677 """Called before each request and will ensure that it triggers11 unmodified lines1689 func()1690 self._got_first_request = True1691 1692 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.1696 1697 .. versionadded:: 0.71698 """1699 adapter = _request_ctx_stack.top.url_adapter14 unmodified lines1714 1715 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.1720 1721 .. versionadded:: 0.101722 """1723 return False1724 1725 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`.1728 1570- The following types are allowed for `rv`:1729+ :param rv: the return value from the view function. The view function1730+ must return a response. Returning ``None``, or the view ending1731+ without returning, is not allowed. The following types are allowed1732+ for ``view_rv``:1733 1572- .. tabularcolumns:: |p{3.5cm}|p{9.5cm}|1734+ ``str`` (``unicode`` in Python 2)1735+ A response object is created with the string encoded to UTF-81736+ as the body.1737+ 1738+ ``bytes`` (``str`` in Python 2)1739+ A response object is created with the bytes as the body.1740+ 1741+ ``tuple``1742+ Either ``(body, status, headers)``, ``(body, status)``, or1743+ ``(body, headers)``, where ``body`` is any of the other types1744+ allowed here, ``status`` is a string or an integer, and1745+ ``headers`` is a dictionary or a list of ``(key, value)``1746+ tuples. If ``body`` is a :attr:`response_class` instance,1747+ ``status`` overwrites the exiting value and ``headers`` are1748+ extended.1749+ 1750+ :attr:`response_class`1751+ The object is returned unchanged.1752+ 1753+ other :class:`~werkzeug.wrappers.Response` class1754+ The object is coerced to :attr:`response_class`.1755+ 1756+ :func:`callable`1757+ The function is called as a WSGI application. The result is1758+ used to create a response object.1759 1574- ======================= ===========================================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- ======================= ===========================================1589-1590- :param rv: the return value from the view function1591-1760 .. 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))1764 1600- if rv is None:1601- raise ValueError('View function did not return a response')1765+ status = headers = None1766 1603- 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)1770 1771+ # a 3-tuple is unpacked directly1772+ if len_rv == 3:1773+ rv, status, headers = rv1774+ # decide if a 2-tuple has status or headers1775+ elif len_rv == 2:1776+ if isinstance(rv[1], (Headers, dict, tuple, list)):1777+ rv, headers = rv1778+ else:1779+ rv, status = rv1780+ # other sized tuples are not allowed1781+ else:1782+ raise TypeError(1783+ 'The view function did not return a valid response tuple.'1784+ ' The tuple must have the form (body, status, headers),'1785+ ' (body, status), or (body, headers).'1786+ )1787+1788+ # the body must not be None1789+ if rv is None:1790+ raise TypeError(1791+ 'The view function did not return a valid response. The'1792+ ' function either returned None or ended without a return'1793+ ' statement.'1794+ )1795+1796+ # make sure the body is an instance of the response class1797 if not isinstance(rv, self.response_class):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])1817 1818+ # 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 = status1824+1825+ # extend existing headers with provided headers1826 if headers:1827 rv.headers.extend(headers)1828 1829 return rv1830 1627-1831 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 lines1872 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 = e1879 1880 # 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 line1884 reraise(exc_type, exc_value, tb)1885 raise error1886 1887 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.1689-1690- 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 """1897+1898 bp = _request_ctx_stack.top.request.blueprint1899 1900 funcs = self.url_value_preprocessors.get(None, ())1901 if bp is not None and bp in self.url_value_preprocessors:34 unmodified lines1936 if not self.session_interface.is_null_session(ctx.session):1937 self.save_session(ctx.session, response)1938 return response1939 1735- 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 a2 unmodified lines1947 .. 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 line1957 for func in funcs:1958 func(exc)1959 request_tearing_down.send(self, exc=exc)1960 1756- 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.1965 1966 .. 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 lines1988 1989 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.1994 1995 Example usage::1996 1997 with app.request_context(environ):1998 do_something_with(request)1999 1795- 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::2003 2004 ctx = app.request_context(environ)3 unmodified lines2008 finally:2009 ctx.pop()2010 2011 .. 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.2014 2015 :param environ: a WSGI environment2016 """36 unmodified lines2053 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)2073 1866- @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.blueprints1872-2074 def __call__(self, environ, start_response):2075 """Shortcut for :attr:`wsgi_app`."""2076 return self.wsgi_app(environ, start_response)2077 5 unmodified linesmodified:flask/blueprints.py+9 added-3 removed
4 unmodified lines5 6 Blueprints are the recommended way to implement larger or more7 pluggable applications in Flask 0.7 and later.8 9- :copyright: (c) 2014 by Armin Ronacher.9+ :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11 """12 from functools import update_wrapper13 27 unmodified lines41 subdomain = self.options.get('subdomain')42 if subdomain is None:43 subdomain = self.blueprint.subdomain44 45- #: 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 = subdomain48 49 url_prefix = self.options.get('url_prefix')38 unmodified lines88 89 warn_on_modifications = False90 _got_registered_once = False91 92+ #: Blueprint local JSON decoder class to use.93+ #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_encoder`.94+ json_encoder = None95+ #: Blueprint local JSON decoder class to use.96+ #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_decoder`.97+ json_decoder = None98+99 def __init__(self, name, import_name, static_folder=None,100 static_url_path=None, template_folder=None,101 url_prefix=None, subdomain=None, url_defaults=None,102 root_path=None):4 unmodified lines107 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 linesadded:flask/cli.py+580 added
1+# -*- coding: utf-8 -*-2+"""3+ flask.cli4+ ~~~~~~~~~5+6+ A simple command line application to run flask apps.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import os13+import sys14+import traceback15+from functools import update_wrapper16+from operator import attrgetter17+from threading import Lock, Thread18+19+import click20+21+from . import __version__22+from ._compat import iteritems, reraise23+from .globals import current_app24+from .helpers import get_debug_flag25+26+27+class NoAppException(click.UsageError):28+ """Raised if an application cannot be found or loaded."""29+30+31+def 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 Flask36+37+ # 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 app42+43+ # 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)]46+47+ 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__)53+54+55+def 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 = []60+61+ # 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)72+73+ 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+ break79+80+ sys.path.insert(0, dirpath)81+ return '.'.join(module[::-1])82+83+84+def 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 = None92+93+ 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)107+108+ 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)116+117+ return app118+119+120+def 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 app127+128+129+def 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()138+139+version_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)144+145+class 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+ """151+152+ 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()161+162+ 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()172+173+ 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)179+180+ def _load_unlocked(self):181+ __traceback_hide__ = True182+ self._app = rv = self.loader()183+ self._bg_loading_exc_info = None184+ return rv185+186+ 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)197+198+199+class 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+ """207+208+ 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 = None215+216+ #: 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 = None225+226+ 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 rv249+250+251+pass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True)252+253+254+def 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)265+266+267+class 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`.271+272+ Not to be confused with :class:`FlaskGroup`.273+ """274+275+ 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 decorator286+287+ 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)294+295+296+class 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.302+303+ For information as of why this is useful see :ref:`custom-scripts`.304+305+ :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+ """311+312+ def __init__(self, add_default_commands=True, create_app=None,313+ add_version_option=True, **extra):314+ params = list(extra.pop('params', None) or ())315+316+ if add_version_option:317+ params.append(version_option)318+319+ AppGroup.__init__(self, params=params, **extra)320+ self.create_app = create_app321+322+ if add_default_commands:323+ self.add_command(run_command)324+ self.add_command(shell_command)325+ self.add_command(routes_command)326+327+ self._loaded_plugin_commands = False328+329+ def _load_plugin_commands(self):330+ if self._loaded_plugin_commands:331+ return332+ try:333+ import pkg_resources334+ except ImportError:335+ self._loaded_plugin_commands = True336+ return337+338+ for ep in pkg_resources.iter_entry_points('flask.commands'):339+ self.add_command(ep.load(), ep.name)340+ self._loaded_plugin_commands = True341+342+ def get_command(self, ctx, name):343+ self._load_plugin_commands()344+345+ # 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 rv355+356+ 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+ pass363+364+ def list_commands(self, ctx):365+ self._load_plugin_commands()366+367+ # 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)382+383+ 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)390+391+392+@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_info409+def run_command(info, host, port, reload, debugger, eager_loading,410+ with_threads):411+ """Runs a local development server for the Flask application.412+413+ 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.418+419+ 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_simple423+424+ # Set a global flag that indicates that we were invoked from the425+ # command line interface provided server command. This is detected426+ # by Flask.run to make the call into a no-op. This is necessary to427+ # avoid ugly errors when the script that is loaded here also attempts428+ # to start a server.429+ os.environ['FLASK_RUN_FROM_CLI_SERVER'] = '1'430+431+ debug = get_debug_flag()432+ if reload is None:433+ reload = bool(debug)434+ if debugger is None:435+ debugger = bool(debug)436+ if eager_loading is None:437+ eager_loading = not reload438+439+ app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)440+441+ # 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'))452+453+ run_simple(host, port, app, use_reloader=reload,454+ use_debugger=debugger, threaded=with_threads)455+456+457+@click.command('shell', short_help='Runs a shell in the app context.')458+@with_appcontext459+def 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.463+464+ 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 = {}478+479+ # 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)485+486+ ctx.update(app.make_shell_context())487+488+ code.interact(banner=banner, local=ctx)489+490+491+@click.command('routes', short_help='Show the routes for the app.')492+@click.option(493+ '--sort', '-s',494+ type=click.Choice(('endpoint', 'methods', 'rule', 'match')),495+ default='endpoint',496+ help=(497+ 'Method to sort routes by. "match" is the order that Flask will match '498+ 'routes when dispatching a request.'499+ )500+)501+@click.option(502+ '--all-methods',503+ is_flag=True,504+ help="Show HEAD and OPTIONS methods."505+)506+@with_appcontext507+def routes_command(sort, all_methods):508+ """Show all registered routes with endpoints and methods."""509+510+ rules = list(current_app.url_map.iter_rules())511+ ignored_methods = set(() if all_methods else ('HEAD', 'OPTIONS'))512+513+ if sort in ('endpoint', 'rule'):514+ rules = sorted(rules, key=attrgetter(sort))515+ elif sort == 'methods':516+ rules = sorted(rules, key=lambda rule: sorted(rule.methods))517+518+ rule_methods = [519+ ', '.join(sorted(rule.methods - ignored_methods)) for rule in rules520+ ]521+522+ headers = ('Endpoint', 'Methods', 'Rule')523+ widths = (524+ max(len(rule.endpoint) for rule in rules),525+ max(len(methods) for methods in rule_methods),526+ max(len(rule.rule) for rule in rules),527+ )528+ widths = [max(len(h), w) for h, w in zip(headers, widths)]529+ row = '{{0:<{0}}} {{1:<{1}}} {{2:<{2}}}'.format(*widths)530+531+ click.echo(row.format(*headers).strip())532+ click.echo(row.format(*('-' * width for width in widths)))533+534+ for rule, methods in zip(rules, rule_methods):535+ click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())536+537+538+cli = FlaskGroup(help="""\539+This shell command acts as general utility script for Flask applications.540+541+It loads the application configured (through the FLASK_APP environment542+variable) and then provides commands either provided by the application or543+Flask itself.544+545+The most useful commands are the "run" and "shell" command.546+547+Example usage:548+549+\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+})557+558+559+def main(as_module=False):560+ this_module = __package__ + '.cli'561+ args = sys.argv[1:]562+563+ 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_module568+569+ # 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 = None575+576+ cli.main(args=args, prog_name=name)577+578+579+if __name__ == '__main__':580+ main(as_module=True)modified:flask/config.py+51 added-21 removed
3 unmodified lines4 ~~~~~~~~~~~~5 6 Implements the configuration related objects.7 8- :copyright: (c) 2014 by Armin Ronacher.8+ :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12-import imp12 import os13+import types14 import errno15 16 from werkzeug.utils import import_string17 from ._compat import string_types, iteritems74 unmodified lines92 93 app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])94 95 :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 lines115 116 :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.121 122 .. 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 False8 unmodified lines142 143 - a string: in this case the object with that name will be imported144 - an actual object reference: that object is used directly145 146- Objects are usually either modules or classes.146+ Objects are usually either modules or classes. :meth:`from_object`147+ loads only the uppercase attributes of the module/class. A ``dict``148+ object will not work with :meth:`from_object` because the keys of a149+ ``dict`` are not attributes of the ``dict`` class.150 148- Just the uppercase variables in that object are stored in the config.149- Example usage::151+ Example of module-based configuration::152 153 app.config.from_object('yourapplication.default_config')154 from yourapplication import default_config155 app.config.from_object(default_config)2 unmodified lines158 rather configuration defaults. The actual config should be loaded159 with :meth:`from_pyfile` and ideally from a location not within the160 package because the package might be installed system wide.161 162+ See :ref:`config-dev-prod` for an example of class-based configuration163+ using :meth:`from_object`.164+165 :param obj: an import name or object166 """167 if isinstance(obj, string_types):168 obj = import_string(obj)2 unmodified lines171 self[key] = getattr(obj, key)172 173 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.177 178 :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.183 179- .. versionadded:: 1.0184+ .. versionadded:: 0.11185 """186 filename = os.path.join(self.root_path, filename)187 188 try:3 unmodified lines192 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)197+198+ def from_mapping(self, *mapping, **kwargs):199+ """Updates the config like :meth:`update` ignoring items with non-upper200+ keys.201+202+ .. 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 True220 196- 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::224 225 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_')229 205- The resulting dictionary `image_store` would look like::230+ The resulting dictionary `image_store_config` would look like::231 232 {233 'type': 'fs',234 'path': '/var/app/images',5 unmodified lines240 241 :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 namespace246 220- .. 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 rv3 unmodified linesmodified:flask/ctx.py+56 added-52 removed
3 unmodified lines4 ~~~~~~~~~5 6 Implements the objects required to keep the context.7 8- :copyright: (c) 2014 by Armin Ronacher.8+ :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12-from __future__ import with_statement13-12 import sys13 from functools import update_wrapper14 15 from werkzeug.exceptions import HTTPException16 17 from .globals import _request_ctx_stack, _app_ctx_stack20-from .module import blueprint_is_module18 from .signals import appcontext_pushed, appcontext_popped19 from ._compat import BROKEN_PYPY_CTXMGR_EXIT, reraise20 21 22+# a singleton sentinel value for parameter defaults23+_sentinel = object()24+25+26 class _AppCtxGlobals(object):27 """A plain object."""28 29 def get(self, name, default=None):30 return self.__dict__.get(name, default)31 32+ 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)37+38+ def setdefault(self, name, default=None):39+ return self.__dict__.setdefault(name, default)40+41 def __contains__(self, item):42 return item in self.__dict__43 44 def __iter__(self):133 unmodified lines178 sys.exc_clear()179 _app_ctx_stack.push(self)180 appcontext_pushed.send(self.app)181 172- 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 lines221 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 lines263 self._after_request_functions = []264 265 self.match_request()266 255- # 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 = True264-267 def _get_g(self):268 return _app_ctx_stack.top.g269 def _set_g(self, value):270 _app_ctx_stack.top.g = value32 unmodified lines303 # 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 lines332 self.session = self.app.open_session(self.request)333 if self.session is None:334 self.session = self.app.make_null_session()335 334- 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 line342 Added the `exc` argument.343 """344 app_ctx = self._implicit_app_ctx_stack.pop()345 346+ try:344- clear_request = False345- if not self._implicit_app_ctx_stack:346- self.preserved = False347- self._preserved_exc = None348- if exc is 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)354 352- # If this interpreter supports clearing the exception information353- # we do that now. This will only go into effect on Python 2.x,354- # on 3.x it disappears automatically at the end of the exception355- # stack.356- if hasattr(sys, 'exc_clear'):357- sys.exc_clear()355+ # If this interpreter supports clearing the exception information356+ # we do that now. This will only go into effect on Python 2.x,357+ # on 3.x it disappears automatically at the end of the exception358+ # stack.359+ if hasattr(sys, 'exc_clear'):360+ sys.exc_clear()361 359- request_close = getattr(self.request, 'close', None)360- if request_close is not None:361- request_close()362- clear_request = True362+ request_close = getattr(self.request, 'close', None)363+ if request_close is not None:364+ request_close()365+ clear_request = True366+ finally:367+ rv = _request_ctx_stack.pop()368 364- rv = _request_ctx_stack.pop()365- assert rv is self, 'Popped wrong request context. (%r instead of %r)' \366- % (rv, self)369+ # get rid of circular dependencies at the end of the request370+ # so that we don't require the GC to be active.371+ if clear_request:372+ rv.request.environ['werkzeug.request'] = None373 368- # get rid of circular dependencies at the end of the request369- # so that we don't require the GC to be active.370- if clear_request:371- rv.request.environ['werkzeug.request'] = None374+ # Get rid of the app as well if necessary.375+ if app_ctx is not None:376+ app_ctx.pop(exc)377 373- # Get rid of the app as well if necessary.374- if app_ctx is not None:375- app_ctx.pop(exc)378+ assert rv is self, 'Popped wrong request context. ' \379+ '(%r instead of %r)' % (rv, self)380 381 def auto_pop(self, exc):382 if self.request.environ.get('flask._preserve_context') or \383 (exc is not None and self.app.preserve_context_on_exception):27 unmodified linesmodified:flask/debughelpers.py+82 added-2 removed
3 unmodified lines4 ~~~~~~~~~~~~~~~~~~5 6 Various helpers to make the development experience better.7 8- :copyright: (c) 2014 by Armin Ronacher.8+ :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11-from ._compat import implements_to_string11+import os12+from warnings import warn13 14+from ._compat import implements_to_string, text_type15+from .app import Flask16+from .blueprints import Blueprint17+from .globals import _request_ctx_stack18 19+20 class UnexpectedUnicodeError(AssertionError, UnicodeError):21 """Raised in places where we want some better error reporting for22 unexpected unicode or binary data.23 """66 unmodified lines90 raise DebugFilesKeyError(request, key)91 newcls.__name__ = oldcls.__name__92 newcls.__module__ = oldcls.__module__93 request.files.__class__ = newcls94+95+96+def _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)111+112+113+def 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.blueprint121+122+ 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)130+131+ info.append('% 5d: trying loader of %s' % (132+ idx + 1, src_info))133+134+ for line in _dump_loader_info(loader):135+ info.append(' %s' % line)136+137+ 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)143+144+ 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 = True151+152+ 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')157+158+ app.logger.info('\n'.join(info))159+160+161+def explain_ignored_app_run():162+ if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':163+ warn(Warning('Silently ignoring app.run() because the '164+ 'application is run from the flask command line '165+ 'executable. Consider putting app.run() behind an '166+ 'if __name__ == "__main__" guard to silence this '167+ 'warning.'), stacklevel=3)modified:flask/exthook.py+26 added-3 removed
14 unmodified lines15 everybody involved.16 17 This is used by `flask.ext`.18 19- :copyright: (c) 2014 by Armin Ronacher.19+ :copyright: (c) 2015 by Armin Ronacher.20 :license: BSD, see LICENSE for more details.21 """22 import sys23 import os24+import warnings25 from ._compat import reraise26 27 28+class ExtDeprecationWarning(DeprecationWarning):29+ pass30+31+warnings.simplefilter('always', ExtDeprecationWarning)32+33+34 class ExtensionImporter(object):35 """This importer redirects imports from this submodule to other locations.36 This makes it possible to transition from the old flaskext.name to the37 newer flask_name without people having a hard time.17 unmodified lines55 def install(self):56 sys.meta_path[:] = [x for x in sys.meta_path if self != x] + [self]57 58 def find_module(self, fullname, path=None):52- if fullname.startswith(self.prefix):59+ if fullname.startswith(self.prefix) and \60+ fullname != 'flask.ext.ExtDeprecationWarning':61 return self62 63 def load_module(self, fullname):64 if fullname in sys.modules:65 return sys.modules[fullname]66+67 modname = fullname.split('.', self.prefix_cutoff)[self.prefix_cutoff]68+69+ warnings.warn(70+ "Importing flask.ext.{x} is deprecated, use flask_{x} instead."71+ .format(x=modname), ExtDeprecationWarning, stacklevel=272+ )73+74 for path in self.module_choices:75 realname = path % modname76 try:77 __import__(realname)19 unmodified lines97 continue98 module = sys.modules[fullname] = sys.modules[realname]99 if '.' not in modname:100 setattr(sys.modules[self.wrapper_module], modname, module)101+102+ if realname.startswith('flaskext.'):103+ warnings.warn(104+ "Detected extension named flaskext.{x}, please rename it "105+ "to flask_{x}. The old form is deprecated."106+ .format(x=modname), ExtDeprecationWarning107+ )108+109 return module110 raise ImportError('No module named %s' % fullname)111 112 def is_important_traceback(self, important_module, tb):20 unmodified lines133 # name shows up properly here. Success!134 if module_name == important_module:135 return True136 114- # 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 linesmodified:flask/globals.py+21 added-4 removed
4 unmodified lines5 6 Defines all the global objects that are proxies to the current7 active context.8 9- :copyright: (c) 2014 by Armin Ronacher.9+ :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11 """12 13 from functools import partial14 from werkzeug.local import LocalStack, LocalProxy15 16 17+_request_ctx_err_msg = '''\18+Working outside of request context.19+20+This typically means that you attempted to use functionality that needed21+an active HTTP request. Consult the documentation on testing for22+information about how to avoid this problem.\23+'''24+_app_ctx_err_msg = '''\25+Working outside of application context.26+27+This typically means that you attempted to use functionality that needed28+to interface with the current application object in a way. To solve29+this set up an application context with app.app_context(). See the30+documentation for more information.\31+'''32+33+34 def _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)39 40 41 def _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)46 47 48 def _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.app53 54 55 # context locals6 unmodified linesmodified:flask/helpers.py+218 added-111 removed
3 unmodified lines4 ~~~~~~~~~~~~~5 6 Implements various helpers.7 8- :copyright: (c) 2014 by Armin Ronacher.8+ :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12 import os13+import socket14 import sys15 import pkgutil16 import posixpath17 import mimetypes18 from time import time19 from zlib import adler3220 from threading import RLock21+import unicodedata22 from werkzeug.routing import BuildError23 from functools import update_wrapper24 25 try:26 from werkzeug.urls import url_quote27 except ImportError:28 from urlparse import quote as url_quote29 28-from werkzeug.datastructures import Headers29-from werkzeug.exceptions import NotFound30+from werkzeug.datastructures import Headers, Range31+from werkzeug.exceptions import BadRequest, NotFound, \32+ RequestedRangeNotSatisfiable33 34 # this was moved in 0.735 try:36 from werkzeug.wsgi import wrap_file18 unmodified lines55 _os_alt_seps = list(sep for sep in [os.path.sep, os.path.altsep]56 if sep not in (None, '/'))57 58 59+def 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')64+65+66 def _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 lines109 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)116 117 def generator():79 unmodified lines197 """Generates a URL to the given endpoint with the method provided.198 199 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 (``.``).204 205 This will reference the index function local to the current blueprint::6 unmodified lines212 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 lines253 :exc:`~werkzeug.routing.BuildError`.254 255 :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.top3 unmodified lines273 'application context being pushed. This has to be '274 'executed when application context is available.')275 276 # 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 lines293 endpoint = endpoint[1:]294 external = values.pop('_external', False)295 296 # 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 lines308 method = values.pop('_method', None)309 scheme = values.pop('_scheme', None)310 appctx.app.inject_url_defaults(endpoint, values)311 312+ # 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 = scheme321 322 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)337 338 if anchor is not None:339 rv += '#' + url_quote(anchor)2 unmodified lines342 343 def 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:347 348 .. sourcecode:: html+jinja349 350 {% macro hello(name) %}Hello {{ name }}!{% endmacro %}44 unmodified lines395 def 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.401 402 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:406 407 * `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.411 412 See :ref:`message-flashing-pattern` for examples.3 unmodified lines416 417 .. versionchanged:: 0.9418 `category_filter` parameter added.419 396- :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 lines432 433 434 def 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``.443 444 By default it will try to guess the mimetype for you, but you can445 also explicitly provide one. For extra security you probably want446 to send certain files as attachment (HTML for instance). The mimetype447 guessing requires a `filename` or an `attachment_filename` to be448 provided.449 426- 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`.452 430- 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.456 457+ Please never pass filenames to this function from user sources;458+ you should use :func:`send_from_directory` instead.459+460 .. versionadded:: 0.2461 462 .. versionadded:: 0.5463 The `add_etags`, `cache_timeout` and `conditional` parameters were7 unmodified lines471 472 .. versionchanged:: 0.9473 cache_timeout pulls its default from application config, when None.474 448- :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`.479+480+ .. versionchanged:: 0.12481+ The `attachment_filename` is preferred over `filename` for MIME-type482+ detection.483+ 484+ .. versionchanged:: 0.13485+ UTF-8 filenames, as specified in `RFC 2231`_, are supported.486+ 487+ .. _RFC 2231: https://tools.ietf.org/html/rfc2231#section-4488+489+ :param filename_or_fp: the filename of the file to send.490+ This is relative to the :attr:`~Flask.root_path`491+ if a relative path is specified.492+ Alternatively a file object might be provided in493+ which case ``X-Sendfile`` might not work and fall494+ back to the traditional method. Make sure that the495+ file pointer is positioned at the start of data to496+ send before calling :func:`send_file`.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.506 465- :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 = None527 479- # 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)493-494- 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'532 533+ if mimetype is None:534+ raise ValueError(535+ 'Unable to infer MIME-type because no filename is available. '536+ 'Please set either `attachment_filename`, pass a filepath to '537+ '`filename_or_fp` or set your own MIME-type via `mimetype`.'538+ )539+540 headers = Headers()541 if as_attachment:542 if attachment_filename is None: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)545 546+ try:547+ attachment_filename = attachment_filename.encode('latin-1')548+ except UnicodeEncodeError:549+ filenames = {550+ 'filename': unicodedata.normalize(551+ 'NFKD', attachment_filename).encode('latin-1', 'ignore'),552+ 'filename*': "UTF-8''%s" % url_quote(attachment_filename),553+ }554+ else:555+ filenames = {'filename': attachment_filename}556+557+ headers.add('Content-Disposition', 'attachment', **filenames)558+559 if current_app.use_x_sendfile and filename:560 if file is not None:561 file.close()562 headers['X-Sendfile'] = 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)573 574 rv = current_app.response_class(data, mimetype=mimetype, headers=headers,575 direct_passthrough=True)576 528- # 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 = mtime581 582 rv.cache_control.public = True583 if cache_timeout is None:584 cache_timeout = current_app.get_send_file_max_age(filename)1 unmodified line586 rv.cache_control.max_age = cache_timeout587 rv.expires = int(time() + cache_timeout)588 589 if add_etags and filename is not None:590+ from warnings import warn591+592 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 lines601 except OSError:602 warn('Access %s failed, maybe it does not exist, so ignore etags in '603 'headers' % filename, stacklevel=2)604 554- 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 rv622 623 563-def safe_join(directory, filename):564- """Safely join `directory` and `filename`.624+def safe_join(directory, *pathnames):625+ """Safely join `directory` and zero or more untrusted `pathnames`626+ components.627 628 Example usage::629 630 @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...635 574- :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:641+642+ parts = [directory]643+644+ for filename in pathnames:645+ if filename != '':646+ filename = posixpath.normpath(filename)647+648+ if (649+ any(sep in filename for sep in _os_alt_seps)650+ or os.path.isabs(filename)651+ or filename == '..'652+ or filename.startswith('../')653+ ):654 raise NotFound()583- if os.path.isabs(filename) or \584- filename == '..' or \585- filename.startswith('../'):586- raise NotFound()587- return os.path.join(directory, filename)655 656+ parts.append(filename)657 658+ return posixpath.join(*parts)659+660+661 def send_from_directory(directory, filename, **options):662 """Send a file from a given directory with :func:`send_file`. This663 is a secure way to quickly expose static files from an upload folder664 or something similar.6 unmodified lines671 filename, as_attachment=True)672 673 .. admonition:: Sending files and Performance674 604- 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 lines687 """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)698 699 35 unmodified lines735 '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)741 742 # 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 lines795 __import__(import_name)796 filename = sys.modules[import_name].__file__797 package_path = os.path.abspath(os.path.dirname(filename))798 725- # 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 lines853 #: The name of the package or module. Do not change this once854 #: it was set by the constructor.855 self.import_name = import_name856 783- #: 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_folder860 861 if root_path is None:9 unmodified lines871 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_folder879 880 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_path889 890 @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.894 895 .. versionadded:: 0.5896 """897 return self.static_folder is not None15 unmodified lines913 the configuration of :data:`~flask.current_app`.914 915 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.920 921 This allows subclasses to change the behavior when sending files based7 unmodified lines929 return flask.Flask.get_send_file_max_age(self, name)930 931 .. versionadded:: 0.9932 """858- return current_app.config['SEND_FILE_MAX_AGE_DEFAULT']933+ return total_seconds(current_app.send_file_max_age_default)934 935 def send_static_file(self, filename):936 """Function used internally to send static files from the static937 folder to the browser.19 unmodified lines957 /templates958 /layout.html959 /index.html960 886- 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::963 964 with app.open_resource('schema.sql') as f:965 contents = f.read()5 unmodified lines971 """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)975+976+977+def total_seconds(td):978+ """Returns the total seconds from a timedelta object.979+980+ :param timedelta td: the timedelta to be converted in seconds981+982+ :returns: number of seconds983+ :rtype: int984+ """985+ return td.days * 60 * 60 * 24 + td.seconds986+987+988+def is_ip(value):989+ """Determine if the given string is an IP address.990+991+ :param value: value to check992+ :type value: str993+994+ :return: True if string is an IP address995+ :rtype: bool996+ """997+998+ 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 True1005+1006+ return Falsemodified:flask/json.py+65 added-28 removed
1 # -*- coding: utf-8 -*-2 """3- flask.jsonimpl4- ~~~~~~~~~~~~~~3+ flask.json4+ ~~~~~~~~~~5 6 Implementation helpers for the JSON support in Flask.7 8- :copyright: (c) 2014 by Armin Ronacher.8+ :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 import io12 import uuid13-from datetime import datetime13+from datetime import date14 from .globals import current_app, request15 from ._compat import text_type, PY216 17 from werkzeug.http import http_date18 from jinja2 import Markup19 20 # Use the same json implementation as itsdangerous on which we21 # depend anyways.22-try:23- from itsdangerous import simplejson as _json24-except ImportError:25- from itsdangerous import json as _json22+from itsdangerous import json as _json23 24 25 # Figure out if simplejson escapes slashes. This behavior was changed26 # from one version to another without reason.29 unmodified lines56 57 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`).61 62 For example, to support arbitrary iterators, you could implement63 default like this::64 5 unmodified lines70 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 line81 82 83 class 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 """89 90 91 def _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+ )100+101 if not current_app.config['JSON_AS_ASCII']:102 kwargs.setdefault('ensure_ascii', False)103+104 kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS'])105 else:106 kwargs.setdefault('sort_keys', True)107 kwargs.setdefault('cls', JSONEncoder)1 unmodified line109 110 def _load_arg_defaults(kwargs):111 """Inject default arguments for load functions."""112 if current_app: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)121 122 80 unmodified lines203 204 205 def 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)))208 209 210 def 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]``.217 218+ For clarity, the JSON serialization behavior has the following differences219+ from :func:`dumps`:220+221+ 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.227+228 Example usage::229 230 from flask import jsonify231 10 unmodified lines242 "email": "admin@localhost",243 "id": 42244 }245 224- For security reasons only objects are supported toplevel. For more225- information about this, have a look at :ref:`json-security`.246 227- 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.250 251+ This function's response will be pretty printed if the252+ ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to True or the253+ Flask app is running in debug mode. Compressed (not pretty) formatting254+ currently means no indents and no spaces after separators.255+256 .. versionadded:: 0.2257 """258+259 indent = None234- if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] \235- and not request.is_xhr:260+ separators = (',', ':')261+262+ 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 = (', ', ': ')265 266+ 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 kwargs272 273+ return current_app.response_class(274+ (dumps(data, indent=indent, separators=separators), '\n'),275+ mimetype=current_app.config['JSONIFY_MIMETYPE']276+ )277+278+279 def tojson_filter(obj, **kwargs):280 return Markup(htmlsafe_dumps(obj, **kwargs))modified:flask/logging.py+60 added-11 removed
3 unmodified lines4 ~~~~~~~~~~~~~5 6 Implements the logging support for Flask.7 8- :copyright: (c) 2014 by Armin Ronacher.8+ :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12 from __future__ import absolute_import13 14-from logging import getLogger, StreamHandler, Formatter, getLoggerClass, DEBUG14+import sys15 16+from werkzeug.local import LocalProxy17+from logging import getLogger, StreamHandler, Formatter, getLoggerClass, \18+ DEBUG, ERROR19+from .globals import _request_ctx_stack20 21+22+PROD_LOG_FORMAT = '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'23+DEBUG_LOG_FORMAT = (24+ '-' * 80 + '\n' +25+ '%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n' +26+ '%(message)s\n' +27+ '-' * 8028+)29+30+31+@LocalProxy32+def _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.stderr41+42+43+def _should_log_for(app, mode):44+ policy = app.config['LOGGER_HANDLER_POLICY']45+ if policy == mode or policy == 'always':46+ return True47+ return False48+49+50 def 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 this2 unmodified lines56 """57 Logger = getLoggerClass()58 59 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)64 65 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)69 70+ class ProductionHandler(StreamHandler):71+ def emit(self, record):72+ if not app.debug and _should_log_for(app, 'production'):73+ StreamHandler.emit(self, record)74+36- 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))78+79+ prod_handler = ProductionHandler(_proxy_stream)80+ prod_handler.setLevel(ERROR)81+ prod_handler.setFormatter(Formatter(PROD_LOG_FORMAT))82+83 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)90+91+ # Disable propagation by default92+ logger.propagate = False93+94 return loggerdeleted:flask/module.py-42 removed
1-# -*- coding: utf-8 -*-2-"""3- flask.module4- ~~~~~~~~~~~~5-6- Implements a class that represents module blueprints.7-8- :copyright: (c) 2014 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-12-import os13-14-from .blueprints import Blueprint15-16-17-def blueprint_is_module(bp):18- """Used to figure out if something is actually a module"""19- return isinstance(bp, Module)20-21-22-class 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.27-28- .. versionchanged:: 0.729- Modules were deprecated in favor for blueprints.30- """31-32- 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')40-41- 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 lines4 ~~~~~~~~~~~~~~5 6 Implements cookie based sessions based on itsdangerous.7 8- :copyright: (c) 2014 by Armin Ronacher.8+ :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12 import uuid13 import hashlib14+import warnings15 from base64 import b64encode, b64decode16 from datetime import datetime17 from werkzeug.http import http_date, parse_date18 from werkzeug.datastructures import CallbackDict19 from . import Markup, json20 from ._compat import iteritems, text_type21+from .helpers import total_seconds, is_ip22 23 from itsdangerous import URLSafeTimedSerializer, BadSignature24 25 24-def total_seconds(td):25- return td.days * 60 * 60 * 24 + td.seconds26-27-26 class SessionMixin(object):27 """Expands a basic dictionary with an accessors that are expected28 by Flask extensions and users for the session.29 """9 unmodified lines39 del _get_permanent, _set_permanent40 41 #: 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 = False45 48- #: 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 = True51 52 #: 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 lines56 #: session cookie as keys when caching pages, preventing multiple users57 #: from being served the same cache.58 accessed = True59 60+def _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 value85+86+87 class 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 """91 92 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=(',', ':'))94 95+ LOADS_MAP = {96+ ' t': tuple,97+ ' u': uuid.UUID,98+ ' b': b64decode,99+ ' m': Markup,100+ ' d': parse_date,101+ }102+103 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)116 117 118 session_json_serializer = TaggedJSONSerializer()119 120 121 class SecureCookieSession(CallbackDict, SessionMixin):117- """Baseclass for sessions based on signed cookies."""122+ """Base class for sessions based on signed cookies."""123 124 def __init__(self, initial=None):125 def on_update(self):126 self.modified = True16 unmodified lines143 but fail on setting.144 """145 146 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 = _fail14 unmodified lines166 167 class Session(dict, SessionMixin):168 pass169 165- 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 lines188 #: this type.189 null_session_class = NullSession190 191 #: 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 = False19 unmodified lines216 """217 return isinstance(obj, self.null_session_class)218 219 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]228 224- # 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']230 230- # 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 None235 238- return rv236+ rv = app.config['SERVER_NAME']237 238+ # server name not set, cache False to return none next time239+ if not rv:240+ app.config['SESSION_COOKIE_DOMAIN'] = False241+ return None242+243+ # 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('.')246+247+ 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 None258+259+ ip = is_ip(rv)260+261+ 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+ )268+269+ # 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 = '.' + rv273+274+ app.config['SESSION_COOKIE_DOMAIN'] = rv275+ return rv276+277 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 lines297 return app.config['SESSION_COOKIE_SECURE']298 299 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_lifetime307 308 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.316 317 This check is usually skipped if sessions get deleted.318 282- .. 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.permanent325 326 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 lines418 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)385-386-387-from flask.debughelpers import UnexpectedUnicodeErrormodified:flask/signals.py+5 added-4 removed
2 unmodified lines3 flask.signals4 ~~~~~~~~~~~~~5 6 Implements signals based on blinker if available, otherwise7- falls silently back to a noop7+ falls silently back to a noop.8 9- :copyright: (c) 2014 by Armin Ronacher.9+ :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11 """12 signals_available = False13 try:22 unmodified lines36 connect = disconnect = has_receivers_for = receivers_for = \37 temporarily_connected_to = connected_to = _fail38 del _fail39 40-# The namespace for code signals. If you are not flask code, do40+# The namespace for code signals. If you are not Flask code, do41 # not put signals in here. Create your own namespace instead.42 _signals = Namespace()43 44 45-# 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.rst47 template_rendered = _signals.signal('template-rendered')48+before_render_template = _signals.signal('before-render-template')49 request_started = _signals.signal('request-started')50 request_finished = _signals.signal('request-finished')51 request_tearing_down = _signals.signal('request-tearing-down')52 got_request_exception = _signals.signal('got-request-exception')4 unmodified linesmodified:flask/templating.py+38 added-32 removed
3 unmodified lines4 ~~~~~~~~~~~~~~~~5 6 Implements the bridge to Jinja2.7 8- :copyright: (c) 2014 by Armin Ronacher.8+ :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11-import posixpath11 from jinja2 import BaseLoader, Environment as BaseEnvironment, \12 TemplateNotFound13 14 from .globals import _request_ctx_stack, _app_ctx_stack16-from .signals import template_rendered17-from .module import blueprint_is_module18-from ._compat import itervalues, iteritems15+from .signals import template_rendered, before_render_template16 17 18 def _default_template_ctx_processor():19 """Default template context processor. Injects `request`,31 unmodified lines51 def __init__(self, app):52 self.app = app53 54 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)58+59+ def _get_source_explained(self, environment, template):60+ attempts = []61+ trv = None62+58- 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))71 72+ from .debughelpers import explain_template_loading_attempts73+ explain_template_loading_attempts(self.app, template, attempts)74+75+ if trv is not None:76+ return trv77 raise TemplateNotFound(template)78 79+ def _get_source_fast(self, environment, template):80+ for srcobj, loader in self._iter_loaders(template):81+ try:82+ return loader.get_source(environment, template)83+ except TemplateNotFound:84+ continue85+ raise TemplateNotFound(template)86+87 def _iter_loaders(self, template):88 loader = self.app.jinja_loader89 if loader is not None:69- yield loader, template90+ yield self.app, loader91 71- # 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- pass82-83- 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, loader96 97 def list_templates(self):98 result = set()99 loader = self.app.jinja_loader100 if loader is not None:101 result.update(loader.list_templates())102 96- 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)108 109 return list(result)110 111 112 def _render(template, context, app):113 """Renders the template and fires the signal"""114+115+ 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 lines135 136 137 def 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.140 135- :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 linesmodified:flask/testing.py+22 added-5 removed
4 unmodified lines5 6 Implements test support helpers. This module is lazily imported7 and usually not used in production environments.8 9- :copyright: (c) 2014 by Armin Ronacher.9+ :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11 """12 13+import werkzeug14 from contextlib import contextmanager15 from werkzeug.test import Client, EnvironBuilder16 from flask import _request_ctx_stack17 21 unmodified lines39 40 class FlaskClient(Client):41 """Works like a regular Werkzeug test client but has some knowledge about42 how Flask works to defer the cleanup of the request context stack to the42- end of a with body when used in a with statement. For general information43- about how to use this class refer to :class:`werkzeug.test.Client`.43+ end of a ``with`` body when used in a ``with`` statement. For general44+ information about how to use this class refer to45+ :class:`werkzeug.test.Client`.46 47+ .. versionchanged:: 0.1248+ `app.test_client()` includes preset default environment, which can be49+ set after instantiation of the `app.test_client()` object in50+ `client.environ_base`.51+52 Basic usage is outlined in the :ref:`testing` chapter.53 """54 55 preserve_context = False56 57+ def __init__(self, *args, **kwargs):58+ super(FlaskClient, self).__init__(*args, **kwargs)59+ self.environ_base = {60+ "REMOTE_ADDR": "127.0.0.1",61+ "HTTP_USER_AGENT": "werkzeug/" + werkzeug.__version__62+ }63+64 @contextmanager65 def session_transaction(self, *args, **kwargs):52- """When used in combination with a with statement this opens a66+ """When used in combination with a ``with`` statement this opens a67 session transaction. This can be used to modify the session that54- the test client uses. Once the with block is left the session is68+ the test client uses. Once the ``with`` block is left the session is69 stored back.70 71+ ::72+73 with client.session_transaction() as session:74 session['value'] = 4275 76 Internally this is implemented by going through a temporary test36 unmodified lines113 114 def open(self, *args, **kwargs):115 kwargs.setdefault('environ_overrides', {}) \116 ['flask._preserve_context'] = self.preserve_context117+ kwargs.setdefault('environ_base', self.environ_base)118 119 as_tuple = kwargs.pop('as_tuple', False)120 buffered = kwargs.pop('buffered', False)121 follow_redirects = kwargs.pop('follow_redirects', False)22 unmodified linesmodified:flask/views.py+24 added-20 removed
3 unmodified lines4 ~~~~~~~~~~~5 6 This module provides class-based views inspired by the ones in Django.7 8- :copyright: (c) 2014 by Armin Ronacher.8+ :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 from .globals import request12 from ._compat import with_metaclass34 unmodified lines47 based decorators since those would decorate the view class and not the48 generated view function!49 """50 51- #: A for which methods this pluggable view can handle.51+ #: A list of methods this view can handle.52 methods = None53 54 #: The canonical way to decorate class-based views is to decorate the55 #: return value of as_view(). However since this moves parts of the46 unmodified lines102 return view103 104 105 class MethodViewType(type):106+ """Metaclass for :class:`MethodView` that determines what methods the view107+ defines.108+ """109 107- def __new__(cls, name, bases, d):108- rv = type.__new__(cls, name, bases, d)110+ def __init__(cls, name, bases, d):111+ super(MethodViewType, cls).__init__(name, bases, d)112+113 if 'methods' not in d:110- methods = set(rv.methods or [])111- for key in d:112- if key in http_method_funcs:114+ methods = set()115+116+ for key in http_method_funcs:117+ if hasattr(cls, key):118 methods.add(key.upper())114- # If we have no method at all in there we don't want to115- # add a method list. (This is for instance the case for116- # the baseclass or another subclass of a base method view117- # that does not introduce new methods).119+120+ # If we have no method at all in there we don't want to add a121+ # method list. This is for instance the case for the base class122+ # or another subclass of a base method view that does not introduce123+ # new methods.124 if methods:119- rv.methods = sorted(methods)120- return rv125+ cls.methods = methods126 127 128 class MethodView(with_metaclass(MethodViewType, View)):124- """Like a regular class-based view but that dispatches requests to125- particular methods. For instance if you implement a method called126- :meth:`get` it means you will response to ``'GET'`` requests and127- the :meth:`dispatch_request` implementation will automatically128- forward your request to that. Also :attr:`options` is set for you129- automatically::129+ """A class-based view that dispatches request methods to the corresponding130+ class methods. For example, if you implement a ``get`` method, it will be131+ used to handle ``GET`` requests. ::132 133 class CounterAPI(MethodView):132-134 def get(self):135 return session.get('counter', 0)136 137 def post(self):1 unmodified line139 return 'OK'140 141 app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))142 """143+144 def dispatch_request(self, *args, **kwargs):145 meth = getattr(self, request.method.lower(), None)146+147 # If the request method is HEAD and we don't have a handler for it148 # retry with GET.149 if meth is None and request.method == 'HEAD':150 meth = getattr(self, 'get', None)151+152 assert meth is not None, 'Unimplemented method %r' % request.method153 return meth(*args, **kwargs)modified:flask/wrappers.py+26 added-20 removed
3 unmodified lines4 ~~~~~~~~~~~~~~5 6 Implements the WSGI wrappers (request and response).7 8- :copyright: (c) 2014 by Armin Ronacher.8+ :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12 from werkzeug.wrappers import Request as RequestBase, Response as ResponseBase13 from werkzeug.exceptions import BadRequest14 15-from .debughelpers import attach_enctype_error_multidict15 from . import json16 from .globals import _request_ctx_stack17 19-18 _missing = object()19 20 21 def _get_data(req, cache):23 unmodified lines45 #: .. versionadded:: 0.646 url_rule = None47 48 #: 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 = None51 52 #: If matching the URL failed, this is the exception that will be53 #: raised / was raised as part of the request handling. This is6 unmodified lines60 _is_old_module = False61 62 @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 line70 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 lines96 return self.url_rule.endpoint.rsplit('.', 1)[0]97 98 @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``.102 103 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()109 110 @property111 def is_json(self):112 """Indicates if this request is JSON or not. By default a request113 is considered to include JSON data if the mimetype is114- ``application/json`` or ``application/*+json``.114+ :mimetype:`application/json` or :mimetype:`application/*+json`.115 116 .. versionadded:: 0.11117 """118 mt = self.mimetype3 unmodified lines122 return True123 return False124 125 def get_json(self, force=False, silent=False, cache=True):126- """Parses the incoming JSON request data and returns it. If127- parsing fails the :meth:`on_json_loading_failed` method on the128- request object will be invoked. By default this function will129- only load the json data if the mimetype is ``application/json``130- but this can be overridden by the `force` parameter.126+ """Parses the incoming JSON request data and returns it. By default127+ this function will return ``None`` if the mimetype is not128+ :mimetype:`application/json` but this can be overridden by the129+ ``force`` parameter. If parsing fails the130+ :meth:`on_json_loading_failed` method on the request object will be131+ invoked.132 132- :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 rv143 144 if not (force or self.is_json):145 return None29 unmodified lines175 add it by subclassing.176 177 .. 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()183 184 def _load_form_data(self):185 RequestBase._load_form_data(self)2 unmodified lines188 # 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)194 195 196 class Response(ResponseBase):9 unmodified linesdeleted: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
1-from flask import Flask, Module, render_template, url_for2-3-4-mod = Module(__name__)5-mod2 = Module(__name__, 'testmod2')6-mod3 = Module(__name__, name='somemod', subdomain='meh')7-8-9-@app.after_request10-def after_request(response):11- g.db.close()12- return response13-14-15-@app.route('/')16-def index_foo():17- x1 = url_for('somemod.index')18- x2 = url_for('.index')19- return render_template('test/index.html')20-21-22-@mod.route('/')23-def index():24- x1 = url_for('somemod.index')25- x2 = url_for('.index')26- return render_template('test/index.html')27-28-29-@mod2.route('/')30-def mod2_index():31- return render_template('testmod2/index.html')32-33-34-@mod3.route('/')35-def mod3_index():36- return render_template('something-else/index.html')37-38-39-app = Flask(__name__)40-app.register_module(mod)41-app.register_module(mod2)42-43-44-def handle_404(error):45- return 'Testing', 40446-app.error_handlers[404] = handle_404modified:scripts/flask-07-upgrade.py+4 added-3 removed
3 unmodified lines4 flask-07-upgrade5 ~~~~~~~~~~~~~~~~6 7 This command line script scans a whole application tree and attempts to8- output an unified diff with all the changes that are necessary to easily8+ output a unified diff with all the changes that are necessary to easily9 upgrade the application to 0.7 and to not yield deprecation warnings.10 11 This will also attempt to find `after_request` functions that don't modify12 the response and appear to be better suited for `teardown_request`.2 unmodified lines15 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.18 19- :copyright: (c) Copyright 2014 by Armin Ronacher.19+ :copyright: (c) Copyright 2015 by Armin Ronacher.20 :license: see LICENSE for more details.21 """22+from __future__ import print_function23 import re24 import os25 import inspect26 import difflib32 unmodified lines59 for line in difflib.unified_diff(old.splitlines(), new.splitlines(),60 posixpath.normpath(posixpath.join('a', filename)),61 posixpath.normpath(posixpath.join('b', filename)),62 lineterm=''):62- print line63+ print(line)64 65 66 def looks_like_teardown_function(node):67 returns = [x for x in ast.walk(node) if isinstance(x, ast.Return)]231 unmodified linesmodified:scripts/flaskext_compat.py+4 added-4 removed
10 unmodified lines11 import flaskext_compat12 flaskext_compat.activate()13 from flask.ext import foo14 15- :copyright: (c) 2014 by Armin Ronacher.15+ :copyright: (c) 2015 by Armin Ronacher.16 :license: BSD, see LICENSE for more details.17 """18+import types19 import sys20 import os20-import imp21 22 23 class ExtensionImporter(object):24 """This importer redirects imports from this submodule to other locations.18 unmodified lines43 44 def install(self):45 sys.meta_path[:] = [x for x in sys.meta_path if self != x] + [self]46 47- def find_module(self, fullname):47+ def find_module(self, fullname, path=None):48 if fullname.startswith(self.prefix):49 return self50 51 def load_module(self, fullname):65 unmodified lines117 118 119 def 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- ~~~~~~~~~~~~~~~~~~~~~5-6- Tests the Flask extensions.7-8- :copyright: (c) 2014 by Ali Afshar.9- :license: BSD, see LICENSE for more details.10-"""11-12-import os13-import sys14-import shutil15-import urllib216-import tempfile17-import subprocess18-import argparse19-20-from flask import json21-22-from setuptools.package_index import PackageIndex23-from setuptools.archive_util import unpack_archive24-25-flask_svc_url = 'http://flask.pocoo.org/extensions/'26-27-28-# 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.31-if sys.platform == 'darwin':32- _tempdir = '/private/tmp'33-else:34- _tempdir = tempfile.gettempdir()35-tdir = _tempdir + '/flaskext-test'36-flaskdir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))37-38-39-# virtualenv hack *cough*40-os.environ['PYTHONDONTWRITEBYTECODE'] = ''41-42-43-RESULT_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-'''112-113-114-def log(msg, *args):115- print '[EXTTEST]', msg % args116-117-118-class TestResult(object):119-120- 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 == 0126-127- 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')139-140- 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] = ''148-149-150-def create_tdir():151- try:152- shutil.rmtree(tdir)153- except Exception:154- pass155- os.mkdir(tdir)156-157-158-def 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])164-165-166-def get_test_command(checkout_dir):167- if os.path.isfile(checkout_dir + '/Makefile'):168- return 'make test'169- return 'python setup.py test'170-171-172-def 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 ext178-179-180-def 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)185-186- 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 path194-195-196-tox_template = """[tox]197-envlist=%(env)s198-199-[testenv]200-deps=201- %(deps)s202- distribute203- py204-commands=bash flaskext-runtest.sh {envlogdir}/test.log205-downloadcache=%(cache)s206-"""207-208-209-def 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_path219-220-221-def iter_extensions(only_approved=True):222- for ext in fetch_extensions_list():223- if ext['approved'] or not only_approved:224- yield ext['name']225-226-227-def test_extension(name, interpreters, flask_dep):228- checkout_path = checkout_extension(name)229- log('Running tests with tox in %s', checkout_path)230-231- # 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()242-243- # if there is a tox.ini, remove it, it will cause troubles244- # for us. Remove it if present, we are running tox ourselves245- # afterall.246-247- 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)250-251-252-def 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 results268-269-270-def 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 filename279-280-281-def 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()292-293- 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)299-300- 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', filename306-307-308-if __name__ == '__main__':309- main()added:scripts/flaskext_tester.py+309 added
1+# -*- coding: utf-8 -*-2+"""3+ Flask Extension Tests4+ ~~~~~~~~~~~~~~~~~~~~~5+6+ Tests the Flask extensions.7+8+ :copyright: (c) 2015 by Ali Afshar.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import os13+import sys14+import shutil15+import urllib216+import tempfile17+import subprocess18+import argparse19+20+from flask import json21+22+from setuptools.package_index import PackageIndex23+from setuptools.archive_util import unpack_archive24+25+flask_svc_url = 'http://flask.pocoo.org/extensions/'26+27+28+# 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.31+if sys.platform == 'darwin':32+ _tempdir = '/private/tmp'33+else:34+ _tempdir = tempfile.gettempdir()35+tdir = _tempdir + '/flaskext-test'36+flaskdir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))37+38+39+# virtualenv hack *cough*40+os.environ['PYTHONDONTWRITEBYTECODE'] = ''41+42+43+RESULT_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+'''112+113+114+def log(msg, *args):115+ print('[EXTTEST] ' + (msg % args))116+117+118+class TestResult(object):119+120+ 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 == 0126+127+ 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')139+140+ 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] = ''148+149+150+def create_tdir():151+ try:152+ shutil.rmtree(tdir)153+ except Exception:154+ pass155+ os.mkdir(tdir)156+157+158+def 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])164+165+166+def get_test_command(checkout_dir):167+ if os.path.isfile(checkout_dir + '/Makefile'):168+ return 'make test'169+ return 'python setup.py test'170+171+172+def 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 ext178+179+180+def 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)185+186+ 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 path194+195+196+tox_template = """[tox]197+envlist=%(env)s198+199+[testenv]200+deps=201+ %(deps)s202+ distribute203+ py204+commands=bash flaskext-runtest.sh {envlogdir}/test.log205+downloadcache=%(cache)s206+"""207+208+209+def 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_path219+220+221+def iter_extensions(only_approved=True):222+ for ext in fetch_extensions_list():223+ if ext['approved'] or not only_approved:224+ yield ext['name']225+226+227+def test_extension(name, interpreters, flask_dep):228+ checkout_path = checkout_extension(name)229+ log('Running tests with tox in %s', checkout_path)230+231+ # 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()242+243+ # if there is a tox.ini, remove it, it will cause troubles244+ # for us. Remove it if present, we are running tox ourselves245+ # afterall.246+247+ 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)250+251+252+def 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 results268+269+270+def 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 filename279+280+281+def 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()292+293+ 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)299+300+ 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))306+307+308+if __name__ == '__main__':309+ main()modified:scripts/make-release.py+5 added-11 removed
5 unmodified lines6 7 Helper script that performs a release. Does pretty much everything8 automatically for us.9 10- :copyright: (c) 2014 by Armin Ronacher.10+ :copyright: (c) 2015 by Armin Ronacher.11 :license: BSD, see LICENSE for more details.12 """13+from __future__ import print_function14 import sys15 import os16 import re17 from datetime import datetime, date62 unmodified lines80 info('Setting __init__.py version to %s', version)81 set_filename_version('flask/__init__.py', version, '__version__')82 83 83-def set_setup_version(version):84- info('Setting setup.py version to %s', version)85- set_filename_version('setup.py', version, 'version')86-87-84 def build_and_upload():89- Popen([sys.executable, 'setup.py', 'release', 'sdist', 'upload']).wait()85+ Popen([sys.executable, 'setup.py', 'release', 'sdist', 'bdist_wheel', 'upload']).wait()86 87 88 def fail(message, *args):93- print >> sys.stderr, 'Error:', message % args89+ print('Error:', message % args, file=sys.stderr)90 sys.exit(1)91 92 93 def info(message, *args):98- print >> sys.stderr, message % args94+ print(message % args, file=sys.stderr)95 96 97 def get_git_tags():98 return set(Popen(['git', 'tag'], stdout=PIPE).communicate()[0].splitlines())36 unmodified lines135 if not git_is_clean():136 fail('You have uncommitted changes in git')137 138 set_init_version(version)143- set_setup_version(version)139 make_git_commit('Bump version number to %s', version)140 make_git_tag(version)141 build_and_upload()142 set_init_version(dev_version)148- set_setup_version(dev_version)143 144 145 if __name__ == '__main__':146 main()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
1+I'm nestedadded: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}} Mailadded: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
1+Admin Fileadded:tests/test_apps/blueprintapp/apps/admin/templates/admin/index.html+1 added
1+Hello from the Adminadded:tests/test_apps/blueprintapp/apps/admin/__init__.py+15 added
1+from flask import Blueprint, render_template2+3+admin = Blueprint('admin', __name__, url_prefix='/admin',4+ template_folder='templates',5+ static_folder='static')6+7+8+@admin.route('/')9+def index():10+ return render_template('admin/index.html')11+12+13+@admin.route('/index2')14+def index2():15+ return render_template('./admin/index.html')added:tests/test_apps/blueprintapp/apps/frontend/templates/frontend/index.html+1 added
1+Hello from the Frontendadded:tests/test_apps/blueprintapp/apps/frontend/__init__.py+13 added
1+from flask import Blueprint, render_template2+3+frontend = Blueprint('frontend', __name__, template_folder='templates')4+5+6+@frontend.route('/')7+def index():8+ return render_template('frontend/index.html')9+10+11+@frontend.route('/missing')12+def 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
1+from flask import Flask2+3+app = Flask(__name__)4+app.config['DEBUG'] = True5+from blueprintapp.apps.admin import admin6+from blueprintapp.apps.frontend import frontend7+app.register_blueprint(admin)8+app.register_blueprint(frontend)added:tests/test_apps/cliapp/__init__.py
added:tests/test_apps/cliapp/app.py+5 added
1+from __future__ import absolute_import, print_function2+3+from flask import Flask4+5+testapp = Flask('testapp')added:tests/test_apps/cliapp/importerrorapp.py+7 added
1+from __future__ import absolute_import, print_function2+3+from flask import Flask4+5+raise ImportError()6+7+testapp = Flask('testapp')added:tests/test_apps/cliapp/multiapp.py+6 added
1+from __future__ import absolute_import, print_function2+3+from flask import Flask4+5+app1 = Flask('app1')6+app2 = Flask('app2')added:tests/test_apps/subdomaintestmodule/static/hello.txt+1 added
1+Hello Subdomainadded:tests/test_apps/subdomaintestmodule/__init__.py+4 added
1+from flask import Module2+3+4+mod = Module(__name__, 'foo', subdomain='foo')added:tests/conftest.py+134 added
1+# -*- coding: utf-8 -*-2+"""3+ tests.conftest4+ ~~~~~~~~~~~~~~5+6+ :copyright: (c) 2015 by the Flask Team, see AUTHORS for more details.7+ :license: BSD, see LICENSE for more details.8+"""9+import flask10+import gc11+import os12+import sys13+import pkgutil14+import pytest15+import textwrap16+17+18+@pytest.fixture19+def test_apps(monkeypatch):20+ monkeypatch.syspath_prepend(21+ os.path.abspath(os.path.join(22+ os.path.dirname(__file__), 'test_apps'))23+ )24+25+@pytest.fixture(autouse=True)26+def leak_detector(request):27+ def ensure_clean_request_context():28+ # make sure we're not leaking a request context since we are29+ # testing flask internally in debug mode in a few cases30+ leaks = []31+ while flask._request_ctx_stack.top is not None:32+ leaks.append(flask._request_ctx_stack.pop())33+ assert leaks == []34+ request.addfinalizer(ensure_clean_request_context)35+36+37+@pytest.fixture(params=(True, False))38+def limit_loader(request, monkeypatch):39+ """Patch pkgutil.get_loader to give loader without get_filename or archive.40+41+ 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.44+45+ This fixture will run the testcase twice, once with and once without the46+ limitation/mock.47+ """48+ if not request.param:49+ return50+51+ class LimitedLoader(object):52+ def __init__(self, loader):53+ self.loader = loader54+55+ 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)60+61+ old_get_loader = pkgutil.get_loader62+63+ def get_loader(*args, **kwargs):64+ return LimitedLoader(old_get_loader(*args, **kwargs))65+ monkeypatch.setattr(pkgutil, 'get_loader', get_loader)66+67+68+@pytest.fixture69+def 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 rv74+75+76+@pytest.fixture77+def modules_tmpdir_prefix(modules_tmpdir, monkeypatch):78+ monkeypatch.setattr(sys, 'prefix', str(modules_tmpdir))79+ return modules_tmpdir80+81+82+@pytest.fixture83+def 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 rv91+92+93+@pytest.fixture94+def 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()102+103+ 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)))111+112+ 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 inner121+122+123+@pytest.fixture124+def purge_module(request):125+ def inner(name):126+ request.addfinalizer(lambda: sys.modules.pop(name, None))127+ return inner128+129+130+@pytest.yield_fixture(autouse=True)131+def catch_deprecation_warnings(recwarn):132+ yield133+ gc.collect()134+ assert not recwarn.listadded:tests/test_appctx.py+170 added
1+# -*- coding: utf-8 -*-2+"""3+ tests.appctx4+ ~~~~~~~~~~~~5+6+ Tests the application context.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import pytest13+14+import flask15+16+17+def test_basic_url_generation():18+ app = flask.Flask(__name__)19+ app.config['SERVER_NAME'] = 'localhost'20+ app.config['PREFERRED_URL_SCHEME'] = 'https'21+22+ @app.route('/')23+ def index():24+ pass25+26+ with app.app_context():27+ rv = flask.url_for('index')28+ assert rv == 'https://localhost/'29+30+def 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')35+36+def test_url_generation_without_context_fails():37+ with pytest.raises(RuntimeError):38+ flask.url_for('index')39+40+def test_request_context_means_app_context():41+ app = flask.Flask(__name__)42+ with app.test_request_context():43+ assert flask.current_app._get_current_object() == app44+ assert flask._app_ctx_stack.top is None45+46+def test_app_context_provides_current_app():47+ app = flask.Flask(__name__)48+ with app.app_context():49+ assert flask.current_app._get_current_object() == app50+ assert flask._app_ctx_stack.top is None51+52+def test_app_tearing_down():53+ cleanup_stuff = []54+ app = flask.Flask(__name__)55+ @app.teardown_appcontext56+ def cleanup(exception):57+ cleanup_stuff.append(exception)58+59+ with app.app_context():60+ pass61+62+ assert cleanup_stuff == [None]63+64+def 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)70+71+ try:72+ raise Exception('dummy')73+ except Exception:74+ pass75+76+ with app.app_context():77+ pass78+79+ assert cleanup_stuff == [None]80+81+def 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)87+88+ with app.app_context():89+ try:90+ raise Exception('dummy')91+ except Exception:92+ pass93+94+ assert cleanup_stuff == [None]95+96+def test_app_ctx_globals_methods():97+ app = flask.Flask(__name__)98+ with app.app_context():99+ # get100+ assert flask.g.get('foo') is None101+ assert flask.g.get('foo', 'bar') == 'bar'102+ # __contains__103+ assert 'foo' not in flask.g104+ flask.g.foo = 'bar'105+ assert 'foo' in flask.g106+ # setdefault107+ flask.g.setdefault('bar', 'the cake is a lie')108+ flask.g.setdefault('bar', 'hello world')109+ assert flask.g.bar == 'the cake is a lie'110+ # pop111+ assert flask.g.pop('bar') == 'the cake is a lie'112+ with pytest.raises(KeyError):113+ flask.g.pop('bar')114+ assert flask.g.pop('bar', 'more cake') == 'more cake'115+ # __iter__116+ assert list(flask.g) == ['foo']117+118+def 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'126+127+def 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']149+150+151+def test_clean_pop():152+ called = []153+ app = flask.Flask(__name__)154+155+ @app.teardown_request156+ def teardown_req(error=None):157+ 1 / 0158+159+ @app.teardown_appcontext160+ def teardown_app(error=None):161+ called.append('TEARDOWN')162+163+ try:164+ with app.test_request_context():165+ called.append(flask.current_app.name)166+ except ZeroDivisionError:167+ pass168+169+ assert called == ['test_appctx', 'TEARDOWN']170+ assert not flask.current_appadded:tests/test_basic.py+1924 added
1+# -*- coding: utf-8 -*-2+"""3+ tests.basic4+ ~~~~~~~~~~~~~~~~~~~~~5+6+ The basic functionality.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import pytest13+14+import re15+import uuid16+import time17+import flask18+import pickle19+from datetime import datetime20+from threading import Thread21+from flask._compat import text_type22+from werkzeug.exceptions import BadRequest, NotFound, Forbidden23+from werkzeug.http import parse_date24+from werkzeug.routing import BuildError25+import werkzeug.serving26+27+28+def test_options_work():29+ app = flask.Flask(__name__)30+31+ @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''37+38+39+def test_options_on_multiple_rules():40+ app = flask.Flask(__name__)41+42+ @app.route('/', methods=['GET', 'POST'])43+ def index():44+ return 'Hello World'45+46+ @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']51+52+53+def test_provide_automatic_options_attr():54+ app = flask.Flask(__name__)55+56+ 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 == 40562+63+ app = flask.Flask(__name__)64+65+ 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']71+72+73+def test_provide_automatic_options_kwarg():74+ app = flask.Flask(__name__)75+76+ def index():77+ return flask.request.method78+79+ def more():80+ return flask.request.method81+82+ app.add_url_rule('/', view_func=index, provide_automatic_options=False)83+ app.add_url_rule(84+ '/more', view_func=more, methods=['GET', 'POST'],85+ provide_automatic_options=False86+ )87+88+ c = app.test_client()89+ assert c.get('/').data == b'GET'90+91+ rv = c.post('/')92+ assert rv.status_code == 40593+ assert sorted(rv.allow) == ['GET', 'HEAD']94+95+ # Older versions of Werkzeug.test.Client don't have an options method96+ if hasattr(c, 'options'):97+ rv = c.options('/')98+ else:99+ rv = c.open('/', method='OPTIONS')100+101+ assert rv.status_code == 405102+103+ rv = c.head('/')104+ assert rv.status_code == 200105+ assert not rv.data # head truncates106+ assert c.post('/more').data == b'POST'107+ assert c.get('/more').data == b'GET'108+109+ rv = c.delete('/more')110+ assert rv.status_code == 405111+ assert sorted(rv.allow) == ['GET', 'HEAD', 'POST']112+113+ if hasattr(c, 'options'):114+ rv = c.options('/more')115+ else:116+ rv = c.open('/more', method='OPTIONS')117+118+ assert rv.status_code == 405119+120+121+def test_request_dispatching():122+ app = flask.Flask(__name__)123+124+ @app.route('/')125+ def index():126+ return flask.request.method127+128+ @app.route('/more', methods=['GET', 'POST'])129+ def more():130+ return flask.request.method131+132+ 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']145+146+147+def 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"153+154+155+def test_url_mapping():156+ app = flask.Flask(__name__)157+158+ random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383"159+160+ def index():161+ return flask.request.method162+163+ def more():164+ return flask.request.method165+166+ def options():167+ return random_uuid4168+169+170+ app.add_url_rule('/', 'index', index)171+ app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])172+173+ # Issue 1288: Test that automatic options are not added when non-uppercase 'options' in methods174+ app.add_url_rule('/options', 'options', options, methods=['options'])175+176+ 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")192+193+194+def 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+ ]))201+202+ def bar():203+ return 'bar'204+205+ def index():206+ return 'index'207+ app.view_functions['bar'] = bar208+ app.view_functions['index'] = index209+210+ c = app.test_client()211+ assert c.get('/foo/').data == b'index'212+ assert c.get('/foo/bar').data == b'bar'213+214+215+def 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+ ]))222+223+ @app.endpoint('bar')224+ def bar():225+ return 'bar'226+227+ @app.endpoint('index')228+ def index():229+ return 'index'230+231+ c = app.test_client()232+ assert c.get('/foo/').data == b'index'233+ assert c.get('/foo/bar').data == b'bar'234+235+236+def test_session():237+ app = flask.Flask(__name__)238+ app.secret_key = 'testkey'239+240+ @app.route('/set', methods=['POST'])241+ def set():242+ flask.session['value'] = flask.request.form['value']243+ return 'value set'244+245+ @app.route('/get')246+ def get():247+ return flask.session['value']248+249+ c = app.test_client()250+ assert c.post('/set', data={'value': '42'}).data == b'value set'251+ assert c.get('/get').data == b'42'252+253+254+def test_session_using_server_name():255+ app = flask.Flask(__name__)256+ app.config.update(257+ SECRET_KEY='foo',258+ SERVER_NAME='example.com'259+ )260+261+ @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()268+269+270+def 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+ )276+277+ @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()284+285+286+def 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+ )293+294+ @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()302+303+304+def test_session_using_application_root():305+ class PrefixPathMiddleware(object):306+307+ def __init__(self, app, prefix):308+ self.app = app309+ self.prefix = prefix310+311+ def __call__(self, environ, start_response):312+ environ['SCRIPT_NAME'] = self.prefix313+ return self.app(environ, start_response)314+315+ 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+ )321+322+ @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()328+329+330+def 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+ )341+342+ @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 cookie352+353+354+def test_session_localhost_warning(recwarn):355+ app = flask.Flask(__name__)356+ app.config.update(357+ SECRET_KEY='testing',358+ SERVER_NAME='localhost:5000',359+ )360+361+ @app.route('/')362+ def index():363+ flask.session['testing'] = 42364+ return 'testing'365+366+ rv = app.test_client().get('/', 'http://localhost:5000/')367+ assert 'domain' not in rv.headers['set-cookie'].lower()368+ w = recwarn.pop(UserWarning)369+ assert '"localhost" is not a valid cookie domain' in str(w.message)370+371+372+def test_session_ip_warning(recwarn):373+ app = flask.Flask(__name__)374+ app.config.update(375+ SECRET_KEY='testing',376+ SERVER_NAME='127.0.0.1:5000',377+ )378+379+ @app.route('/')380+ def index():381+ flask.session['testing'] = 42382+ return 'testing'383+384+ rv = app.test_client().get('/', 'http://127.0.0.1:5000/')385+ assert 'domain=127.0.0.1' in rv.headers['set-cookie'].lower()386+ w = recwarn.pop(UserWarning)387+ assert 'cookie domain is an IP' in str(w.message)388+389+390+def test_missing_session():391+ app = flask.Flask(__name__)392+393+ def expect_exception(f, *args, **kwargs):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')400+401+402+def test_session_expiration():403+ permanent = True404+ app = flask.Flask(__name__)405+ app.secret_key = 'testkey'406+407+ @app.route('/')408+ def index():409+ flask.session['test'] = 42410+ flask.session.permanent = permanent411+ return ''412+413+ @app.route('/test')414+ def test():415+ return text_type(flask.session.permanent)416+417+ 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.day426+427+ rv = client.get('/test')428+ assert rv.data == b'True'429+430+ 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 None435+436+437+def test_session_stored_last():438+ app = flask.Flask(__name__)439+ app.secret_key = 'development-key'440+ app.testing = True441+442+ @app.after_request443+ def modify_session(response):444+ flask.session['foo'] = 42445+ return response446+447+ @app.route('/')448+ def dump_session_contents():449+ return repr(flask.session.get('foo'))450+451+ c = app.test_client()452+ assert c.get('/').data == b'None'453+ assert c.get('/').data == b'42'454+455+456+def 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()462+463+ @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 response471+472+ @app.route('/')473+ def dump_session_contents():474+ return pickle.dumps(dict(flask.session))475+476+ 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)486+487+488+def test_session_cookie_setting():489+ app = flask.Flask(__name__)490+ app.testing = True491+ app.secret_key = 'dev key'492+ is_permanent = True493+494+ @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)499+500+ @app.route('/read')501+ def read():502+ return str(flask.session.get('foo', 0))503+504+ 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'509+510+ 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'514+515+ is_permanent = True516+ app.config['SESSION_REFRESH_EACH_REQUEST'] = True517+ run_test(expect_header=True)518+519+ is_permanent = True520+ app.config['SESSION_REFRESH_EACH_REQUEST'] = False521+ run_test(expect_header=False)522+523+ is_permanent = False524+ app.config['SESSION_REFRESH_EACH_REQUEST'] = True525+ run_test(expect_header=False)526+527+ is_permanent = False528+ app.config['SESSION_REFRESH_EACH_REQUEST'] = False529+ run_test(expect_header=False)530+531+532+def test_session_vary_cookie():533+ app = flask.Flask(__name__)534+ app.secret_key = 'testkey'535+536+ @app.route('/set-session')537+ def set_session():538+ flask.session['test'] = 'test'539+ return ''540+541+ @app.route('/get-session')542+ def get_session():543+ s = flask.session.get('test')544+ return ''545+546+ @app.route('/get-session-with-dictionary')547+ def get_session_with_dictionary():548+ s = flask.session['test']549+ return ''550+551+ @app.route('/no-vary-header')552+ def no_vary_header():553+ return ''554+555+ c = app.test_client()556+557+ rv = c.get('/set-session')558+ assert rv.headers['Vary'] == 'Cookie'559+560+ rv = c.get('/get-session')561+ assert rv.headers['Vary'] == 'Cookie'562+563+ rv = c.get('/get-session-with-dictionary')564+ assert rv.headers['Vary'] == 'Cookie'565+566+ rv = c.get('/no-vary-header')567+ assert 'Vary' not in rv.headers568+569+570+def test_flashes():571+ app = flask.Flask(__name__)572+ app.secret_key = 'testkey'573+574+ 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']581+582+583+def 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.589+590+ app = flask.Flask(__name__)591+ app.secret_key = 'testkey'592+ app.testing = True593+594+ @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 ''600+601+ @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 ''610+611+ @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 ''621+622+ @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 ''628+629+ @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 ''638+639+ @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 ''647+648+ # Create new test client on each test to clean flashed messages.649+650+ c = app.test_client()651+ c.get('/')652+ c.get('/test/')653+654+ c = app.test_client()655+ c.get('/')656+ c.get('/test_with_categories/')657+658+ c = app.test_client()659+ c.get('/')660+ c.get('/test_filter/')661+662+ c = app.test_client()663+ c.get('/')664+ c.get('/test_filters/')665+666+ c = app.test_client()667+ c.get('/')668+ c.get('/test_filters_without_returning_categories/')669+670+671+def test_request_processing():672+ app = flask.Flask(__name__)673+ evts = []674+675+ @app.before_request676+ def before_request():677+ evts.append('before')678+679+ @app.after_request680+ def after_request(response):681+ response.data += b'|after'682+ evts.append('after')683+ return response684+685+ @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'694+695+696+def test_request_preprocessing_early_return():697+ app = flask.Flask(__name__)698+ evts = []699+700+ @app.before_request701+ def before_request1():702+ evts.append(1)703+704+ @app.before_request705+ def before_request2():706+ evts.append(2)707+ return "hello"708+709+ @app.before_request710+ def before_request3():711+ evts.append(3)712+ return "bye"713+714+ @app.route('/')715+ def index():716+ evts.append('index')717+ return "damnit"718+719+ rv = app.test_client().get('/').data.strip()720+ assert rv == b'hello'721+ assert evts == [1, 2]722+723+724+def test_after_request_processing():725+ app = flask.Flask(__name__)726+ app.testing = True727+728+ @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'739+740+741+def test_teardown_request_handler():742+ called = []743+ app = flask.Flask(__name__)744+745+ @app.teardown_request746+ def teardown_request(exc):747+ called.append(True)748+ return "Ignored"749+750+ @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) == 1757+758+759+def test_teardown_request_handler_debug_mode():760+ called = []761+ app = flask.Flask(__name__)762+ app.testing = True763+764+ @app.teardown_request765+ def teardown_request(exc):766+ called.append(True)767+ return "Ignored"768+769+ @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) == 1776+777+778+def test_teardown_request_handler_error():779+ called = []780+ app = flask.Flask(__name__)781+ app.config['LOGGER_HANDLER_POLICY'] = 'never'782+783+ @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+ pass794+795+ @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+ pass806+807+ @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) == 2814+815+816+def test_before_after_request_order():817+ called = []818+ app = flask.Flask(__name__)819+820+ @app.before_request821+ def before1():822+ called.append(1)823+824+ @app.before_request825+ def before2():826+ called.append(2)827+828+ @app.after_request829+ def after1(response):830+ called.append(4)831+ return response832+833+ @app.after_request834+ def after2(response):835+ called.append(3)836+ return response837+838+ @app.teardown_request839+ def finish1(exc):840+ called.append(6)841+842+ @app.teardown_request843+ def finish2(exc):844+ called.append(5)845+846+ @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]852+853+854+def test_error_handling():855+ app = flask.Flask(__name__)856+ app.config['LOGGER_HANDLER_POLICY'] = 'never'857+858+ @app.errorhandler(404)859+ def not_found(e):860+ return 'not found', 404861+862+ @app.errorhandler(500)863+ def internal_server_error(e):864+ return 'internal server error', 500865+866+ @app.errorhandler(Forbidden)867+ def forbidden(e):868+ return 'forbidden', 403869+870+ @app.route('/')871+ def index():872+ flask.abort(404)873+874+ @app.route('/error')875+ def error():876+ 1 // 0877+878+ @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.data891+892+893+def test_error_handling_processing():894+ app = flask.Flask(__name__)895+ app.config['LOGGER_HANDLER_POLICY'] = 'never'896+897+ @app.errorhandler(500)898+ def internal_server_error(e):899+ return 'internal server error', 500900+901+ @app.route('/')902+ def broken_func():903+ 1 // 0904+905+ @app.after_request906+ def after_request(resp):907+ resp.mimetype = 'text/x-special'908+ return resp909+910+ 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'914+915+916+def test_baseexception_error_handling():917+ app = flask.Flask(__name__)918+ app.config['LOGGER_HANDLER_POLICY'] = 'never'919+920+ @app.route('/')921+ def broken_func():922+ raise KeyboardInterrupt()923+924+ with app.test_client() as c:925+ with pytest.raises(KeyboardInterrupt):926+ c.get('/')927+928+ ctx = flask._request_ctx_stack.top929+ assert ctx.preserved930+ assert type(ctx._preserved_exc) is KeyboardInterrupt931+932+933+def test_before_request_and_routing_errors():934+ app = flask.Flask(__name__)935+936+ @app.before_request937+ def attach_something():938+ flask.g.something = 'value'939+940+ @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'946+947+948+def test_user_error_handling():949+ class MyException(Exception):950+ pass951+952+ app = flask.Flask(__name__)953+954+ @app.errorhandler(MyException)955+ def handle_my_exception(e):956+ assert isinstance(e, MyException)957+ return '42'958+959+ @app.route('/')960+ def index():961+ raise MyException()962+963+ c = app.test_client()964+ assert c.get('/').data == b'42'965+966+967+def test_http_error_subclass_handling():968+ class ForbiddenSubclass(Forbidden):969+ pass970+971+ app = flask.Flask(__name__)972+973+ @app.errorhandler(ForbiddenSubclass)974+ def handle_forbidden_subclass(e):975+ assert isinstance(e, ForbiddenSubclass)976+ return 'banana'977+978+ @app.errorhandler(403)979+ def handle_forbidden_subclass(e):980+ assert not isinstance(e, ForbiddenSubclass)981+ assert isinstance(e, Forbidden)982+ return 'apple'983+984+ @app.route('/1')985+ def index1():986+ raise ForbiddenSubclass()987+988+ @app.route('/2')989+ def index2():990+ flask.abort(403)991+992+ @app.route('/3')993+ def index3():994+ raise Forbidden()995+996+ 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'1000+1001+1002+def test_trapping_of_bad_request_key_errors():1003+ app = flask.Flask(__name__)1004+ app.testing = True1005+1006+ @app.route('/fail')1007+ def fail():1008+ flask.request.form['missing_key']1009+ c = app.test_client()1010+ assert c.get('/fail').status_code == 4001011+1012+ 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)1017+1018+1019+def test_trapping_of_all_http_exceptions():1020+ app = flask.Flask(__name__)1021+ app.testing = True1022+ app.config['TRAP_HTTP_EXCEPTIONS'] = True1023+1024+ @app.route('/fail')1025+ def fail():1026+ flask.abort(404)1027+1028+ c = app.test_client()1029+ with pytest.raises(NotFound):1030+ c.get('/fail')1031+1032+1033+def test_enctype_debug_helper():1034+ from flask.debughelpers import DebugFilesKeyError1035+ app = flask.Flask(__name__)1036+ app.debug = True1037+1038+ @app.route('/fail', methods=['POST'])1039+ def index():1040+ return flask.request.files['foo'].filename1041+1042+ # 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)1050+1051+1052+def test_response_types():1053+ app = flask.Flask(__name__)1054+ app.testing = True1055+1056+ @app.route('/text')1057+ def from_text():1058+ return u'Hällo Wörld'1059+1060+ @app.route('/bytes')1061+ def from_bytes():1062+ return u'Hällo Wörld'.encode('utf-8')1063+1064+ @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+ }1070+1071+ @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+ }1077+1078+ @app.route('/text_status')1079+ def from_text_status():1080+ return 'Hi, status!', 4001081+1082+ @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+ }1088+1089+ @app.route('/response_status')1090+ def from_response_status():1091+ return app.response_class('Hello world', 400), 5001092+1093+ @app.route('/wsgi')1094+ def from_wsgi():1095+ return NotFound()1096+1097+ c = app.test_client()1098+1099+ 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')1101+1102+ 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'1107+1108+ 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'1113+1114+ rv = c.get('/text_status')1115+ assert rv.data == b'Hi, status!'1116+ assert rv.status_code == 4001117+ assert rv.mimetype == 'text/html'1118+1119+ 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 == 4041124+1125+ rv = c.get('/response_status')1126+ assert rv.data == b'Hello world'1127+ assert rv.status_code == 5001128+1129+ rv = c.get('/wsgi')1130+ assert b'Not Found' in rv.data1131+ assert rv.status_code == 4041132+1133+1134+def test_response_type_errors():1135+ app = flask.Flask(__name__)1136+ app.testing = True1137+1138+ @app.route('/none')1139+ def from_none():1140+ pass1141+1142+ @app.route('/small_tuple')1143+ def from_small_tuple():1144+ return 'Hello',1145+1146+ @app.route('/large_tuple')1147+ def from_large_tuple():1148+ return 'Hello', 234, {'X-Foo': 'Bar'}, '???'1149+1150+ @app.route('/bad_type')1151+ def from_bad_type():1152+ return True1153+1154+ @app.route('/bad_wsgi')1155+ def from_bad_wsgi():1156+ return lambda: None1157+1158+ c = app.test_client()1159+1160+ with pytest.raises(TypeError) as e:1161+ c.get('/none')1162+ assert 'returned None' in str(e)1163+1164+ with pytest.raises(TypeError) as e:1165+ c.get('/small_tuple')1166+ assert 'tuple must have the form' in str(e)1167+1168+ pytest.raises(TypeError, c.get, '/large_tuple')1169+1170+ with pytest.raises(TypeError) as e:1171+ c.get('/bad_type')1172+ assert 'it was a bool' in str(e)1173+1174+ pytest.raises(TypeError, c.get, '/bad_wsgi')1175+1176+1177+def 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'1184+1185+ rv = flask.make_response('Awesome')1186+ assert rv.status_code == 2001187+ assert rv.data == b'Awesome'1188+ assert rv.mimetype == 'text/html'1189+1190+ rv = flask.make_response('W00t', 404)1191+ assert rv.status_code == 4041192+ assert rv.data == b'W00t'1193+ assert rv.mimetype == 'text/html'1194+1195+1196+def 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'1204+1205+ rv = flask.make_response(1206+ flask.Response(''), 400)1207+ assert rv.status_code == 4001208+ assert rv.data == b''1209+ assert rv.mimetype == 'text/html'1210+1211+ 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'1217+1218+1219+def 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+ }1230+1231+ rv = flask.make_response(1232+ flask.jsonify(uncompressed_msg), 200)1233+ assert rv.data == compressed_msg1234+1235+1236+def 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'1243+1244+ rv = flask.make_response(1245+ flask.jsonify(compressed_msg), 200)1246+ assert rv.data == pretty_response1247+1248+1249+def 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'1259+1260+1261+def 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)1267+1268+1269+def test_url_generation():1270+ app = flask.Flask(__name__)1271+1272+ @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'1279+1280+1281+def test_build_error_handler():1282+ app = flask.Flask(__name__)1283+1284+ # Test base case, a URL which results in a BuildError.1285+ with app.test_request_context():1286+ pytest.raises(BuildError, flask.url_for, 'spam')1287+1288+ # 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', {})1299+1300+ # 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/'1307+1308+1309+def test_build_error_handler_reraise():1310+ app = flask.Flask(__name__)1311+1312+ # 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)1316+1317+ with app.test_request_context():1318+ pytest.raises(BuildError, flask.url_for, 'not.existing')1319+1320+1321+def test_url_for_passes_special_values_to_build_error_handler():1322+ app = flask.Flask(__name__)1323+1324+ @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'1333+1334+ with app.test_request_context():1335+ flask.url_for('/')1336+1337+1338+def test_custom_converters():1339+ from werkzeug.routing import BaseConverter1340+1341+ class ListConverter(BaseConverter):1342+1343+ def to_python(self, value):1344+ return value.split(',')1345+1346+ 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'] = ListConverter1351+1352+ @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'1357+1358+1359+def 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()1369+1370+1371+def test_static_path_deprecated(recwarn):1372+ app = flask.Flask(__name__, static_path='/foo')1373+ recwarn.pop(DeprecationWarning)1374+1375+ app.testing = True1376+ rv = app.test_client().get('/foo/index.html')1377+ assert rv.status_code == 2001378+ rv.close()1379+1380+ with app.test_request_context():1381+ assert flask.url_for('static', filename='index.html') == '/foo/index.html'1382+1383+1384+def 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()1390+1391+ with app.test_request_context():1392+ assert flask.url_for('static', filename='index.html') == '/foo/index.html'1393+1394+1395+def 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)1412+1413+1414+def test_request_locals():1415+ assert repr(flask.g) == '<LocalProxy unbound>'1416+ assert not flask.g1417+1418+1419+def test_test_app_proper_environ():1420+ app = flask.Flask(__name__)1421+ app.config.update(1422+ SERVER_NAME='localhost.localdomain:5000'1423+ )1424+1425+ @app.route('/')1426+ def index():1427+ return 'Foo'1428+1429+ @app.route('/', subdomain='foo')1430+ def subdomain():1431+ return 'Foo SubDomain'1432+1433+ rv = app.test_client().get('/')1434+ assert rv.data == b'Foo'1435+1436+ rv = app.test_client().get('/', 'http://localhost.localdomain:5000')1437+ assert rv.data == b'Foo'1438+1439+ rv = app.test_client().get('/', 'https://localhost.localdomain:5000')1440+ assert rv.data == b'Foo'1441+1442+ app.config.update(SERVER_NAME='localhost.localdomain')1443+ rv = app.test_client().get('/', 'https://localhost.localdomain')1444+ assert rv.data == b'Foo'1445+1446+ 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+ )1458+1459+ 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+ )1471+1472+ rv = app.test_client().get('/', 'http://foo.localhost.localdomain')1473+ assert rv.data == b'Foo SubDomain'1474+1475+1476+def test_exception_propagation():1477+ def apprunner(config_key):1478+ app = flask.Flask(__name__)1479+ app.config['LOGGER_HANDLER_POLICY'] = 'never'1480+1481+ @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 == 5001491+1492+ # 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()1500+1501+1502+@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])1506+def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1507+ use_reloader, propagate_exceptions):1508+ rv = {}1509+1510+ # Mocks werkzeug.serving.run_simple method1511+ def run_simple_mock(*args, **kwargs):1512+ rv['passthrough_errors'] = kwargs.get('passthrough_errors')1513+1514+ 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)1518+1519+1520+def test_max_content_length():1521+ app = flask.Flask(__name__)1522+ app.config['MAX_CONTENT_LENGTH'] = 641523+1524+ @app.before_request1525+ def always_first():1526+ flask.request.form['myfile']1527+ assert False1528+1529+ @app.route('/accept', methods=['POST'])1530+ def accept_file():1531+ flask.request.form['myfile']1532+ assert False1533+1534+ @app.errorhandler(413)1535+ def catcher(error):1536+ return '42'1537+1538+ c = app.test_client()1539+ rv = c.post('/accept', data={'myfile': 'foo' * 100})1540+ assert rv.data == b'42'1541+1542+1543+def test_url_processors():1544+ app = flask.Flask(__name__)1545+1546+ @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)1551+1552+ @app.url_value_preprocessor1553+ def pull_lang_code(endpoint, values):1554+ flask.g.lang_code = values.pop('lang_code', None)1555+1556+ @app.route('/<lang_code>/')1557+ def index():1558+ return flask.url_for('about')1559+1560+ @app.route('/<lang_code>/about')1561+ def about():1562+ return flask.url_for('something_else')1563+1564+ @app.route('/foo')1565+ def something_else():1566+ return flask.url_for('about', lang_code='en')1567+1568+ c = app.test_client()1569+1570+ 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'1573+1574+1575+def test_inject_blueprint_url_defaults():1576+ app = flask.Flask(__name__)1577+ bp = flask.Blueprint('foo.bar.baz', __name__,1578+ template_folder='template')1579+1580+ @bp.url_defaults1581+ def bp_defaults(endpoint, values):1582+ values['page'] = 'login'1583+1584+ @bp.route('/<page>')1585+ def view(page):1586+ pass1587+1588+ app.register_blueprint(bp)1589+1590+ values = dict()1591+ app.inject_url_defaults('foo.bar.baz.view', values)1592+ expected = dict(page='login')1593+ assert values == expected1594+1595+ with app.test_request_context('/somepage'):1596+ url = flask.url_for('foo.bar.baz.view')1597+ expected = '/login'1598+ assert url == expected1599+1600+1601+def test_nonascii_pathinfo():1602+ app = flask.Flask(__name__)1603+ app.testing = True1604+1605+ @app.route(u'/киртест')1606+ def index():1607+ return 'Hello World!'1608+1609+ c = app.test_client()1610+ rv = c.get(u'/киртест')1611+ assert rv.data == b'Hello World!'1612+1613+1614+def test_debug_mode_complains_after_first_request():1615+ app = flask.Flask(__name__)1616+ app.debug = True1617+1618+ @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)1628+1629+ app.debug = False1630+1631+ @app.route('/foo')1632+ def working():1633+ return 'Meh'1634+ assert app.test_client().get('/foo').data == b'Meh'1635+ assert app.got_first_request1636+1637+1638+def test_before_first_request_functions():1639+ got = []1640+ app = flask.Flask(__name__)1641+1642+ @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_request1651+1652+1653+def test_before_first_request_functions_concurrent():1654+ got = []1655+ app = flask.Flask(__name__)1656+1657+ @app.before_first_request1658+ def foo():1659+ time.sleep(0.2)1660+ got.append(42)1661+1662+ c = app.test_client()1663+1664+ def get_and_assert():1665+ c.get("/")1666+ assert got == [42]1667+1668+ t = Thread(target=get_and_assert)1669+ t.start()1670+ get_and_assert()1671+ t.join()1672+ assert app.got_first_request1673+1674+1675+def test_routing_redirect_debugging():1676+ app = flask.Flask(__name__)1677+ app.debug = True1678+1679+ @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)1688+1689+ rv = c.get('/foo', data={}, follow_redirects=True)1690+ assert rv.data == b'success'1691+1692+ app.debug = False1693+ with app.test_client() as c:1694+ rv = c.post('/foo', data={}, follow_redirects=True)1695+ assert rv.data == b'success'1696+1697+1698+def test_route_decorator_custom_endpoint():1699+ app = flask.Flask(__name__)1700+ app.debug = True1701+1702+ @app.route('/foo/')1703+ def foo():1704+ return flask.request.endpoint1705+1706+ @app.route('/bar/', endpoint='bar')1707+ def for_bar():1708+ return flask.request.endpoint1709+1710+ @app.route('/bar/123', endpoint='123')1711+ def for_bar_foo():1712+ return flask.request.endpoint1713+1714+ 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'1718+1719+ 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'1723+1724+1725+def test_preserve_only_once():1726+ app = flask.Flask(__name__)1727+ app.debug = True1728+1729+ @app.route('/fail')1730+ def fail_func():1731+ 1 // 01732+1733+ c = app.test_client()1734+ for x in range(3):1735+ with pytest.raises(ZeroDivisionError):1736+ c.get('/fail')1737+1738+ 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 None1744+1745+1746+def test_preserve_remembers_exception():1747+ app = flask.Flask(__name__)1748+ app.debug = True1749+ errors = []1750+1751+ @app.route('/fail')1752+ def fail_func():1753+ 1 // 01754+1755+ @app.route('/success')1756+ def success_func():1757+ return 'Okay'1758+1759+ @app.teardown_request1760+ def teardown_handler(exc):1761+ errors.append(exc)1762+1763+ c = app.test_client()1764+1765+ # After this failure we did not yet call the teardown handler1766+ with pytest.raises(ZeroDivisionError):1767+ c.get('/fail')1768+ assert errors == []1769+1770+ # But this request triggers it, and it's an error1771+ c.get('/success')1772+ assert len(errors) == 21773+ assert isinstance(errors[0], ZeroDivisionError)1774+1775+ # At this point another request does nothing.1776+ c.get('/success')1777+ assert len(errors) == 31778+ assert errors[1] is None1779+1780+1781+def test_get_method_on_g():1782+ app = flask.Flask(__name__)1783+ app.testing = True1784+1785+ 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 == 421791+1792+1793+def test_g_iteration_protocol():1794+ app = flask.Flask(__name__)1795+ app.testing = True1796+1797+ 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']1803+1804+1805+def test_subdomain_basic_support():1806+ app = flask.Flask(__name__)1807+ app.config['SERVER_NAME'] = 'localhost'1808+1809+ @app.route('/')1810+ def normal_index():1811+ return 'normal index'1812+1813+ @app.route('/', subdomain='test')1814+ def test_index():1815+ return 'test index'1816+1817+ c = app.test_client()1818+ rv = c.get('/', 'http://localhost/')1819+ assert rv.data == b'normal index'1820+1821+ rv = c.get('/', 'http://test.localhost/')1822+ assert rv.data == b'test index'1823+1824+1825+def test_subdomain_matching():1826+ app = flask.Flask(__name__)1827+ app.config['SERVER_NAME'] = 'localhost'1828+1829+ @app.route('/', subdomain='<user>')1830+ def index(user):1831+ return 'index for %s' % user1832+1833+ c = app.test_client()1834+ rv = c.get('/', 'http://mitsuhiko.localhost/')1835+ assert rv.data == b'index for mitsuhiko'1836+1837+1838+def test_subdomain_matching_with_ports():1839+ app = flask.Flask(__name__)1840+ app.config['SERVER_NAME'] = 'localhost:3000'1841+1842+ @app.route('/', subdomain='<user>')1843+ def index(user):1844+ return 'index for %s' % user1845+1846+ c = app.test_client()1847+ rv = c.get('/', 'http://mitsuhiko.localhost:3000/')1848+ assert rv.data == b'index for mitsuhiko'1849+1850+1851+def test_multi_route_rules():1852+ app = flask.Flask(__name__)1853+1854+ @app.route('/')1855+ @app.route('/<test>/')1856+ def index(test='a'):1857+ return test1858+1859+ rv = app.test_client().open('/')1860+ assert rv.data == b'a'1861+ rv = app.test_client().open('/b/')1862+ assert rv.data == b'b'1863+1864+1865+def test_multi_route_class_views():1866+ class View(object):1867+1868+ def __init__(self, app):1869+ app.add_url_rule('/', 'index', self.index)1870+ app.add_url_rule('/<test>/', 'index', self.index)1871+1872+ def index(self, test='a'):1873+ return test1874+1875+ 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'1881+1882+1883+def test_run_defaults(monkeypatch):1884+ rv = {}1885+1886+ # Mocks werkzeug.serving.run_simple method1887+ def run_simple_mock(*args, **kwargs):1888+ rv['result'] = 'running...'1889+1890+ app = flask.Flask(__name__)1891+ monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1892+ app.run()1893+ assert rv['result'] == 'running...'1894+1895+1896+def test_run_server_port(monkeypatch):1897+ rv = {}1898+1899+ # Mocks werkzeug.serving.run_simple method1900+ def run_simple_mock(hostname, port, application, *args, **kwargs):1901+ rv['result'] = 'running on %s:%s ...' % (hostname, port)1902+1903+ 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)1908+1909+1910+@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+))1916+def 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_port1920+1921+ 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+ ~~~~~~~~~~~~~~~~5+6+ Blueprints (and currently modules)7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import pytest13+14+import flask15+16+from flask._compat import text_type17+from werkzeug.http import parse_cache_control_header18+from jinja2 import TemplateNotFound19+20+21+def test_blueprint_specific_error_handling():22+ frontend = flask.Blueprint('frontend', __name__)23+ backend = flask.Blueprint('backend', __name__)24+ sideend = flask.Blueprint('sideend', __name__)25+26+ @frontend.errorhandler(403)27+ def frontend_forbidden(e):28+ return 'frontend says no', 40329+30+ @frontend.route('/frontend-no')31+ def frontend_no():32+ flask.abort(403)33+34+ @backend.errorhandler(403)35+ def backend_forbidden(e):36+ return 'backend says no', 40337+38+ @backend.route('/backend-no')39+ def backend_no():40+ flask.abort(403)41+42+ @sideend.route('/what-is-a-sideend')43+ def sideend_no():44+ flask.abort(403)45+46+ app = flask.Flask(__name__)47+ app.register_blueprint(frontend)48+ app.register_blueprint(backend)49+ app.register_blueprint(sideend)50+51+ @app.errorhandler(403)52+ def app_forbidden(e):53+ return 'application itself says no', 40354+55+ c = app.test_client()56+57+ assert c.get('/frontend-no').data == b'frontend says no'58+ assert c.get('/backend-no').data == b'backend says no'59+ assert c.get('/what-is-a-sideend').data == b'application itself says no'60+61+def test_blueprint_specific_user_error_handling():62+ class MyDecoratorException(Exception):63+ pass64+ class MyFunctionException(Exception):65+ pass66+67+ blue = flask.Blueprint('blue', __name__)68+69+ @blue.errorhandler(MyDecoratorException)70+ def my_decorator_exception_handler(e):71+ assert isinstance(e, MyDecoratorException)72+ return 'boom'73+74+ def my_function_exception_handler(e):75+ assert isinstance(e, MyFunctionException)76+ return 'bam'77+ blue.register_error_handler(MyFunctionException, my_function_exception_handler)78+79+ @blue.route('/decorator')80+ def blue_deco_test():81+ raise MyDecoratorException()82+ @blue.route('/function')83+ def blue_func_test():84+ raise MyFunctionException()85+86+ app = flask.Flask(__name__)87+ app.register_blueprint(blue)88+89+ c = app.test_client()90+91+ assert c.get('/decorator').data == b'boom'92+ assert c.get('/function').data == b'bam'93+94+def test_blueprint_url_definitions():95+ bp = flask.Blueprint('test', __name__)96+97+ @bp.route('/foo', defaults={'baz': 42})98+ def foo(bar, baz):99+ return '%s/%d' % (bar, baz)100+101+ @bp.route('/bar')102+ def bar(bar):103+ return text_type(bar)104+105+ 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})108+109+ c = app.test_client()110+ assert c.get('/1/foo').data == b'23/42'111+ assert c.get('/2/foo').data == b'19/42'112+ assert c.get('/1/bar').data == b'23'113+ assert c.get('/2/bar').data == b'19'114+115+def test_blueprint_url_processors():116+ bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')117+118+ @bp.url_defaults119+ def add_language_code(endpoint, values):120+ values.setdefault('lang_code', flask.g.lang_code)121+122+ @bp.url_value_preprocessor123+ def pull_lang_code(endpoint, values):124+ flask.g.lang_code = values.pop('lang_code')125+126+ @bp.route('/')127+ def index():128+ return flask.url_for('.about')129+130+ @bp.route('/about')131+ def about():132+ return flask.url_for('.index')133+134+ app = flask.Flask(__name__)135+ app.register_blueprint(bp)136+137+ c = app.test_client()138+139+ assert c.get('/de/').data == b'/de/about'140+ assert c.get('/de/about').data == b'/de/'141+142+def test_templates_and_static(test_apps):143+ from blueprintapp import app144+ c = app.test_client()145+146+ 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()158+159+ # 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_default172+173+ with app.test_request_context():174+ assert flask.url_for('admin.static', filename='test.txt') == '/admin/static/test.txt'175+176+ with app.test_request_context():177+ with pytest.raises(TemplateNotFound) as e:178+ flask.render_template('missing.html')179+ assert e.value.name == 'missing.html'180+181+ with flask.Flask(__name__).test_request_context():182+ assert flask.render_template('nested/nested.txt') == 'I\'m nested'183+184+def 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 100189+190+ blueprint = MyBlueprint('blueprint', __name__, static_folder='static')191+ app.register_blueprint(blueprint)192+193+ # 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_default207+208+def 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']212+213+def test_dotted_names():214+ frontend = flask.Blueprint('myapp.frontend', __name__)215+ backend = flask.Blueprint('myapp.backend', __name__)216+217+ @frontend.route('/fe')218+ def frontend_index():219+ return flask.url_for('myapp.backend.backend_index')220+221+ @frontend.route('/fe2')222+ def frontend_page2():223+ return flask.url_for('.frontend_index')224+225+ @backend.route('/be')226+ def backend_index():227+ return flask.url_for('myapp.frontend.frontend_index')228+229+ app = flask.Flask(__name__)230+ app.register_blueprint(frontend)231+ app.register_blueprint(backend)232+233+ c = app.test_client()234+ assert c.get('/fe').data.strip() == b'/be'235+ assert c.get('/fe2').data.strip() == b'/fe'236+ assert c.get('/be').data.strip() == b'/fe'237+238+def test_dotted_names_from_app():239+ app = flask.Flask(__name__)240+ app.testing = True241+ test = flask.Blueprint('test', __name__)242+243+ @app.route('/')244+ def app_index():245+ return flask.url_for('test.index')246+247+ @test.route('/test/')248+ def index():249+ return flask.url_for('app_index')250+251+ app.register_blueprint(test)252+253+ with app.test_client() as c:254+ rv = c.get('/')255+ assert rv.data == b'/test/'256+257+def test_empty_url_defaults():258+ bp = flask.Blueprint('bp', __name__)259+260+ @bp.route('/', defaults={'page': 1})261+ @bp.route('/page/<int:page>')262+ def something(page):263+ return str(page)264+265+ app = flask.Flask(__name__)266+ app.register_blueprint(bp)267+268+ c = app.test_client()269+ assert c.get('/').data == b'1'270+ assert c.get('/page/2').data == b'2'271+272+def test_route_decorator_custom_endpoint():273+274+ bp = flask.Blueprint('bp', __name__)275+276+ @bp.route('/foo')277+ def foo():278+ return flask.request.endpoint279+280+ @bp.route('/bar', endpoint='bar')281+ def foo_bar():282+ return flask.request.endpoint283+284+ @bp.route('/bar/123', endpoint='123')285+ def foo_bar_foo():286+ return flask.request.endpoint287+288+ @bp.route('/bar/foo')289+ def bar_foo():290+ return flask.request.endpoint291+292+ app = flask.Flask(__name__)293+ app.register_blueprint(bp, url_prefix='/py')294+295+ @app.route('/')296+ def index():297+ return flask.request.endpoint298+299+ c = app.test_client()300+ assert c.get('/').data == b'index'301+ assert c.get('/py/foo').data == b'bp.foo'302+ assert c.get('/py/bar').data == b'bp.bar'303+ assert c.get('/py/bar/123').data == b'bp.123'304+ assert c.get('/py/bar/foo').data == b'bp.bar_foo'305+306+def test_route_decorator_custom_endpoint_with_dots():307+ bp = flask.Blueprint('bp', __name__)308+309+ @bp.route('/foo')310+ def foo():311+ return flask.request.endpoint312+313+ 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')321+322+ 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')330+331+ def foo_foo_foo():332+ pass333+334+ pytest.raises(335+ AssertionError,336+ lambda: bp.add_url_rule(337+ '/bar/123', endpoint='bar.123', view_func=foo_foo_foo338+ )339+ )340+341+ pytest.raises(342+ AssertionError,343+ bp.route('/bar/123', endpoint='bar.123'),344+ lambda: None345+ )346+347+ app = flask.Flask(__name__)348+ app.register_blueprint(bp, url_prefix='/py')349+350+ 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 == 404357+358+359+def test_endpoint_decorator():360+ from werkzeug.routing import Rule361+ app = flask.Flask(__name__)362+ app.url_map.add(Rule('/foo', endpoint='bar'))363+364+ bp = flask.Blueprint('bp', __name__)365+366+ @bp.endpoint('bar')367+ def foobar():368+ return flask.request.endpoint369+370+ app.register_blueprint(bp, url_prefix='/bp_prefix')371+372+ c = app.test_client()373+ assert c.get('/foo').data == b'bar'374+ assert c.get('/bp_prefix/bar').status_code == 404375+376+377+def test_template_filter():378+ bp = flask.Blueprint('bp', __name__)379+ @bp.app_template_filter()380+ def my_reverse(s):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'387+388+def 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'398+399+def 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'409+410+def 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'420+421+def 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'433+434+def 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'446+447+def 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'459+460+def 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'472+473+def 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'485+486+def 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)496+497+def 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)507+508+def 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)518+519+def 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)529+530+def 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.data542+543+def 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.data555+556+def 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.data568+569+def 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.data581+582+def 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.dataadded:tests/test_cli.py+270 added
1+# -*- coding: utf-8 -*-2+"""3+ tests.test_cli4+ ~~~~~~~~~~~~~~5+6+ :copyright: (c) 2016 by the Flask Team, see AUTHORS for more details.7+ :license: BSD, see LICENSE for more details.8+"""9+#10+# This file was part of Flask-CLI and was modified under the terms its license,11+# the Revised BSD License.12+# Copyright (C) 2015 CERN.13+#14+from __future__ import absolute_import, print_function15+import os16+import sys17+from functools import partial18+19+import click20+import pytest21+from click.testing import CliRunner22+from flask import Flask, current_app23+24+from flask.cli import cli, AppGroup, FlaskGroup, NoAppException, ScriptInfo, \25+ find_best_app, locate_app, with_appcontext, prepare_exec_for_file, \26+ find_default_import_path, get_version27+28+29+@pytest.fixture30+def runner():31+ return CliRunner()32+33+34+def test_cli_name(test_apps):35+ """Make sure the CLI object's name is the app's name and not the app itself"""36+ from cliapp.app import testapp37+ assert testapp.cli.name == testapp.name38+39+40+def 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.app45+46+ class Module:47+ application = Flask('appname')48+ assert find_best_app(Module) == Module.application49+50+ class Module:51+ myapp = Flask('appname')52+ assert find_best_app(Module) == Module.myapp53+54+ class Module:55+ pass56+ pytest.raises(NoAppException, find_best_app, Module)57+58+ class Module:59+ myapp1 = Flask('appname1')60+ myapp2 = Flask('appname2')61+ pytest.raises(NoAppException, find_best_app, Module)62+63+64+def test_prepare_exec_for_file(test_apps):65+ """Expect the correct path to be set and the correct module name to be returned.66+67+ :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.path74+75+ 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.path79+80+ with pytest.raises(NoAppException):81+ prepare_exec_for_file('/tmp/share/test.txt')82+83+84+def 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")93+94+95+def 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_rv106+107+108+def 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 out121+122+123+def 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"128+129+ def create_app(info):130+ return Flask("createapp")131+132+ obj = ScriptInfo(create_app=create_app)133+ app = obj.load_app()134+ assert app.name == "createapp"135+ assert obj.load_app() == app136+137+138+def test_with_appcontext(runner):139+ """Test of with_appcontext."""140+ @click.command()141+ @with_appcontext142+ def testcmd():143+ click.echo(current_app.name)144+145+ obj = ScriptInfo(create_app=lambda info: Flask("testapp"))146+147+ result = runner.invoke(testcmd, obj=obj)148+ assert result.exit_code == 0149+ assert result.output == 'testapp\n'150+151+152+def test_appgroup(runner):153+ """Test of with_appcontext."""154+ @click.group(cls=AppGroup)155+ def cli():156+ pass157+158+ @cli.command(with_appcontext=True)159+ def test():160+ click.echo(current_app.name)161+162+ @cli.group()163+ def subgroup():164+ pass165+166+ @subgroup.command(with_appcontext=True)167+ def test2():168+ click.echo(current_app.name)169+170+ obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))171+172+ result = runner.invoke(cli, ['test'], obj=obj)173+ assert result.exit_code == 0174+ assert result.output == 'testappgroup\n'175+176+ result = runner.invoke(cli, ['subgroup', 'test2'], obj=obj)177+ assert result.exit_code == 0178+ assert result.output == 'testappgroup\n'179+180+181+def test_flaskgroup(runner):182+ """Test FlaskGroup."""183+ def create_app(info):184+ return Flask("flaskgroup")185+186+ @click.group(cls=FlaskGroup, create_app=create_app)187+ def cli(**params):188+ pass189+190+ @cli.command()191+ def test():192+ click.echo(current_app.name)193+194+ result = runner.invoke(cli, ['test'])195+ assert result.exit_code == 0196+ assert result.output == 'flaskgroup\n'197+198+199+def test_print_exceptions(runner):200+ """Print the stacktrace if the CLI."""201+ def create_app(info):202+ raise Exception("oh no")203+ return Flask("flaskgroup")204+205+ @click.group(cls=FlaskGroup, create_app=create_app)206+ def cli(**params):207+ pass208+209+ result = runner.invoke(cli, ['--help'])210+ assert result.exit_code == 0211+ assert 'Exception: oh no' in result.output212+ assert 'Traceback' in result.output213+214+215+class TestRoutes:216+ @pytest.fixture217+ def invoke(self, runner):218+ def create_app(info):219+ app = Flask(__name__)220+ app.testing = True221+222+ @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])223+ def yyy_get_post(x, y):224+ pass225+226+ @app.route('/zzz_post', methods=['POST'])227+ def aaa_post():228+ pass229+230+ return app231+232+ cli = FlaskGroup(create_app=create_app)233+ return partial(runner.invoke, cli)234+235+ def expect_order(self, order, output):236+ # skip the header and match the start of each row237+ for expect, line in zip(order, output.splitlines()[2:]):238+ # do this instead of startswith for nicer pytest output239+ assert line[:len(expect)] == expect240+241+ def test_simple(self, invoke):242+ result = invoke(['routes'])243+ assert result.exit_code == 0244+ self.expect_order(245+ ['aaa_post', 'static', 'yyy_get_post'],246+ result.output247+ )248+249+ def test_sort(self, invoke):250+ default_output = invoke(['routes']).output251+ endpoint_output = invoke(['routes', '-s', 'endpoint']).output252+ assert default_output == endpoint_output253+ self.expect_order(254+ ['static', 'yyy_get_post', 'aaa_post'],255+ invoke(['routes', '-s', 'methods']).output256+ )257+ self.expect_order(258+ ['yyy_get_post', 'static', 'aaa_post'],259+ invoke(['routes', '-s', 'rule']).output260+ )261+ self.expect_order(262+ ['aaa_post', 'yyy_get_post', 'static'],263+ invoke(['routes', '-s', 'match']).output264+ )265+266+ def test_all_methods(self, invoke):267+ output = invoke(['routes']).output268+ assert 'GET, HEAD, OPTIONS, POST' not in output269+ output = invoke(['routes', '--all-methods']).output270+ assert 'GET, HEAD, OPTIONS, POST' in outputadded:tests/test_config.py+207 added
1+# -*- coding: utf-8 -*-2+"""3+ tests.test_config4+ ~~~~~~~~~~~~~~~~~5+6+ :copyright: (c) 2015 by the Flask Team, see AUTHORS for more details.7+ :license: BSD, see LICENSE for more details.8+"""9+10+11+from datetime import timedelta12+import os13+import textwrap14+15+import flask16+from flask._compat import PY217+import pytest18+19+20+# config keys used for the TestConfig21+TEST_KEY = 'foo'22+SECRET_KEY = 'devkey'23+24+25+def common_object_test(app):26+ assert app.secret_key == 'devkey'27+ assert app.config['TEST_KEY'] == 'foo'28+ assert 'TestConfig' not in app.config29+30+31+def test_config_from_file():32+ app = flask.Flask(__name__)33+ app.config.from_pyfile(__file__.rsplit('.', 1)[0] + '.py')34+ common_object_test(app)35+36+37+def test_config_from_object():38+ app = flask.Flask(__name__)39+ app.config.from_object(__name__)40+ common_object_test(app)41+42+43+def 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)48+49+50+def 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)57+58+ app = flask.Flask(__name__)59+ app.config.from_mapping([60+ ('SECRET_KEY', 'devkey'),61+ ('TEST_KEY', 'foo')62+ ])63+ common_object_test(app)64+65+ app = flask.Flask(__name__)66+ app.config.from_mapping(67+ SECRET_KEY='devkey',68+ TEST_KEY='foo'69+ )70+ common_object_test(app)71+72+ app = flask.Flask(__name__)73+ with pytest.raises(TypeError):74+ app.config.from_mapping(75+ {}, {}76+ )77+78+79+def test_config_from_class():80+ class Base(object):81+ TEST_KEY = 'foo'82+83+ class Test(Base):84+ SECRET_KEY = 'devkey'85+ app = flask.Flask(__name__)86+ app.config.from_object(Test)87+ common_object_test(app)88+89+90+def 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)99+100+ 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 = env105+106+107+def 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 = env121+122+123+def 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)132+133+134+def 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)143+144+145+def test_custom_config_class():146+ class Config(flask.Config):147+ pass148+149+ 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)155+156+157+def test_session_lifetime():158+ app = flask.Flask(__name__)159+ app.config['PERMANENT_SESSION_LIFETIME'] = 42160+ assert app.permanent_session_lifetime.seconds == 42161+162+163+def 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 == 7200169+170+171+def 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']193+194+195+@pytest.mark.parametrize('encoding', ['utf-8', 'iso-8859-15', 'latin-1'])196+def test_from_pyfile_weird_encoding(tmpdir, encoding):197+ f = tmpdir.join('my_config.py')198+ f.write_binary(textwrap.dedent(u'''199+ # -*- coding: {0} -*-200+ TEST_VALUE = "föö"201+ '''.format(encoding)).encode(encoding))202+ app = flask.Flask(__name__)203+ app.config.from_pyfile(str(f))204+ value = app.config['TEST_VALUE']205+ if PY2:206+ value = value.decode(encoding)207+ assert value == u'föö'added:tests/test_deprecations.py+46 added
1+# -*- coding: utf-8 -*-2+"""3+ tests.deprecations4+ ~~~~~~~~~~~~~~~~~~5+6+ Tests deprecation support. Not used currently.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import pytest13+14+import flask15+16+17+class TestRequestDeprecation(object):18+19+ def test_request_json(self, recwarn):20+ """Request.json is deprecated"""21+ app = flask.Flask(__name__)22+ app.testing = True23+24+ @app.route('/', methods=['POST'])25+ def index():26+ assert flask.request.json == {'spam': 42}27+ print(flask.request.json)28+ return 'OK'29+30+ c = app.test_client()31+ c.post('/', data='{"spam": 42}', content_type='application/json')32+ recwarn.pop(DeprecationWarning)33+34+ def test_request_module(self, recwarn):35+ """Request.module is deprecated"""36+ app = flask.Flask(__name__)37+ app.testing = True38+39+ @app.route('/')40+ def index():41+ assert flask.request.module is None42+ return 'OK'43+44+ 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+ ~~~~~~~~~~~~~~~~~~~5+6+ Tests the extension import thing.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import sys13+import pytest14+15+try:16+ from imp import reload as reload_module17+except ImportError:18+ reload_module = reload19+20+from flask._compat import PY221+22+23+@pytest.fixture(autouse=True)24+def disable_extwarnings(request, recwarn):25+ from flask.exthook import ExtDeprecationWarning26+27+ def inner():28+ assert set(w.category for w in recwarn.list) \29+ <= set([ExtDeprecationWarning])30+ recwarn.clear()31+32+ request.addfinalizer(inner)33+34+35+@pytest.fixture(autouse=True)36+def importhook_setup(monkeypatch, request):37+ # we clear this out for various reasons. The most important one is38+ # that a real flaskext could be in there which would disable our39+ # fake package. Secondly we want to make sure that the 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)51+52+ # 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 == 160+61+ def teardown():62+ from flask import ext63+ for key in ext.__dict__:64+ assert '.' not in key65+66+ request.addfinalizer(teardown)67+68+69+@pytest.fixture70+def newext_simple(modules_tmpdir):71+ x = modules_tmpdir.join('flask_newext_simple.py')72+ x.write('ext_id = "newext_simple"')73+74+75+@pytest.fixture76+def 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"')80+81+82+@pytest.fixture83+def 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')87+88+89+@pytest.fixture90+def 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')97+98+99+@pytest.fixture100+def 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')105+106+107+def test_flaskext_new_simple_import_normal(newext_simple):108+ from flask.ext.newext_simple import ext_id109+ assert ext_id == 'newext_simple'110+111+112+def 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'116+117+118+def test_flaskext_new_package_import_normal(newext_package):119+ from flask.ext.newext_package import ext_id120+ assert ext_id == 'newext_package'121+122+123+def 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'127+128+129+def test_flaskext_new_package_import_submodule_function(newext_package):130+ from flask.ext.newext_package.submodule import test_function131+ assert test_function() == 42132+133+134+def 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() == 42138+139+140+def test_flaskext_old_simple_import_normal(oldext_simple):141+ from flask.ext.oldext_simple import ext_id142+ assert ext_id == 'oldext_simple'143+144+145+def 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'149+150+151+def test_flaskext_old_package_import_normal(oldext_package):152+ from flask.ext.oldext_package import ext_id153+ assert ext_id == 'oldext_package'154+155+156+def 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'160+161+162+def 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() == 42166+167+168+def test_flaskext_old_package_import_submodule_function(oldext_package):169+ from flask.ext.oldext_package.submodule import test_function170+ assert test_function() == 42171+172+173+def test_flaskext_broken_package_no_module_caching(flaskext_broken):174+ for x in range(2):175+ with pytest.raises(ImportError):176+ import flask.ext.broken177+178+179+def 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()190+191+ # 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_next196+197+ import os.path198+ assert os.path.join('flask_broken', '__init__.py') in \199+ next.tb_frame.f_code.co_filenameadded:tests/test_helpers.py+943 added
1+# -*- coding: utf-8 -*-2+"""3+ tests.helpers4+ ~~~~~~~~~~~~~~~~~~~~~~~5+6+ Various helpers.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import pytest13+14+import os15+import uuid16+import datetime17+18+import flask19+from logging import StreamHandler20+from werkzeug.datastructures import Range21+from werkzeug.exceptions import BadRequest, NotFound22+from werkzeug.http import parse_cache_control_header, parse_options_header23+from werkzeug.http import http_date24+from flask._compat import StringIO, text_type25+26+27+def has_encoding(name):28+ try:29+ import codecs30+ codecs.lookup(name)31+ return True32+ except LookupError:33+ return False34+35+36+class TestJSON(object):37+38+ def test_ignore_cached_json(self):39+ app = flask.Flask(__name__)40+ with app.test_request_context('/', method='POST', data='malformed',41+ content_type='application/json'):42+ assert flask.request.get_json(silent=True, cache=True) is None43+ with pytest.raises(BadRequest):44+ flask.request.get_json(silent=False, cache=False)45+46+ def test_post_empty_json_adds_exception_to_response_content_in_debug(self):47+ app = flask.Flask(__name__)48+ app.config['DEBUG'] = True49+ @app.route('/json', methods=['POST'])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.data57+58+ 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.data69+70+ 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 == 40078+79+ 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'87+88+ 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()94+95+ 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')99+100+ def test_json_as_unicode(self):101+ app = flask.Flask(__name__)102+103+ app.config['JSON_AS_ASCII'] = True104+ with app.app_context():105+ rv = flask.json.dumps(u'\N{SNOWMAN}')106+ assert rv == '"\\u2603"'107+108+ app.config['JSON_AS_ASCII'] = False109+ with app.app_context():110+ rv = flask.json.dumps(u'\N{SNOWMAN}')111+ assert rv == u'"\u2603"'112+113+ def test_json_dump_to_file(self):114+ app = flask.Flask(__name__)115+ test_data = {'name': 'Flask'}116+ out = StringIO()117+118+ with app.app_context():119+ flask.json.dump(test_data, out)120+ out.seek(0)121+ rv = flask.json.load(out)122+ assert rv == test_data123+124+ @pytest.mark.parametrize('test_value', [0, -1, 1, 23, 3.14, 's', "longer string", True, False, None])125+ def test_jsonify_basic_types(self, test_value):126+ """Test jsonify with basic types."""127+ app = flask.Flask(__name__)128+ c = app.test_client()129+130+ url = '/jsonify_basic_types'131+ app.add_url_rule(url, url, lambda x=test_value: flask.jsonify(x))132+ rv = c.get(url)133+ assert rv.mimetype == 'application/json'134+ assert flask.json.loads(rv.data) == test_value135+136+ def test_jsonify_dicts(self):137+ """Test jsonify with dicts and kwargs unpacking."""138+ d = dict(139+ a=0, b=23, c=3.14, d='t', e='Hi', f=True, g=False,140+ h=['test list', 10, False],141+ i={'test':'dict'}142+ )143+ app = flask.Flask(__name__)144+ @app.route('/kw')145+ def return_kwargs():146+ return flask.jsonify(**d)147+ @app.route('/dict')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) == d155+156+ def test_jsonify_arrays(self):157+ """Test jsonify of lists and args unpacking."""158+ l = [159+ 0, 42, 3.14, 't', 'hello', True, False,160+ ['test list', 2, False],161+ {'test':'dict'}162+ ]163+ app = flask.Flask(__name__)164+ @app.route('/args_unpack')165+ def return_args_unpack():166+ return flask.jsonify(*l)167+ @app.route('/array')168+ def return_array():169+ return flask.jsonify(l)170+ c = app.test_client()171+ for url in '/args_unpack', '/array':172+ rv = c.get(url)173+ assert rv.mimetype == 'application/json'174+ assert flask.json.loads(rv.data) == l175+176+ def test_jsonify_date_types(self):177+ """Test jsonify with datetime.date and datetime.datetime types."""178+ test_dates = (179+ datetime.datetime(1973, 3, 11, 6, 30, 45),180+ datetime.date(1975, 1, 5)181+ )182+ app = flask.Flask(__name__)183+ c = app.test_client()184+185+ for i, d in enumerate(test_dates):186+ url = '/datetest{0}'.format(i)187+ app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val))188+ rv = c.get(url)189+ assert rv.mimetype == 'application/json'190+ assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple())191+192+ def test_jsonify_uuid_types(self):193+ """Test jsonify with uuid.UUID types"""194+195+ test_uuid = uuid.UUID(bytes=b'\xDE\xAD\xBE\xEF' * 4)196+ app = flask.Flask(__name__)197+ url = '/uuid_test'198+ app.add_url_rule(url, url, lambda: flask.jsonify(x=test_uuid))199+200+ c = app.test_client()201+ rv = c.get(url)202+203+ rv_x = flask.json.loads(rv.data)['x']204+ assert rv_x == str(test_uuid)205+ rv_uuid = uuid.UUID(rv_x)206+ assert rv_uuid == test_uuid207+208+ def test_json_attr(self):209+ app = flask.Flask(__name__)210+ @app.route('/add', methods=['POST'])211+ def add():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'218+219+ 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>'239+240+ 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>"'269+270+ def test_blueprint_json_customization(self):271+ class X(object):272+ def __init__(self, val):273+ self.val = val274+275+ class MyEncoder(flask.json.JSONEncoder):276+ def default(self, o):277+ if isinstance(o, X):278+ return '<%d>' % o.val279+280+ return flask.json.JSONEncoder.default(self, o)281+282+ class MyDecoder(flask.json.JSONDecoder):283+ def __init__(self, *args, **kwargs):284+ kwargs.setdefault('object_hook', self.object_hook)285+ flask.json.JSONDecoder.__init__(self, *args, **kwargs)286+287+ def object_hook(self, obj):288+ if len(obj) == 1 and '_foo' in obj:289+ return X(obj['_foo'])290+291+ return obj292+293+ bp = flask.Blueprint('bp', __name__)294+ bp.json_encoder = MyEncoder295+ bp.json_decoder = MyDecoder296+297+ @bp.route('/bp', methods=['POST'])298+ def index():299+ return flask.json.dumps(flask.request.get_json()['x'])300+301+ app = flask.Flask(__name__)302+ app.testing = True303+ app.register_blueprint(bp)304+305+ c = app.test_client()306+ rv = c.post('/bp', data=flask.json.dumps({307+ 'x': {'_foo': 42}308+ }), content_type='application/json')309+ assert rv.data == b'"<42>"'310+311+ def test_modified_url_encoding(self):312+ class ModifiedRequest(flask.Request):313+ url_charset = 'euc-kr'314+ app = flask.Flask(__name__)315+ app.testing = True316+ app.request_class = ModifiedRequest317+ app.url_map.charset = 'euc-kr'318+319+ @app.route('/')320+ def index():321+ return flask.request.args['foo']322+323+ rv = app.test_client().get(u'/?foo=정상처리'.encode('euc-kr'))324+ assert rv.status_code == 200325+ assert rv.data == u'정상처리'.encode('utf-8')326+327+ if not has_encoding('euc-kr'):328+ test_modified_url_encoding = None329+330+ def test_json_key_sorting(self):331+ app = flask.Flask(__name__)332+ app.testing = True333+ app.debug = True334+335+ assert app.config['JSON_SORT_KEYS'] == True336+ d = dict.fromkeys(range(20), 'foo')337+338+ @app.route('/')339+ def index():340+ return flask.jsonify(values=d)341+342+ 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+ ]397+398+ try:399+ assert lines == sorted_by_int400+ except AssertionError:401+ assert lines == sorted_by_str402+403+class TestSendfile(object):404+405+ 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()415+416+ def test_send_file_xsendfile(self, catch_deprecation_warnings):417+ app = flask.Flask(__name__)418+ app.use_x_sendfile = True419+ with app.test_request_context():420+ rv = flask.send_file('static/index.html')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()427+428+ def test_send_file_last_modified(self):429+ app = flask.Flask(__name__)430+ last_modified = datetime.datetime(1999, 1, 1)431+432+ @app.route('/')433+ def index():434+ return flask.send_file(StringIO("party like it's"),435+ last_modified=last_modified,436+ mimetype='text/plain')437+438+ c = app.test_client()439+ rv = c.get('/')440+ assert rv.last_modified == last_modified441+442+ def test_send_file_object_without_mimetype(self):443+ app = flask.Flask(__name__)444+445+ with app.test_request_context():446+ with pytest.raises(ValueError) as excinfo:447+ flask.send_file(StringIO("LOL"))448+ assert 'Unable to infer MIME-type' in str(excinfo)449+ assert 'no filename is available' in str(excinfo)450+451+ with app.test_request_context():452+ flask.send_file(StringIO("LOL"), attachment_filename='filename')453+454+ def test_send_file_object(self):455+ app = flask.Flask(__name__)456+457+ with app.test_request_context():458+ with open(os.path.join(app.root_path, 'static/index.html'), mode='rb') as f:459+ rv = flask.send_file(f, mimetype='text/html')460+ rv.direct_passthrough = False461+ with app.open_resource('static/index.html') as f:462+ assert rv.data == f.read()463+ assert rv.mimetype == 'text/html'464+ rv.close()465+466+ app.use_x_sendfile = True467+468+ with app.test_request_context():469+ with open(os.path.join(app.root_path, 'static/index.html')) as f:470+ rv = flask.send_file(f, mimetype='text/html')471+ assert rv.mimetype == 'text/html'472+ assert 'x-sendfile' not in rv.headers473+ rv.close()474+475+ 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()483+484+ class PyStringIO(object):485+ def __init__(self, *args, **kwargs):486+ self._io = StringIO(*args, **kwargs)487+ def __getattr__(self, name):488+ return getattr(self._io, name)489+ f = PyStringIO('Test')490+ f.name = 'test.txt'491+ rv = flask.send_file(f, attachment_filename=f.name)492+ rv.direct_passthrough = False493+ assert rv.data == b'Test'494+ assert rv.mimetype == 'text/plain'495+ rv.close()496+497+ f = StringIO('Test')498+ rv = flask.send_file(f, mimetype='text/plain')499+ rv.direct_passthrough = False500+ assert rv.data == b'Test'501+ assert rv.mimetype == 'text/plain'502+ rv.close()503+504+ app.use_x_sendfile = True505+506+ with app.test_request_context():507+ f = StringIO('Test')508+ rv = flask.send_file(f, mimetype='text/html')509+ assert 'x-sendfile' not in rv.headers510+ rv.close()511+512+ @pytest.mark.skipif(513+ not callable(getattr(Range, 'to_content_range_header', None)),514+ reason="not implement within werkzeug"515+ )516+ def test_send_file_range_request(self):517+ app = flask.Flask(__name__)518+519+ @app.route('/')520+ def index():521+ return flask.send_file('static/index.html', conditional=True)522+523+ c = app.test_client()524+525+ rv = c.get('/', headers={'Range': 'bytes=4-15'})526+ assert rv.status_code == 206527+ with app.open_resource('static/index.html') as f:528+ assert rv.data == f.read()[4:16]529+ rv.close()530+531+ rv = c.get('/', headers={'Range': 'bytes=4-'})532+ assert rv.status_code == 206533+ with app.open_resource('static/index.html') as f:534+ assert rv.data == f.read()[4:]535+ rv.close()536+537+ rv = c.get('/', headers={'Range': 'bytes=4-1000'})538+ assert rv.status_code == 206539+ with app.open_resource('static/index.html') as f:540+ assert rv.data == f.read()[4:]541+ rv.close()542+543+ rv = c.get('/', headers={'Range': 'bytes=-10'})544+ assert rv.status_code == 206545+ with app.open_resource('static/index.html') as f:546+ assert rv.data == f.read()[-10:]547+ rv.close()548+549+ rv = c.get('/', headers={'Range': 'bytes=1000-'})550+ assert rv.status_code == 416551+ rv.close()552+553+ rv = c.get('/', headers={'Range': 'bytes=-'})554+ assert rv.status_code == 416555+ rv.close()556+557+ rv = c.get('/', headers={'Range': 'somethingsomething'})558+ assert rv.status_code == 416559+ rv.close()560+561+ last_modified = datetime.datetime.utcfromtimestamp(os.path.getmtime(562+ os.path.join(app.root_path, 'static/index.html'))).replace(563+ microsecond=0)564+565+ rv = c.get('/', headers={'Range': 'bytes=4-15',566+ 'If-Range': http_date(last_modified)})567+ assert rv.status_code == 206568+ rv.close()569+570+ rv = c.get('/', headers={'Range': 'bytes=4-15', 'If-Range': http_date(571+ datetime.datetime(1999, 1, 1))})572+ assert rv.status_code == 200573+ rv.close()574+575+ def test_attachment(self):576+ app = flask.Flask(__name__)577+ with app.test_request_context():578+ with open(os.path.join(app.root_path, 'static/index.html')) as f:579+ rv = flask.send_file(f, as_attachment=True,580+ attachment_filename='index.html')581+ value, options = \582+ parse_options_header(rv.headers['Content-Disposition'])583+ assert value == 'attachment'584+ assert options['filename'] == 'index.html'585+ assert 'filename*' not in rv.headers['Content-Disposition']586+ rv.close()587+588+ 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()594+595+ 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()604+605+ def test_attachment_with_utf8_filename(self):606+ app = flask.Flask(__name__)607+608+ with app.test_request_context():609+ rv = flask.send_file('static/index.html', as_attachment=True, attachment_filename=u'Ñandú/pingüino.txt')610+ content_disposition = set(rv.headers['Content-Disposition'].split('; '))611+ assert content_disposition == set((612+ 'attachment',613+ 'filename="Nandu/pinguino.txt"',614+ "filename*=UTF-8''%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt"615+ ))616+ rv.close()617+618+ def test_static_file(self):619+ app = flask.Flask(__name__)620+ # default cache timeout is 12 hours621+ with app.test_request_context():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()659+660+ 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()670+671+ def test_send_from_directory_bad_request(self):672+ app = flask.Flask(__name__)673+ app.testing = True674+ app.root_path = os.path.join(os.path.dirname(__file__),675+ 'test_apps', 'subdomaintestmodule')676+ with app.test_request_context():677+ with pytest.raises(BadRequest):678+ flask.send_from_directory('static', 'bad\x00')679+680+class TestLogging(object):681+682+ def test_logger_cache(self):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 logger1689+690+ def test_debug_log(self, capsys):691+ app = flask.Flask(__name__)692+ app.debug = True693+694+ @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 ''699+700+ @app.route('/exc')701+ def exc():702+ 1 // 0703+704+ 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 err711+712+ with pytest.raises(ZeroDivisionError):713+ c.get('/exc')714+715+ 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 == 10721+722+ 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))728+729+ @app.route('/')730+ def index():731+ 1 // 0732+733+ rv = app.test_client().get('/')734+ assert rv.status_code == 500735+ assert b'Internal Server Error' in rv.data736+737+ 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 err742+743+ 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'765+766+ 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'773+774+ 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/'781+782+ 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')792+793+ def test_url_for_with_alternating_schemes(self):794+ app = flask.Flask(__name__)795+ @app.route('/')796+ def index():797+ return '42'798+ with app.test_request_context():799+ assert flask.url_for('index', _external=True) == 'http://localhost/'800+ assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'801+ assert flask.url_for('index', _external=True) == 'http://localhost/'802+803+ def test_url_with_method(self):804+ from flask.views import MethodView805+ app = flask.Flask(__name__)806+ class MyView(MethodView):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)820+821+ 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'825+826+827+class TestNoImports(object):828+ """Test Flasks are created without import.829+830+ 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+ """837+838+ 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.'844+845+846+class TestStreaming(object):847+848+ 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!'861+862+ 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!'876+877+ 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]903+904+905+class 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+ )924+925+ for args, expected in passing:926+ assert flask.safe_join(*args) == expected927+928+ 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+ )940+941+ 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+ ~~~~~~~~~~~~~~~~~~~5+6+ :copyright: (c) 2015 by the Flask Team, see AUTHORS for more details.7+ :license: BSD, see LICENSE for more details.8+"""9+import os10+import sys11+12+import pytest13+import flask14+from flask._compat import PY215+16+17+def 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)21+22+ app = flask.Flask(__name__, instance_path=str(modules_tmpdir))23+ assert app.instance_path == str(modules_tmpdir)24+25+26+def 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')30+31+ from main_app import app32+ here = os.path.abspath(os.getcwd())33+ assert app.instance_path == os.path.join(here, 'instance')34+35+36+def 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')44+45+ from config_module_app import app46+ assert app.instance_path == str(modules_tmpdir.join('instance'))47+48+49+def 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')59+60+ from config_package_app import app61+ assert app.instance_path == str(modules_tmpdir.join('instance'))62+63+64+def 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')71+72+ from site_app import app73+ assert app.instance_path == \74+ modules_tmpdir.join('var').join('site_app-instance')75+76+77+def 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)82+83+ 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')87+88+ from installed_package import app89+ assert app.instance_path == \90+ modules_tmpdir.join('var').join('installed_package-instance')91+92+93+def 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')100+101+ import site_package102+ assert site_package.app.instance_path == \103+ modules_tmpdir.join('var').join('site_package-instance')104+105+106+def 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']119+120+121+@pytest.mark.skipif(not PY2, reason='This only works under Python 2.')122+def 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__)')125+126+ class Loader(object):127+ def find_module(self, name, path=None):128+ return self129+130+ sys.meta_path.append(Loader())131+ request.addfinalizer(sys.meta_path.pop)132+133+ with pytest.raises(AttributeError):134+ import unimportableadded:tests/test_regression.py+102 added
1+# -*- coding: utf-8 -*-2+"""3+ tests.regression4+ ~~~~~~~~~~~~~~~~~~~~~~~~~~5+6+ Tests regressions.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import pytest13+14+import os15+import gc16+import sys17+import flask18+import threading19+from werkzeug.exceptions import NotFound20+21+22+_gc_lock = threading.Lock()23+24+25+class assert_no_leak(object):26+27+ def __enter__(self):28+ gc.disable()29+ _gc_lock.acquire()30+ loc = flask._request_ctx_stack._local31+32+ # 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]37+38+ gc.collect()39+ self.old_objects = len(gc.get_objects())40+41+ 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()48+49+50+def test_memory_consumption():51+ app = flask.Flask(__name__)52+53+ @app.route('/')54+ def index():55+ return flask.render_template('simple_template.html', whiskey=42)56+57+ 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>'62+63+ # Trigger caches64+ fire()65+66+ # 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()72+73+74+def test_safe_join_toplevel_pardir():75+ from flask.helpers import safe_join76+ with pytest.raises(NotFound):77+ safe_join('/foo', '..')78+79+80+def test_aborting():81+ class Foo(Exception):82+ whatever = 4283+ app = flask.Flask(__name__)84+ app.testing = True85+86+ @app.errorhandler(Foo)87+ def handle_foo(e):88+ return str(e.whatever)89+90+ @app.route('/')91+ def index():92+ raise flask.abort(flask.redirect(flask.url_for('test')))93+94+ @app.route('/test')95+ def test():96+ raise Foo()97+98+ 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+ ~~~~~~~~~~~~5+6+ Tests the request context.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import pytest13+14+import flask15+from flask.sessions import SessionInterface16+17+try:18+ from greenlet import greenlet19+except ImportError:20+ greenlet = None21+22+23+def test_teardown_on_pop():24+ buffer = []25+ app = flask.Flask(__name__)26+ @app.teardown_request27+ def end_of_request(exception):28+ buffer.append(exception)29+30+ ctx = app.test_request_context()31+ ctx.push()32+ assert buffer == []33+ ctx.pop()34+ assert buffer == [None]35+36+def 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)42+43+ try:44+ raise Exception('dummy')45+ except Exception:46+ pass47+48+ with app.test_request_context():49+ assert buffer == []50+ assert buffer == [None]51+52+def 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)58+59+ with app.test_request_context():60+ assert buffer == []61+ try:62+ raise Exception('dummy')63+ except Exception:64+ pass65+ assert buffer == [None]66+67+def test_proper_test_request_context():68+ app = flask.Flask(__name__)69+ app.config.update(70+ SERVER_NAME='localhost.localdomain:5000'71+ )72+73+ @app.route('/')74+ def index():75+ return None76+77+ @app.route('/', subdomain='foo')78+ def sub():79+ return None80+81+ with app.test_request_context('/'):82+ assert flask.url_for('index', _external=True) == \83+ 'http://localhost.localdomain:5000/'84+85+ with app.test_request_context('/'):86+ assert flask.url_for('sub', _external=True) == \87+ 'http://foo.localhost.localdomain:5000/'88+89+ 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+ )98+99+ app.config.update(SERVER_NAME='localhost')100+ with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}):101+ pass102+103+ app.config.update(SERVER_NAME='localhost:80')104+ with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}):105+ pass106+107+def 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.url115+116+ 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 None121+122+def 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()133+134+def test_manual_context_binding():135+ app = flask.Flask(__name__)136+ @app.route('/')137+ def index():138+ return 'Hello %s!' % flask.request.args['name']139+140+ 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()146+147+@pytest.mark.skipif(greenlet is None, reason='greenlet not installed')148+def test_greenlet_context_copying():149+ app = flask.Flask(__name__)150+ greenlets = []151+152+ @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!'167+168+ rv = app.test_client().get('/?foo=bar')169+ assert rv.data == b'Hello World!'170+171+ result = greenlets[0].run()172+ assert result == 42173+174+@pytest.mark.skipif(greenlet is None, reason='greenlet not installed')175+def test_greenlet_context_copying_api():176+ app = flask.Flask(__name__)177+ greenlets = []178+179+ @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!'191+192+ rv = app.test_client().get('/?foo=bar')193+ assert rv.data == b'Hello World!'194+195+ result = greenlets[0].run()196+ assert result == 42197+198+199+def test_session_error_pops_context():200+ class SessionError(Exception):201+ pass202+203+ class FailingSessionInterface(SessionInterface):204+ def open_session(self, app, request):205+ raise SessionError()206+207+ class CustomFlask(flask.Flask):208+ session_interface = FailingSessionInterface()209+210+ app = CustomFlask(__name__)211+212+ @app.route('/')213+ def index():214+ # shouldn't get here215+ assert False216+217+ response = app.test_client().get('/')218+ assert response.status_code == 500219+ assert not flask.request220+ assert not flask.current_appadded:tests/test_signals.py+202 added
1+# -*- coding: utf-8 -*-2+"""3+ tests.signals4+ ~~~~~~~~~~~~~~~~~~~~~~~5+6+ Signalling.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import pytest13+14+try:15+ import blinker16+except ImportError:17+ blinker = None18+19+import flask20+21+22+pytestmark = pytest.mark.skipif(23+ blinker is None,24+ reason='Signals require the blinker library.'25+)26+27+def test_template_rendered():28+ app = flask.Flask(__name__)29+30+ @app.route('/')31+ def index():32+ return flask.render_template('simple_template.html', whiskey=42)33+34+ recorded = []35+36+ def record(sender, template, context):37+ recorded.append((template, context))38+39+ 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)48+49+def test_before_render_template():50+ app = flask.Flask(__name__)51+52+ @app.route('/')53+ def index():54+ return flask.render_template('simple_template.html', whiskey=42)55+56+ recorded = []57+58+ def record(sender, template, context):59+ context['whiskey'] = 4360+ recorded.append((template, context))61+62+ 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)72+73+def test_request_signals():74+ app = flask.Flask(__name__)75+ calls = []76+77+ def before_request_signal(sender):78+ calls.append('before-signal')79+80+ def after_request_signal(sender, response):81+ assert response.data == b'stuff'82+ calls.append('after-signal')83+84+ @app.before_request85+ def before_request_handler():86+ calls.append('before-handler')87+88+ @app.after_request89+ def after_request_handler(response):90+ calls.append('after-handler')91+ response.data = 'stuff'92+ return response93+94+ @app.route('/')95+ def index():96+ calls.append('handler')97+ return 'ignored anyway'98+99+ flask.request_started.connect(before_request_signal, app)100+ flask.request_finished.connect(after_request_signal, app)101+102+ try:103+ rv = app.test_client().get('/')104+ assert rv.data == b'stuff'105+106+ 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)111+112+def test_request_exception_signal():113+ app = flask.Flask(__name__)114+ recorded = []115+116+ @app.route('/')117+ def index():118+ 1 // 0119+120+ def record(sender, exception):121+ recorded.append(exception)122+123+ 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)130+131+def test_appcontext_signals():132+ app = flask.Flask(__name__)133+ recorded = []134+135+ def record_push(sender, **kwargs):136+ recorded.append('push')137+138+ def record_pop(sender, **kwargs):139+ recorded.append('pop')140+141+ @app.route('/')142+ def index():143+ return 'Hello'144+145+ 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)156+157+def test_flash_signal():158+ app = flask.Flask(__name__)159+ app.config['SECRET_KEY'] = 'secret'160+161+ @app.route('/')162+ def index():163+ flask.flash('This is a flash message', category='notice')164+ return flask.redirect('/other')165+166+ recorded = []167+168+ def record(sender, message, category):169+ recorded.append((message, category))170+171+ 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)182+183+def test_appcontext_tearing_down_signal():184+ app = flask.Flask(__name__)185+ recorded = []186+187+ def record_teardown(sender, **kwargs):188+ recorded.append(('tear_down', kwargs))189+190+ @app.route('/')191+ def index():192+ 1 // 0193+194+ 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+ ~~~~~~~~~~~~~~~~~5+6+ Test that certain behavior of flask can be customized by7+ subclasses.8+9+ :copyright: (c) 2015 by Armin Ronacher.10+ :license: BSD, see LICENSE for more details.11+"""12+import flask13+from logging import StreamHandler14+15+from flask._compat import StringIO16+17+18+def test_suppressed_exception_logging():19+ class SuppressedFlask(flask.Flask):20+ def log_exception(self, exc_info):21+ pass22+23+ out = StringIO()24+ app = SuppressedFlask(__name__)25+ app.logger_name = 'flask_tests/test_suppressed_exception_logging'26+ app.logger.addHandler(StreamHandler(out))27+28+ @app.route('/')29+ def index():30+ 1 // 031+32+ rv = app.test_client().get('/')33+ assert rv.status_code == 50034+ assert b'Internal Server Error' in rv.data35+36+ err = out.getvalue()37+ assert err == ''added:tests/test_templating.py+392 added
1+# -*- coding: utf-8 -*-2+"""3+ tests.templating4+ ~~~~~~~~~~~~~~~~5+6+ Template functionality7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import pytest13+14+import flask15+import logging16+from jinja2 import TemplateNotFound17+18+19+def 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'29+30+def 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'37+38+def 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)44+45+ with app.app_context():46+ rv = flask.render_template_string('Hello {{ config.WORLD_NAME }} '47+ '{{ foo }}')48+ assert rv == 'Hello Special World 42'49+50+def 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']65+66+def 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'<p>Hello World!',76+ b'<p>Hello World!',77+ b'<p>Hello World!',78+ b'<p>Hello World!',79+ b'<p>Hello World!',80+ b'<p>Hello World!'81+ ]82+83+def 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'<p>Hello World!',97+ b'<p>Hello World!',98+ b'<p>Hello World!',99+ b'<p>Hello World!'100+ ]101+102+def 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>') == '<test>'107+ assert flask.render_template('mail.txt', foo='<test>') == \108+ '<test> Mail'109+110+def 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!'115+116+def 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'124+125+def 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'133+134+def 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'142+143+def 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'151+152+def 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'162+163+def 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'173+174+def 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'184+185+def 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'195+196+def 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)204+205+def 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)213+214+def 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)222+223+def 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)231+232+def 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.data242+243+def 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.data253+254+def 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.data264+265+def 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.data275+276+def 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'287+288+def 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!'300+301+def 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)313+314+ rv = app.test_client().get('/')315+ assert rv.data == b'<h1>Jameson</h1>'316+317+def 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 True348+349+def test_template_loader_debugging(test_apps):350+ from blueprintapp import app351+352+ 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 text366+367+ 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'] = True373+374+ with pytest.raises(TemplateNotFound) as excinfo:375+ c.get('/missing')376+377+ assert 'missing_template.html' in str(excinfo.value)378+ finally:379+ app.logger.handlers[:] = old_handlers380+ app.config['EXPLAIN_TEMPLATE_LOADING'] = old_load_setting381+382+ assert len(called) == 1383+384+def test_custom_jinja_env():385+ class CustomEnvironment(flask.templating.Environment):386+ pass387+388+ class CustomFlask(flask.Flask):389+ jinja_environment = CustomEnvironment390+391+ 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+ ~~~~~~~~~~~~~5+6+ Test client and more.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+import pytest12+13+import flask14+import werkzeug15+16+from flask._compat import text_type17+18+19+def 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.url27+28+ 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/'33+34+def test_environ_defaults():35+ app = flask.Flask(__name__)36+ app.testing = True37+ @app.route('/')38+ def index():39+ return flask.request.url40+41+ 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/'46+47+def test_environ_base_default():48+ app = flask.Flask(__name__)49+ app.testing = True50+ @app.route('/')51+ def index():52+ flask.g.user_agent = flask.request.headers["User-Agent"]53+ return flask.request.remote_addr54+55+ with app.test_client() as c:56+ rv = c.get('/')57+ assert rv.data == b'127.0.0.1'58+ assert flask.g.user_agent == 'werkzeug/' + werkzeug.__version__59+60+def test_environ_base_modified():61+ app = flask.Flask(__name__)62+ app.testing = True63+ @app.route('/')64+ def index():65+ flask.g.user_agent = flask.request.headers["User-Agent"]66+ return flask.request.remote_addr67+68+ with app.test_client() as c:69+ c.environ_base['REMOTE_ADDR'] = '0.0.0.0'70+ c.environ_base['HTTP_USER_AGENT'] = 'Foo'71+ rv = c.get('/')72+ assert rv.data == b'0.0.0.0'73+ assert flask.g.user_agent == 'Foo'74+75+ c.environ_base['REMOTE_ADDR'] = '0.0.0.1'76+ c.environ_base['HTTP_USER_AGENT'] = 'Bar'77+ rv = c.get('/')78+ assert rv.data == b'0.0.0.1'79+ assert flask.g.user_agent == 'Bar'80+81+def test_redirect_keep_session():82+ app = flask.Flask(__name__)83+ app.secret_key = 'testing'84+85+ @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'91+92+ @app.route('/getsession')93+ def get_session():94+ return flask.session.get('data', '<missing>')95+96+ with app.test_client() as c:97+ rv = c.get('/getsession')98+ assert rv.data == b'<missing>'99+100+ 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'105+106+ # This support requires a new Werkzeug version107+ if not hasattr(c, 'redirect_client'):108+ assert flask.session.get('data') == 'foo'109+110+ rv = c.get('/getsession')111+ assert rv.data == b'foo'112+113+def test_session_transactions():114+ app = flask.Flask(__name__)115+ app.testing = True116+ app.secret_key = 'testing'117+118+ @app.route('/')119+ def index():120+ return text_type(flask.session['foo'])121+122+ 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]132+133+def test_session_transactions_no_null_sessions():134+ app = flask.Flask(__name__)135+ app.testing = True136+137+ 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)142+143+def test_session_transactions_keep_context():144+ app = flask.Flask(__name__)145+ app.testing = True146+ app.secret_key = 'testing'147+148+ 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()154+155+def 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)163+164+def 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!'171+172+ @app.route('/other')173+ def other():174+ 1 // 0175+176+ 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 == 200181+182+ 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 = 23187+188+ try:189+ flask.g.value190+ except (AttributeError, RuntimeError):191+ pass192+ else:193+ raise AssertionError('some kind of exception expected')194+195+def test_reuse_client():196+ app = flask.Flask(__name__)197+ c = app.test_client()198+199+ with c:200+ assert c.get('/').status_code == 404201+202+ with c:203+ assert c.get('/').status_code == 404204+205+def test_test_client_calls_teardown_handlers():206+ app = flask.Flask(__name__)207+ called = []208+ @app.teardown_request209+ def remember(error):210+ called.append(error)211+212+ with app.test_client() as c:213+ assert called == []214+ c.get('/')215+ assert called == []216+ assert called == [None]217+218+ 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]226+227+def test_full_url_request():228+ app = flask.Flask(__name__)229+ app.testing = True230+231+ @app.route('/action', methods=['POST'])232+ def action():233+ return 'x'234+235+ 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.args240+241+def 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_id247+248+ with app.test_request_context():249+ url = flask.url_for('view', company_id='xxx')250+251+ with app.test_client() as c:252+ response = c.get(url)253+254+ assert 200 == response.status_code255+ assert b'xxx' == response.data256+257+def 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_id263+264+ with app.test_request_context():265+ url = flask.url_for('view', company_id='xxx')266+267+ with app.test_client() as c:268+ response = c.get(url)269+270+ assert 200 == response.status_code271+ assert b'xxx' == response.dataadded:tests/test_user_error_handler.py+140 added
1+# -*- coding: utf-8 -*-2+from werkzeug.exceptions import Forbidden, InternalServerError3+import flask4+5+6+def test_error_handler_no_match():7+ app = flask.Flask(__name__)8+9+ class CustomException(Exception):10+ pass11+12+ @app.errorhandler(CustomException)13+ def custom_exception_handler(e):14+ assert isinstance(e, CustomException)15+ return 'custom'16+17+ @app.errorhandler(500)18+ def handle_500(e):19+ return type(e).__name__20+21+ @app.route('/custom')22+ def custom_test():23+ raise CustomException()24+25+ @app.route('/keyerror')26+ def key_error():27+ raise KeyError()28+29+ c = app.test_client()30+31+ assert c.get('/custom').data == b'custom'32+ assert c.get('/keyerror').data == b'KeyError'33+34+35+def test_error_handler_subclass():36+ app = flask.Flask(__name__)37+38+ class ParentException(Exception):39+ pass40+41+ class ChildExceptionUnregistered(ParentException):42+ pass43+44+ class ChildExceptionRegistered(ParentException):45+ pass46+47+ @app.errorhandler(ParentException)48+ def parent_exception_handler(e):49+ assert isinstance(e, ParentException)50+ return 'parent'51+52+ @app.errorhandler(ChildExceptionRegistered)53+ def child_exception_handler(e):54+ assert isinstance(e, ChildExceptionRegistered)55+ return 'child-registered'56+57+ @app.route('/parent')58+ def parent_test():59+ raise ParentException()60+61+ @app.route('/child-unregistered')62+ def unregistered_test():63+ raise ChildExceptionUnregistered()64+65+ @app.route('/child-registered')66+ def registered_test():67+ raise ChildExceptionRegistered()68+69+ c = app.test_client()70+71+ 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'74+75+76+def test_error_handler_http_subclass():77+ app = flask.Flask(__name__)78+79+ class ForbiddenSubclassRegistered(Forbidden):80+ pass81+82+ class ForbiddenSubclassUnregistered(Forbidden):83+ pass84+85+ @app.errorhandler(403)86+ def code_exception_handler(e):87+ assert isinstance(e, Forbidden)88+ return 'forbidden'89+90+ @app.errorhandler(ForbiddenSubclassRegistered)91+ def subclass_exception_handler(e):92+ assert isinstance(e, ForbiddenSubclassRegistered)93+ return 'forbidden-registered'94+95+ @app.route('/forbidden')96+ def forbidden_test():97+ raise Forbidden()98+99+ @app.route('/forbidden-registered')100+ def registered_test():101+ raise ForbiddenSubclassRegistered()102+103+ @app.route('/forbidden-unregistered')104+ def unregistered_test():105+ raise ForbiddenSubclassUnregistered()106+107+ c = app.test_client()108+109+ 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'112+113+114+def test_error_handler_blueprint():115+ bp = flask.Blueprint('bp', __name__)116+117+ @bp.errorhandler(500)118+ def bp_exception_handler(e):119+ return 'bp-error'120+121+ @bp.route('/error')122+ def bp_test():123+ raise InternalServerError()124+125+ app = flask.Flask(__name__)126+127+ @app.errorhandler(500)128+ def app_exception_handler(e):129+ return 'app-error'130+131+ @app.route('/error')132+ def app_test():133+ raise InternalServerError()134+135+ app.register_blueprint(bp, url_prefix='/bp')136+137+ c = app.test_client()138+139+ 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+ ~~~~~~~~~~~5+6+ Pluggable views.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import pytest13+14+import flask15+import flask.views16+17+from werkzeug.http import parse_set_header18+19+def common_test(app):20+ c = app.test_client()21+22+ 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']27+28+def test_basic_view():29+ app = flask.Flask(__name__)30+31+ class Index(flask.views.View):32+ methods = ['GET', 'POST']33+ def dispatch_request(self):34+ return flask.request.method35+36+ app.add_url_rule('/', view_func=Index.as_view('index'))37+ common_test(app)38+39+def test_method_based_view():40+ app = flask.Flask(__name__)41+42+ class Index(flask.views.MethodView):43+ def get(self):44+ return 'GET'45+ def post(self):46+ return 'POST'47+48+ app.add_url_rule('/', view_func=Index.as_view('index'))49+50+ common_test(app)51+52+def test_view_patching():53+ app = flask.Flask(__name__)54+55+ class Index(flask.views.MethodView):56+ def get(self):57+ 1 // 058+ def post(self):59+ 1 // 060+61+ class Other(Index):62+ def get(self):63+ return 'GET'64+ def post(self):65+ return 'POST'66+67+ view = Index.as_view('index')68+ view.view_class = Other69+ app.add_url_rule('/', view_func=view)70+ common_test(app)71+72+def test_view_inheritance():73+ app = flask.Flask(__name__)74+75+ class Index(flask.views.MethodView):76+ def get(self):77+ return 'GET'78+ def post(self):79+ return 'POST'80+81+ class BetterIndex(Index):82+ def delete(self):83+ return 'DELETE'84+85+ app.add_url_rule('/', view_func=BetterIndex.as_view('index'))86+ c = app.test_client()87+88+ meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])89+ assert sorted(meths) == ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST']90+91+def test_view_decorators():92+ app = flask.Flask(__name__)93+94+ def add_x_parachute(f):95+ def new_function(*args, **kwargs):96+ resp = flask.make_response(f(*args, **kwargs))97+ resp.headers['X-Parachute'] = 'awesome'98+ return resp99+ return new_function100+101+ class Index(flask.views.View):102+ decorators = [add_x_parachute]103+ def dispatch_request(self):104+ return 'Awesome'105+106+ 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'111+112+def test_implicit_head():113+ app = flask.Flask(__name__)114+115+ class Index(flask.views.MethodView):116+ def get(self):117+ return flask.Response('Blub', headers={118+ 'X-Method': flask.request.method119+ })120+121+ 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'129+130+def test_explicit_head():131+ app = flask.Flask(__name__)132+133+ class Index(flask.views.MethodView):134+ def get(self):135+ return 'GET'136+ def head(self):137+ return flask.Response('', headers={'X-Method': 'HEAD'})138+139+ 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'146+147+def test_endpoint_override():148+ app = flask.Flask(__name__)149+ app.debug = True150+151+ class Index(flask.views.View):152+ methods = ['GET', 'POST']153+ def dispatch_request(self):154+ return flask.request.method155+156+ app.add_url_rule('/', view_func=Index.as_view('index'))157+158+ with pytest.raises(AssertionError):159+ app.add_url_rule('/', view_func=Index.as_view('index'))160+161+ # But these tests should still pass. We just log a warning.162+ common_test(app)163+164+def test_multiple_inheritance():165+ app = flask.Flask(__name__)166+167+ class GetView(flask.views.MethodView):168+ def get(self):169+ return 'GET'170+171+ class DeleteView(flask.views.MethodView):172+ def delete(self):173+ return 'DELETE'174+175+ class GetDeleteView(GetView, DeleteView):176+ pass177+178+ app.add_url_rule('/', view_func=GetDeleteView.as_view('index'))179+180+ c = app.test_client()181+ assert c.get('/').data == b'GET'182+ assert c.delete('/').data == b'DELETE'183+ assert sorted(GetDeleteView.methods) == ['DELETE', 'GET']184+185+def test_remove_method_from_parent():186+ app = flask.Flask(__name__)187+188+ class GetView(flask.views.MethodView):189+ def get(self):190+ return 'GET'191+192+ class OtherView(flask.views.MethodView):193+ def post(self):194+ return 'POST'195+196+ class View(GetView, OtherView):197+ methods = ['GET']198+199+ app.add_url_rule('/', view_func=View.as_view('index'))200+201+ c = app.test_client()202+ assert c.get('/').data == b'GET'203+ assert c.post('/').status_code == 405204+ assert sorted(View.methods) == ['GET']added:.gitattributes+1 added
1+CHANGES merge=unionmodified:.gitignore+9 added
2 unmodified lines3 *.pyo4 env5 env*6 dist7+build8 *.egg9 *.egg-info10 _mailinglist11 .tox12+.cache/13+.idea/14+15+# Coverage reports16+htmlcov17+.coverage18+.coverage.*19+*,covermodified:.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.gitdeleted:.travis-devel-requirements.txt-6 removed
1-git+git://github.com/mitsuhiko/werkzeug.git#egg=Werkzeug2-git+git://github.com/mitsuhiko/jinja2.git#egg=Jinja23-git+git://github.com/mitsuhiko/itsdangerous.git#egg=itsdangerous4-5-# extra dependencies6-git+git://github.com/jek/blinker.git#egg=blinkerdeleted:.travis-lowest-requirements.txt-6 removed
1-Werkzeug==0.72-Jinja2==2.43-itsdangerous==0.214-5-# extra dependencies6-blinker==1.0deleted:.travis-release-requirements.txt-2 removed
1-# extra dependencies2-blinkermodified:.travis.yml+24 added-3 removed
1+sudo: false2 language: python3 4 python:5 - "2.6"6 - "2.7"7 - "pypy"8 - "3.3"9+ - "3.4"10+ - "3.5"11+ - "3.6"12 13 env:14 - REQUIREMENTS=lowest15+ - REQUIREMENTS=lowest-simplejson16 - REQUIREMENTS=release17+ - REQUIREMENTS=release-simplejson18 - REQUIREMENTS=devel19+ - REQUIREMENTS=devel-simplejson20 21 matrix:22 exclude:23 # Python 3 support currently does not work with lowest requirements24 - python: "3.3"25 env: REQUIREMENTS=lowest26+ - python: "3.3"27+ env: REQUIREMENTS=lowest-simplejson28+ - python: "3.4"29+ env: REQUIREMENTS=lowest30+ - python: "3.4"31+ env: REQUIREMENTS=lowest-simplejson32+ - python: "3.5"33+ env: REQUIREMENTS=lowest34+ - python: "3.5"35+ env: REQUIREMENTS=lowest-simplejson36+ - python: "3.6"37+ env: REQUIREMENTS=lowest38+ - python: "3.6"39+ env: REQUIREMENTS=lowest-simplejson40 41 install:21- - pip install -r .travis-$REQUIREMENTS-requirements.txt22- - pip install --editable .42+ - pip install tox43 24-script: make test44+script:45+ - tox -e py-$REQUIREMENTS46 47 branches:48 except:49 - website10 unmodified linesmodified:AUTHORS+7 added-1 removed
13 unmodified lines14 - Chris Edgemon15 - Chris Grindstaff16 - Christopher Grebs17 - Daniel Neuhäuser18+- Dan Sully19+- David Lord @davidism20+- Edmond Burnett21 - Florent Xicluna22 - Georg Brandl23+- Jeff Widman @jeffwidman24+- Joshua Bronson @jab25 - Justin Quick26 - Kenneth Reitz27+- Keyan Pishdadian28 - Marian Sigler29+- Martijn Pieters30 - Matt Campell31 - Matthew Frazier32 - Michael van Tellingen33 - Ron DuPlain1 unmodified line35 - Simon Sapin36 - Stephane Wirtel37 - Thomas Schranz38 - Zhao Xiaohong32-- Edmond Burnettmodified:CHANGES+185 added-24 removed
1 unmodified line2 ===============3 4 Here you can see the full list of changes between each Flask release.5 6-Version 1.07------------6+Version 0.137+------------8 9-(release date to be announced, codename to be selected)9+Major release, unreleased10 11+- Make `app.run()` into a noop if a Flask application is run from the12+ development server on the command line. This avoids some behavior that13+ was confusing to debug for newcomers.14+- Change default configuration `JSONIFY_PRETTYPRINT_REGULAR=False`. jsonify()15+ method returns compressed response by default, and pretty response in16+ debug mode.17+- Change Flask.__init__ to accept two new keyword arguments, ``host_matching``18+ and ``static_host``. This enables ``host_matching`` to be set properly by the19+ time the constructor adds the static route, and enables the static route to20+ be properly associated with the required host. (``#1559``)21+- ``send_file`` supports Unicode in ``attachment_filename``. (`#2223`_)22+- Pass ``_scheme`` argument from ``url_for`` to ``handle_build_error``.23+ (`#2017`_)24+- Add support for ``provide_automatic_options`` in ``add_url_rule`` to disable25+ adding OPTIONS method when the ``view_func`` argument is not a class.26+ (`#1489`_).27+- ``MethodView`` can inherit method handlers from base classes. (`#1936`_)28+- Errors caused while opening the session at the beginning of the request are29+ handled by the app's error handlers. (`#2254`_)30+- Blueprints gained ``json_encoder`` and ``json_decoder`` attributes to31+ override the app's encoder and decoder. (`#1898`_)32+- ``Flask.make_response`` raises ``TypeError`` instead of ``ValueError`` for33+ bad response types. The error messages have been improved to describe why the34+ type is invalid. (`#2256`_)35+- Add ``routes`` CLI command to output routes registered on the application.36+ (`#2259`_)37+- Show warning when session cookie domain is a bare hostname or an IP38+ address, as these may not behave properly in some browsers, such as Chrome.39+ (`#2282`_)40+- Allow IP address as exact session cookie domain. (`#2282`_)41+- ``SESSION_COOKIE_DOMAIN`` is set if it is detected through ``SERVER_NAME``.42+ (`#2282`_)43+44+.. _#1489: https://github.com/pallets/flask/pull/148945+.. _#1898: https://github.com/pallets/flask/pull/189846+.. _#1936: https://github.com/pallets/flask/pull/193647+.. _#2017: https://github.com/pallets/flask/pull/201748+.. _#2223: https://github.com/pallets/flask/pull/222349+.. _#2254: https://github.com/pallets/flask/pull/225450+.. _#2256: https://github.com/pallets/flask/pull/225651+.. _#2259: https://github.com/pallets/flask/pull/225952+.. _#2282: https://github.com/pallets/flask/pull/228253+54+Version 0.12.255+--------------56+57+Released on May 16 201758+59+- Fix a bug in `safe_join` on Windows.60+61+Version 0.12.162+--------------63+64+Bugfix release, released on March 31st 201765+66+- 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.75+76+Version 0.1277+------------78+79+Released on December 21st 2016, codename Punsch.80+81+- 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``.96+97+Version 0.11.298+--------------99+100+Bugfix release, unreleased101+102+- Fix crash when running under PyPy3, see pull request ``#1814``.103+104+Version 0.11.1105+--------------106+107+Bugfix release, released on June 7th 2016.108+109+- Fixed a bug that prevented ``FLASK_APP=foobar/__init__.py`` from working. See110+ pull request ``#1872``.111+112+Version 0.11113+------------114+115+Released on May 29th 2016, codename Absinthe.116+117+- 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.188 189 Version 0.10.2190 --------------191 13 unmodified lines205 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`.211 212 Version 0.10.1213 --------------214 11 unmodified lines226 227 Version 0.10228 ------------229 69-Released on June 13nd 2013, codename Limoncello.230+Released on June 13th 2013, codename Limoncello.231 232 - 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 lines315 - 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 payload12 unmodified lines336 :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 of60 unmodified lines406 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` to43 unmodified lines458 Released on June 28th 2011, codename Grappa459 460 - 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 lines471 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 which28 unmodified lines511 -------------512 513 Bugfix release, released on December 31st 2010514 354-- 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 was36 unmodified lines557 - 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.560 400-.. _blinker: http://pypi.python.org/pypi/blinker561+.. _blinker: https://pypi.python.org/pypi/blinker562 563 Version 0.5.2564 -------------565 16 unmodified lines582 Released on July 6th 2010, codename Calvados583 584 - 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 the23 unmodified lines614 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.620 621 Version 0.3.1622 -------------623 48 unmodified linesadded:CONTRIBUTING.rst+114 added
1+==========================2+How to contribute to Flask3+==========================4+5+Thanks for considering contributing to Flask.6+7+Support questions8+=================9+10+Please, don't use the issue tracker for this. Check whether the ``#pocoo`` IRC11+channel on Freenode can help with your issue. If your problem is not strictly12+Werkzeug or Flask specific, ``#python`` is generally more active.13+`Stack Overflow <https://stackoverflow.com/>`_ is also worth considering.14+15+Reporting issues16+================17+18+- Under which versions of Python does this happen? This is even more important19+ if your issue is encoding related.20+21+- Under which versions of Werkzeug does this happen? Check if this issue is22+ fixed in the repository.23+24+Submitting patches25+==================26+27+- Include tests if your patch is supposed to solve a bug, and explain28+ clearly under which circumstances the bug happens. Make sure the test fails29+ without your patch.30+31+- Try to follow `PEP8 <https://www.python.org/dev/peps/pep-0008/>`_, but you32+ may ignore the line-length-limit if following it would make the code uglier.33+34+35+Running the testsuite36+---------------------37+38+You probably want to set up a `virtualenv39+<https://virtualenv.readthedocs.io/en/latest/index.html>`_.40+41+The minimal requirement for running the testsuite is ``pytest``. You can42+install it with::43+44+ pip install pytest45+46+Clone this repository::47+48+ git clone https://github.com/pallets/flask.git49+50+Install Flask as an editable package using the current source::51+52+ cd flask53+ pip install --editable .54+55+Then you can run the testsuite with::56+57+ pytest tests/58+59+With only pytest installed, a large part of the testsuite will get skipped60+though. Whether this is relevant depends on which part of Flask you're working61+on. Travis is set up to run the full testsuite when you submit your pull62+request anyways.63+64+If you really want to test everything, you will have to install ``tox`` instead65+of ``pytest``. You can install it with::66+67+ pip install tox68+69+The ``tox`` command will then run all tests against multiple combinations70+Python versions and dependency versions.71+72+Running test coverage73+---------------------74+Generating a report of lines that do not have unit test coverage can indicate where75+to start contributing. ``pytest`` integrates with ``coverage.py``, using the ``pytest-cov``76+plugin. This assumes you have already run the testsuite (see previous section)::77+78+ pip install pytest-cov79+80+After this has been installed, you can output a report to the command line using this command::81+82+ pytest --cov=flask tests/83+84+Generate a HTML report can be done using this command::85+86+ pytest --cov-report html --cov=flask tests/87+88+Full docs on ``coverage.py`` are here: https://coverage.readthedocs.io89+90+Caution91+=======92+pushing93+-------94+This repository contains several zero-padded file modes that may cause issues when pushing this repository to git hosts other than github. Fixing this is destructive to the commit history, so we suggest ignoring these warnings. If it fails to push and you're using a self-hosted git service like Gitlab, you can turn off repository checks in the admin panel.95+96+97+cloning98+-------99+The zero-padded file modes files above can cause issues while cloning, too. If you have100+101+::102+103+ [fetch]104+ fsckobjects = true105+106+or107+108+::109+110+ [receive]111+ fsckObjects = true112+113+114+set in your git configuration file, cloning this repository will fail. The only solution is to set both of the above settings to false while cloning, and then setting them back to true after the cloning is finished.modified:LICENSE+1 added-1 removed
1-Copyright (c) 2014 by Armin Ronacher and contributors. See AUTHORS1+Copyright (c) 2015 by Armin Ronacher and contributors. See AUTHORS2 for more details.3 4 Some rights reserved.5 28 unmodified linesmodified:Makefile+2 added-7 removed
1 unmodified line2 3 all: clean-pyc test4 5 test:6- python run-tests.py6+ pip install -r test-requirements.txt7+ tox -e py-release8 8-tox-test:9- tox10-11-test-with-mem:12- RUN_FLASK_MEMORY_TESTS=1 python run-tests.py13-9 audit:10 python setup.py audit11 12 release:29 unmodified linesmodified:MANIFEST.in+10 added-15 removed
1-include Makefile CHANGES LICENSE AUTHORS run-tests.py2-recursive-include artwork *3-recursive-include tests *4-recursive-include examples *5-recursive-include docs *6-recursive-exclude docs *.pyc7-recursive-exclude docs *.pyo8-recursive-exclude tests *.pyc9-recursive-exclude tests *.pyo10-recursive-exclude examples *.pyc11-recursive-exclude examples *.pyo12-recursive-include flask/testsuite/static *13-recursive-include flask/testsuite/templates *14-recursive-include flask/testsuite/test_apps *1+include Makefile CHANGES LICENSE AUTHORS2+3+graft artwork4+graft tests5+graft examples6+graft docs7+8+global-exclude *.py[co]9+10 prune docs/_build16-prune docs/_themes/.git11+prune docs/_themesmodified:README+7 added-17 removed
17 unmodified lines18 improve over time but we don't plan on breaking it.19 20 ~ What do I need?21 22- 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.25 26 ~ Where are the docs?27 28 Go to http://flask.pocoo.org/docs/ for a prebuilt version2 unmodified lines31 32 ~ Where are the tests?33 34 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:37 40- $ python run-tests.py38+ $ pytest39 42- If it's not enough output for you, you can use the43- `--verbose` flag:40+ Details on contributing can be found in CONTRIBUTING.rst41 45- $ python run-tests.py --verbose46-47- If you just want one particular testcase to run you can48- provide it on the command line:49-50- $ python run-tests.py test_to_run51-42 ~ Where can I get help?43 44 Either use the #pocoo IRC channel on irc.freenode.net or45 ask on the mailinglist: http://flask.pocoo.org/mailinglist/4 unmodified linesdeleted:run-tests.py-5 removed
1-#!/usr/bin/env python2-import sys, os3-sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))4-from flask.testsuite import main5-main()modified:setup.cfg+7 added-4 removed
1-[egg_info]2-tag_date = true3-1 [aliases]2 release = egg_info -RDb ''3 7-[wheel]4+[bdist_wheel]5 universal = 16+7+[metadata]8+license_file = LICENSE9+10+[tool:pytest]11+norecursedirs = .* *.egg *.egg-info env* artwork docsmodified:setup.py+29 added-40 removed
6 unmodified lines7 8 Flask is Fun9 ````````````10 11+Save in a hello.py:12+13 .. code:: python14 15 from flask import Flask16 app = Flask(__name__)7 unmodified lines24 25 And Easy to Setup26 `````````````````27 28+And run it:29+30 .. code:: bash31 32 $ pip install Flask33 $ python hello.py34 * Running on http://localhost:5000/35 36+ Ready for production? `Read this first <http://flask.pocoo.org/docs/deploying/>`.37+38 Links39 `````40 41 * `website <http://flask.pocoo.org/>`_42 * `documentation <http://flask.pocoo.org/docs/>`_43 * `development version38- <http://github.com/mitsuhiko/flask/zipball/master#egg=Flask-dev>`_44+ <https://github.com/pallets/flask/zipball/master#egg=Flask-dev>`_45 46 """41-from __future__ import print_function42-from setuptools import Command, setup47+import re48+import ast49+from setuptools import setup50 44-class 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 = []51 52- def initialize_options(self):53- pass52+_version_re = re.compile(r'__version__\s+=\s+(.*)')53 55- def finalize_options(self):56- pass54+with open('flask/__init__.py', 'rb') as f:55+ version = str(ast.literal_eval(_version_re.search(56+ f.read().decode('utf-8')).group(1)))57 58- 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)58 66- 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.")78-59 setup(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
1+toxmodified:tox.ini+30 added-3 removed
1 [tox]2-envlist = py26, py27, pypy, py332+envlist = {py26,py27,pypy}-{lowest,release,devel}{,-simplejson}, {py33,py34,py35,py36}-{release,devel}{,-simplejson}3 4+5+6 [testenv]5-deps = blinker6-commands = python run-tests.py []7+passenv = LANG8+usedevelop=true9+commands =10+ # We need to install those after Flask is installed.11+ pip install -e examples/flaskr12+ pip install -e examples/minitwit13+ pip install -e examples/patterns/largerapp14+ pytest --cov=flask --cov-report html []15+deps=16+ pytest17+ pytest-cov18+ greenlet19+20+ lowest: Werkzeug==0.721+ lowest: Jinja2==2.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: simplejson30+31+[testenv:docs]32+deps = sphinx33+commands = sphinx-build -W -b linkcheck -d {envtmpdir}/doctrees docs docs/_build/linkcheck