Merge branch 'master' into makecov
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Anton Sarukhanov · committed by GitHub · parents 5cadd4a, e706b5e · Browse files · 141 files·+3769 added−2444 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
141 files+3769 added−2444 removed
- tests:+1094 added−111 removed
- other:+2675 added−2333 removed
Provenance
- Commit
4cd0299- Tree
8721450- Author
Anton Sarukhanov <code@ant.sr>- Committer
GitHub <noreply@github.com>- Parent 1
5cadd4a- Parent 2
e706b5e
141 files changed+3769 added−2444 removed
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/pallets/flask">Flask @ GitHub</a></li> <li><a href="http://github.com/pallets/flask/issues">Issue Tracker</a></li> <li><a href="https://pypi.python.org/pypi/Flask">Flask @ PyPI</a></li> <li><a href="https://github.com/pallets/flask">Flask @ GitHub</a></li> <li><a href="https://github.com/pallets/flask/issues">Issue Tracker</a></li></ul>modified:docs/deploying/fastcgi.rst+4 added-4 removed
142 unmodified lines143 ))144 )145 146 alias.url = (147- "/static/" => "/path/to/your/static"147+ "/static/" => "/path/to/your/static/"148 )149 150 url.rewrite-once = (151 "^(/static($|/.*))$" => "$1",6 unmodified lines158 :class:`~werkzeug.contrib.fixers.LighttpdCGIRootFix` middleware.159 160 Make sure to apply it only if you are mounting the application the URL161 root. Also, see the Lighty docs for more information on `FastCGI and Python162-<http://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModFastCGI>`_ (note that162+<https://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModFastCGI>`_ (note that163 explicitly passing a socket to run() is no longer necessary).164 165 Configuring nginx166 -----------------66 unmodified lines233 - The code depending on environment variables that are not set by the234 web server.235 - Different python interpreters being used.236 237-.. _nginx: http://nginx.org/238-.. _lighttpd: http://www.lighttpd.net/237+.. _nginx: https://nginx.org/238+.. _lighttpd: https://www.lighttpd.net/239 .. _cherokee: http://cherokee-project.com/240 .. _flup: https://pypi.python.org/pypi/flupmodified:docs/deploying/index.rst+2 added
19 unmodified lines20 - `Deploying Flask on Heroku <https://devcenter.heroku.com/articles/getting-started-with-python>`_21 - `Deploying Flask on OpenShift <https://developers.openshift.com/en/python-flask.html>`_22 - `Deploying Flask on Webfaction <http://flask.pocoo.org/snippets/65/>`_23 - `Deploying Flask on Google App Engine <https://github.com/kamalgill/flask-appengine-template>`_24+- `Deploying Flask on AWS Elastic Beanstalk <https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-flask.html>`_25 - `Sharing your Localhost Server with Localtunnel <http://flask.pocoo.org/snippets/89/>`_26 - `Deploying on Azure (IIS) <https://azure.microsoft.com/documentation/articles/web-sites-python-configure/>`_27+- `Deploying on PythonAnywhere <https://help.pythonanywhere.com/pages/Flask/>`_28 29 Self-hosted options30 -------------------31 8 unmodified linesmodified:docs/deploying/mod_wsgi.rst+6 added-6 removed
11 unmodified lines12 '__main__':`` block or moved to a separate file. Just make sure it's13 not called because this will always start a local WSGI server which14 we do not want if we deploy that application to mod_wsgi.15 16-.. _Apache: http://httpd.apache.org/16+.. _Apache: https://httpd.apache.org/17 18 Installing `mod_wsgi`19 ---------------------20 92 unmodified lines113 </VirtualHost>114 115 Note: There have been some changes in access control configuration for `Apache 2.4`_.116 117-.. _Apache 2.4: http://httpd.apache.org/docs/trunk/upgrading.html117+.. _Apache 2.4: https://httpd.apache.org/docs/trunk/upgrading.html118 119 Most notably, the syntax for directory permissions has changed from httpd 2.2120 121 .. sourcecode:: apache7 unmodified lines129 130 Require all granted131 132 133-For more information consult the `mod_wsgi wiki`_.133+For more information consult the `mod_wsgi documentation`_.134 135-.. _mod_wsgi: http://code.google.com/p/modwsgi/136-.. _installation instructions: http://code.google.com/p/modwsgi/wiki/QuickInstallationGuide135+.. _mod_wsgi: https://github.com/GrahamDumpleton/mod_wsgi136+.. _installation instructions: https://modwsgi.readthedocs.io/en/develop/installation.html137 .. _virtual python: https://pypi.python.org/pypi/virtualenv138-.. _mod_wsgi wiki: http://code.google.com/p/modwsgi/w/list138+.. _mod_wsgi documentation: https://modwsgi.readthedocs.io/en/develop/index.html139 140 Troubleshooting141 ---------------142 75 unmodified linesmodified:docs/deploying/uwsgi.rst+3 added-3 removed
27 unmodified lines28 Given a flask application in myapp.py, use the following command:29 30 .. sourcecode:: text31 32- $ uwsgi -s /tmp/uwsgi.sock --manage-script-name --mount /yourapplication=myapp:app32+ $ uwsgi -s /tmp/yourapplication.sock --manage-script-name --mount /yourapplication=myapp:app33 34 The ``--manage-script-name`` will move the handling of ``SCRIPT_NAME`` to uwsgi,35 since its smarter about that. It is used together with the ``--mount`` directive36 which will make requests to ``/yourapplication`` be directed to ``myapp:app``.28 unmodified lines65 include uwsgi_params;66 uwsgi_pass unix:/tmp/yourapplication.sock;67 }68 69-.. _nginx: http://nginx.org/70-.. _lighttpd: http://www.lighttpd.net/69+.. _nginx: https://nginx.org/70+.. _lighttpd: https://www.lighttpd.net/71 .. _cherokee: http://cherokee-project.com/72 .. _uwsgi: http://projects.unbit.it/uwsgi/modified:docs/patterns/appfactories.rst+2 added-2 removed
4 unmodified lines5 6 If you are already using packages and blueprints for your application7 (:ref:`blueprints`) there are a couple of really nice ways to further improve8 the experience. A common pattern is creating the application object when9-the blueprint is imported. But if you move the creation of this object,9+the blueprint is imported. But if you move the creation of this object10 into a function, you can then create multiple instances of this app later.11 12 So why would you want to do this?13 45 unmodified lines59 60 It's preferable to create your extensions and app factories so that the61 extension object does not initially get bound to the application.62 63-Using `Flask-SQLAlchemy <http://pythonhosted.org/Flask-SQLAlchemy/>`_,63+Using `Flask-SQLAlchemy <http://flask-sqlalchemy.pocoo.org/>`_,64 as an example, you should not do something along those lines::65 66 def create_app(config_filename):67 app = Flask(__name__)49 unmodified linesmodified:docs/patterns/celery.rst+44 added-36 removed
1-Celery Based Background Tasks2-=============================1+Celery Background Tasks2+=======================3 4-Celery is a task queue for Python with batteries included. It used to5-have a Flask integration but it became unnecessary after some6-restructuring of the internals of Celery with Version 3. This guide fills7-in the blanks in how to properly use Celery with Flask but assumes that8-you generally already read the `First Steps with Celery9-<http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html>`_10-guide in the official Celery documentation.4+If your application has a long running task, such as processing some uploaded5+data or sending email, you don't want to wait for it to finish during a6+request. Instead, use a task queue to send the necessary data to another7+process that will run the task in the background while the request returns8+immediately.9 12-Installing Celery13------------------10+Celery is a powerful task queue that can be used for simple background tasks11+as well as complex multi-stage programs and schedules. This guide will show you12+how to configure Celery using Flask, but assumes you've already read the13+`First Steps with Celery <http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html>`_14+guide in the Celery documentation.15 15-Celery is on the Python Package Index (PyPI), so it can be installed with16-standard Python tools like :command:`pip` or :command:`easy_install`::16+Install17+-------18 19+Celery is a separate Python package. Install it from PyPI using pip::20+21 $ pip install celery22 20-Configuring Celery21-------------------23+Configure24+---------25 26 The first thing you need is a Celery instance, this is called the celery27 application. It serves the same purpose as the :class:`~flask.Flask`28 object in Flask, just for Celery. Since this instance is used as the9 unmodified lines38 39 from celery import Celery40 41 def make_celery(app):39- celery = Celery(app.import_name, backend=app.config['CELERY_BACKEND'],40- broker=app.config['CELERY_BROKER_URL'])42+ celery = Celery(43+ app.import_name,44+ backend=app.config['CELERY_RESULT_BACKEND'],45+ broker=app.config['CELERY_BROKER_URL']46+ )47 celery.conf.update(app.config)42- TaskBase = celery.Task43- class ContextTask(TaskBase):44- abstract = True48+49+ class ContextTask(celery.Task):50 def __call__(self, *args, **kwargs):51 with app.app_context():47- return TaskBase.__call__(self, *args, **kwargs)52+ return self.run(*args, **kwargs)53+54 celery.Task = ContextTask55 return celery56 57 The function creates a new Celery object, configures it with the broker58 from the application config, updates the rest of the Celery config from59 the Flask config and then creates a subclass of the task that wraps the60 task execution in an application context.61 56-Minimal Example62+An example task63 ---------------64 59-With what we have above this is the minimal example of using Celery with60-Flask::65+Let's write a task that adds two numbers together and returns the result. We66+configure Celery's broker and backend to use Redis, create a ``celery``67+application using the factor from above, and then use it to define the task. ::68 69 from flask import Flask70 71 flask_app = Flask(__name__)2 unmodified lines74 CELERY_RESULT_BACKEND='redis://localhost:6379'75 )76 celery = make_celery(flask_app)77 71-78 @celery.task()79 def add_together(a, b):80 return a + b81 76-This task can now be called in the background:82+This task can now be called in the background::83 78->>> result = add_together.delay(23, 42)79->>> result.wait()80-6584+ result = add_together.delay(23, 42)85+ result.wait() # 6586 82-Running the Celery Worker83--------------------------87+Run a worker88+------------89 85-Now if you jumped in and already executed the above code you will be86-disappointed to learn that your ``.wait()`` will never actually return.87-That's because you also need to run celery. You can do that by running88-celery as a worker::90+If you jumped in and already executed the above code you will be91+disappointed to learn that ``.wait()`` will never actually return.92+That's because you also need to run a Celery worker to receive and execute the93+task. ::94 95 $ celery -A your_application.celery worker96 97 The ``your_application`` string has to point to your application's package93-or module that creates the `celery` object.98+or module that creates the ``celery`` object.99+100+Now that the worker is running, ``wait`` will return the result once the task101+is finished.modified:docs/patterns/deferredcallbacks.rst+24 added-52 removed
1 unmodified line2 3 Deferred Request Callbacks4 ==========================5 6-One of the design principles of Flask is that response objects are created7-and passed down a chain of potential callbacks that can modify them or8-replace them. When the request handling starts, there is no response9-object yet. It is created as necessary either by a view function or by10-some other component in the system.6+One of the design principles of Flask is that response objects are created and7+passed down a chain of potential callbacks that can modify them or replace8+them. When the request handling starts, there is no response object yet. It is9+created as necessary either by a view function or by some other component in10+the system.11 12-But what happens if you want to modify the response at a point where the13-response does not exist yet? A common example for that would be a14-before-request function that wants to set a cookie on the response object.12+What happens if you want to modify the response at a point where the response13+does not exist yet? A common example for that would be a14+:meth:`~flask.Flask.before_request` callback that wants to set a cookie on the15+response object.16 16-One way is to avoid the situation. Very often that is possible. For17-instance you can try to move that logic into an after-request callback18-instead. Sometimes however moving that code there is just not a very19-pleasant experience or makes code look very awkward.17+One way is to avoid the situation. Very often that is possible. For instance18+you can try to move that logic into a :meth:`~flask.Flask.after_request`19+callback instead. However, sometimes moving code there makes it more20+more complicated or awkward to reason about.21 21-As an alternative possibility you can attach a bunch of callback functions22-to the :data:`~flask.g` object and call them at the end of the request.23-This way you can defer code execution from anywhere in the application.22+As an alternative, you can use :func:`~flask.after_this_request` to register23+callbacks that will execute after only the current request. This way you can24+defer code execution from anywhere in the application, based on the current25+request.26 25-26-The Decorator27--------------28-29-The following decorator is the key. It registers a function on a list on30-the :data:`~flask.g` object::31-32- from flask import g33-34- def after_this_request(f):35- if not hasattr(g, 'after_request_callbacks'):36- g.after_request_callbacks = []37- g.after_request_callbacks.append(f)38- return f39-40-41-Calling the Deferred42---------------------43-44-Now you can use the `after_this_request` decorator to mark a function to45-be called at the end of the request. But we still need to call them. For46-this the following function needs to be registered as47-:meth:`~flask.Flask.after_request` callback::48-49- @app.after_request50- def call_after_request_callbacks(response):51- for callback in getattr(g, 'after_request_callbacks', ()):52- callback(response)53- return response54-55-56-A Practical Example57--------------------58-27 At any time during a request, we can register a function to be called at the60-end of the request. For example you can remember the current language of the61-user in a cookie in the before-request function::28+end of the request. For example you can remember the current language of the29+user in a cookie in a :meth:`~flask.Flask.before_request` callback::30 63- from flask import request31+ from flask import request, after_this_request32 33 @app.before_request34 def detect_user_language():35 language = request.cookies.get('user_lang')36+37 if language is None:38 language = guess_language_from_request()39+40+ # when the response exists, set a cookie with the language41 @after_this_request42 def remember_language(response):43 response.set_cookie('user_lang', language)44+45 g.language = languagemodified:docs/patterns/distribute.rst+13 added-15 removed
37 unmodified lines38 39 Basic Setup Script40 ------------------41 42-Because you have Flask running, you have setuptools available on your system anyways.43-Flask already depends upon setuptools. If you do not, fear not, there is a44-script to install it for you: `ez_setup.py`_. Just download and45-run with your Python interpreter.42+Because you have Flask installed, you have setuptools available on your system.43+Flask already depends upon setuptools.44 45 Standard disclaimer applies: :ref:`you better use a virtualenv46 <virtualenv>`.47 16 unmodified lines64 )65 66 Please keep in mind that you have to list subpackages explicitly. If you67 want setuptools to lookup the packages for you automatically, you can use70-the `find_packages` function::68+the ``find_packages`` function::69 70 from setuptools import setup, find_packages71 72 setup(73 ...74 packages=find_packages()75 )76 79-Most parameters to the `setup` function should be self explanatory,80-`include_package_data` and `zip_safe` might not be.81-`include_package_data` tells setuptools to look for a :file:`MANIFEST.in` file77+Most parameters to the ``setup`` function should be self explanatory,78+``include_package_data`` and ``zip_safe`` might not be.79+``include_package_data`` tells setuptools to look for a :file:`MANIFEST.in` file80 and install all the entries that match as package data. We will use this81 to distribute the static files and templates along with the Python module84-(see :ref:`distributing-resources`). The `zip_safe` flag can be used to82+(see :ref:`distributing-resources`). The ``zip_safe`` flag can be used to83 force or prevent zip Archive creation. In general you probably don't want84 your packages to be installed as zip files because some tools do not85 support them and they make debugging a lot harder.86 33 unmodified lines120 recursive-include yourapplication/static *121 122 Don't forget that even if you enlist them in your :file:`MANIFEST.in` file, they123 won't be installed for you unless you set the `include_package_data`126-parameter of the `setup` function to ``True``!124+parameter of the ``setup`` function to ``True``!125 126 127 Declaring Dependencies128 ----------------------129 132-Dependencies are declared in the `install_requires` parameter as a list.130+Dependencies are declared in the ``install_requires`` parameter as a list.131 Each item in that list is the name of a package that should be pulled from132 PyPI on installation. By default it will always use the most recent133 version, but you can also provide minimum and maximum version134 requirements. Here some examples::21 unmodified lines156 Installing / Developing157 -----------------------158 159 To install your application (ideally into a virtualenv) just run the162-:file:`setup.py` script with the `install` parameter. It will install your160+:file:`setup.py` script with the ``install`` parameter. It will install your161 application into the virtualenv's site-packages folder and also download162 and install all dependencies::163 164 $ python setup.py install165 166 If you are developing on the package and also want the requirements to be169-installed, you can use the `develop` command instead::167+installed, you can use the ``develop`` command instead::168 169 $ python setup.py develop170 171 This has the advantage of just installing a link to the site-packages172 folder instead of copying the data over. You can then continue to work on175-the code without having to run `install` again after each change.173+the code without having to run ``install`` again after each change.174 175 176 .. _pip: https://pypi.python.org/pypi/pip179-.. _Setuptools: https://pythonhosted.org/setuptools177+.. _Setuptools: https://pypi.python.org/pypi/setuptoolsmodified:docs/patterns/errorpages.rst+35 added-19 removed
45 unmodified lines46 47 Error Handlers48 --------------49 50-An error handler is a function, just like a view function, but it is51-called when an error happens and is passed that error. The error is most52-likely a :exc:`~werkzeug.exceptions.HTTPException`, but in one case it53-can be a different error: a handler for internal server errors will be54-passed other exception instances as well if they are uncaught.50+An error handler is a function that returns a response when a type of error is51+raised, similar to how a view is a function that returns a response when a52+request URL is matched. It is passed the instance of the error being handled,53+which is most likely a :exc:`~werkzeug.exceptions.HTTPException`. An error54+handler for "500 Internal Server Error" will be passed uncaught exceptions in55+addition to explicit 500 errors.56 57 An error handler is registered with the :meth:`~flask.Flask.errorhandler`57-decorator and the error code of the exception. Keep in mind that Flask58-will *not* set the error code for you, so make sure to also provide the59-HTTP status code when returning a response.58+decorator or the :meth:`~flask.Flask.register_error_handler` method. A handler59+can be registered for a status code, like 404, or for an exception class.60 61-Please note that if you add an error handler for "500 Internal Server62-Error", Flask will not trigger it if it's running in Debug mode.61+The status code of the response will not be set to the handler's code. Make62+sure to provide the appropriate HTTP status code when returning a response from63+a handler.64 64-Here an example implementation for a "404 Page Not Found" exception::65+A handler for "500 Internal Server Error" will not be used when running in66+debug mode. Instead, the interactive debugger will be shown.67 68+Here is an example implementation for a "404 Page Not Found" exception::69+70 from flask import render_template71 72 @app.errorhandler(404)73 def page_not_found(e):74+ # note that we set the 404 status explicitly75 return render_template('404.html'), 40476 77+When using the :ref:`application factory pattern <app-factories>`::78+79+ from flask import Flask, render_template80+81+ def page_not_found(e):82+ return render_template('404.html'), 40483+84+ def create_app(config_filename):85+ app = Flask(__name__)86+ app.register_error_handler(404, page_not_found)87+ return app88+89 An example template might be this:90 91 .. sourcecode:: html+jinja92 76- {% extends "layout.html" %}77- {% block title %}Page Not Found{% endblock %}78- {% block body %}79- <h1>Page Not Found</h1>80- <p>What you were looking for is just not there.81- <p><a href="{{ url_for('index') }}">go somewhere nice</a>82- {% endblock %}83-93+ {% extends "layout.html" %}94+ {% block title %}Page Not Found{% endblock %}95+ {% block body %}96+ <h1>Page Not Found</h1>97+ <p>What you were looking for is just not there.98+ <p><a href="{{ url_for('index') }}">go somewhere nice</a>99+ {% endblock %}modified:docs/patterns/favicon.rst+1 added-1 removed
47 unmodified lines48 49 See also50 --------51 52-* The `Favicon <http://en.wikipedia.org/wiki/Favicon>`_ article on52+* The `Favicon <https://en.wikipedia.org/wiki/Favicon>`_ article on53 Wikipediamodified:docs/patterns/fileuploads.rst+10 added-10 removed
19 unmodified lines20 specific upload folder and displays a file to the user. Let's look at the21 bootstrapping code for our application::22 23 import os24- from flask import Flask, request, redirect, url_for24+ from flask import Flask, flash, request, redirect, url_for25 from werkzeug.utils import secure_filename26 27 UPLOAD_FOLDER = '/path/to/the/uploads'28 ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])17 unmodified lines46 the file and redirects the user to the URL for the uploaded file::47 48 def allowed_file(filename):49 return '.' in filename and \50- filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS50+ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS51 52 @app.route('/', methods=['GET', 'POST'])53 def upload_file():54 if request.method == 'POST':2 unmodified lines57 flash('No file part')58 return redirect(request.url)59 file = request.files['file']60 # if user does not select file, browser also61- # submit a empty part without filename61+ # submit an empty part without filename62 if file.filename == '':63 flash('No selected file')64 return redirect(request.url)65 if file and allowed_file(file.filename):4 unmodified lines70 return '''71 <!doctype html>72 <title>Upload new File</title>73 <h1>Upload new File</h1>74- <form action="" method=post enctype=multipart/form-data>75- <p><input type=file name=file>76- <input type=submit value=Upload>74+ <form method=post enctype=multipart/form-data>75+ <input type=file name=file>76+ <input type=submit value=Upload>77 </form>78 '''79 80 So what does that :func:`~werkzeug.utils.secure_filename` function actually do?22 unmodified lines103 104 >>> secure_filename('../../../../home/username/.bashrc')105 'home_username_.bashrc'106 107-Now one last thing is missing: the serving of the uploaded files. In the 108-:func:`upload_file()` we redirect the user to 109-``url_for('uploaded_file', filename=filename)``, that is, ``/uploads/filename``. 107+Now one last thing is missing: the serving of the uploaded files. In the108+:func:`upload_file()` we redirect the user to109+``url_for('uploaded_file', filename=filename)``, that is, ``/uploads/filename``.110 So we write the :func:`uploaded_file` function to return the file of that name. As111 of Flask 0.5 we can use a function that does that for us::112 113 from flask import send_from_directory66 unmodified lines180 `Flask-Uploads`_ that implements a full fledged upload mechanism with white and181 blacklisting of extensions and more.182 183 .. _jQuery: https://jquery.com/184-.. _Flask-Uploads: http://pythonhosted.org/Flask-Uploads/184+.. _Flask-Uploads: https://pythonhosted.org/Flask-Uploads/modified:docs/patterns/flashing.rst+1 added-1 removed
76 unmodified lines77 <h1>Login</h1>78 {% if error %}79 <p class=error><strong>Error:</strong> {{ error }}80 {% endif %}81- <form action="" method=post>81+ <form method=post>82 <dl>83 <dt>Username:84 <dd><input type=text name=username value="{{85 request.form.username }}">65 unmodified linesmodified:docs/patterns/lazyloading.rst+10 added-5 removed
88 unmodified lines89 90 You can further optimize this in terms of amount of keystrokes needed to91 write this by having a function that calls into92 :meth:`~flask.Flask.add_url_rule` by prefixing a string with the project93-name and a dot, and by wrapping `view_func` in a `LazyView` as needed::93+name and a dot, and by wrapping `view_func` in a `LazyView` as needed. ::94 95- def url(url_rule, import_name, **options):95+ def url(import_name, url_rules=[], **options):96 view = LazyView('yourapplication.' + import_name)97+ for url_rule in url_rules:97- app.add_url_rule(url_rule, view_func=view, **options)98+ app.add_url_rule(url_rule, view_func=view, **options)99 99- url('/', 'views.index')100- url('/user/<username>', 'views.user')100+ # add a single route to the index view101+ url('views.index', ['/'])102 103+ # add two routes to a single function endpoint104+ url_rules = ['/user/','/user/<username>']105+ url('views.user', url_rules)106+107 One thing to keep in mind is that before and after request handlers have108 to be in a file that is imported upfront to work properly on the first109 request. The same goes for any kind of remaining decorator.modified:docs/patterns/packages.rst+41 added-11 removed
6 unmodified lines7 module. That is quite simple. Imagine a small application looks like8 this::9 10 /yourapplication11- /yourapplication.py11+ yourapplication.py12 /static13- /style.css13+ style.css14 /templates15 layout.html16 index.html17 login.html18 ...19 20+If you find yourself stuck on something, feel free21+to take a look at the source code for this example.22+You'll find `the full src for this example here`_.23+24 Simple Packages25 ---------------26 27 To convert that into a larger one, just create a new folder4 unmodified lines32 You should then end up with something like that::33 34 /yourapplication35 /yourapplication32- /__init__.py36+ __init__.py37 /static34- /style.css38+ style.css39 /templates40 layout.html41 index.html42 login.html1 unmodified line44 45 But how do you run your application now? The naive ``python46 yourapplication/__init__.py`` will not work. Let's just say that Python47 does not want modules in packages to be the startup file. But that is not44-a big problem, just add a new file called :file:`runserver.py` next to the inner48+a big problem, just add a new file called :file:`setup.py` next to the inner49 :file:`yourapplication` folder with the following contents::50 47- from yourapplication import app48- app.run(debug=True)51+ from setuptools import setup52 53+ setup(54+ name='yourapplication',55+ packages=['yourapplication'],56+ include_package_data=True,57+ install_requires=[58+ 'flask',59+ ],60+ )61+62+In order to run the application you need to export an environment variable 63+that tells Flask where to find the application instance:: 64+65+ export FLASK_APP=yourapplication66+67+If you are outside of the project directory make sure to provide the exact 68+path to your application directory. Similarly you can turn on "debug 69+mode" with this environment variable:: 70+71+ export FLASK_DEBUG=true 72+73+In order to install and run the application you need to issue the following 74+commands::75+76+ pip install -e . 77+ flask run78+79 What did we gain from this? Now we can restructure the application a bit80 into multiple modules. The only thing you have to remember is the81 following quick checklist:82 22 unmodified lines105 106 You should then end up with something like that::107 108 /yourapplication80- /runserver.py109+ setup.py110 /yourapplication82- /__init__.py83- /views.py111+ __init__.py112+ views.py113 /static85- /style.css114+ style.css115 /templates116 layout.html117 index.html118 login.html14 unmodified lines133 :ref:`becomingbig` section for some inspiration how to deal with that.134 135 136 .. _working-with-modules:137+.. _the full src for this example here: https://github.com/pallets/flask/tree/master/examples/patterns/largerapp138 139 Working with Blueprints140 -----------------------141 4 unmodified linesmodified:docs/patterns/sqlalchemy.rst+5 added-5 removed
20 unmodified lines21 22 You can download `Flask-SQLAlchemy`_ from `PyPI23 <https://pypi.python.org/pypi/Flask-SQLAlchemy>`_.24 25-.. _Flask-SQLAlchemy: http://pythonhosted.org/Flask-SQLAlchemy/25+.. _Flask-SQLAlchemy: http://flask-sqlalchemy.pocoo.org/26 27 28 Declarative29 -----------77 unmodified lines107 [<User u'admin'>]108 >>> User.query.filter(User.name == 'admin').first()109 <User u'admin'>110 111-.. _SQLAlchemy: http://www.sqlalchemy.org/111+.. _SQLAlchemy: https://www.sqlalchemy.org/112 .. _declarative:113- http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/113+ https://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/114 115 Manual Object Relational Mapping116 --------------------------------117 16 unmodified lines134 bind=engine))135 def init_db():136 metadata.create_all(bind=engine)137 138-As for the declarative approach you need to close the session after138+As in the declarative approach, you need to close the session after139 each request or application context shutdown. Put this into your140 application module::141 142 from yourapplication.database import db_session71 unmodified lines214 >>> engine.execute('select * from users where id = :1', [1]).first()215 (1, u'admin', u'admin@localhost')216 217 For more information about SQLAlchemy, head over to the218-`website <http://www.sqlalchemy.org/>`_.218+`website <https://www.sqlalchemy.org/>`_.modified:docs/patterns/sqlite3.rst+25 added-8 removed
1 unmodified line2 3 Using SQLite 3 with Flask4 =========================5 6-In Flask you can easily implement the opening of database connections on 7-demand and closing them when the context dies (usually at the end of the 6+In Flask you can easily implement the opening of database connections on7+demand and closing them when the context dies (usually at the end of the8 request).9 10 Here is a simple example of how you can use SQLite 3 with Flask::11 58 unmodified lines70 Now in each request handling function you can access `g.db` to get the71 current open database connection. To simplify working with SQLite, a72 row factory function is useful. It is executed for every result returned73 from the database to convert the result. For instance, in order to get74-dictionaries instead of tuples, this could be inserted into ``get_db``::74+dictionaries instead of tuples, this could be inserted into the ``get_db``75+function we created above::76 77 def make_dicts(cursor, row):78 return dict((cursor.description[idx][0], value)79 for idx, value in enumerate(row))80 81 db.row_factory = make_dicts82 82-Or even simpler::83+This will make the sqlite3 module return dicts for this database connection, which are much nicer to deal with. Even more simply, we could place this in ``get_db`` instead::84 85 db.row_factory = sqlite3.Row86 87+This would use Row objects rather than dicts to return the results of queries. These are ``namedtuple`` s, so we can access them either by index or by key. For example, assuming we have a ``sqlite3.Row`` called ``r`` for the rows ``id``, ``FirstName``, ``LastName``, and ``MiddleInitial``::88+89+ >>> # You can get values based on the row's name90+ >>> r['FirstName']91+ John92+ >>> # Or, you can get them based on index93+ >>> r[1]94+ John95+ # Row objects are also iterable:96+ >>> for value in r:97+ ... print(value)98+ 199+ John100+ Doe101+ M102+103 Additionally, it is a good idea to provide a query function that combines104 getting the cursor, executing and fetching the results::88- 105+106 def query_db(query, args=(), one=False):107 cur = get_db().execute(query, args)108 rv = cur.fetchall()109 cur.close()110 return (rv[0] if rv else None) if one else rv111 95-This handy little function, in combination with a row factory, makes 96-working with the database much more pleasant than it is by just using the 112+This handy little function, in combination with a row factory, makes113+working with the database much more pleasant than it is by just using the114 raw cursor and connection objects.115 116 Here is how you can use it::117 12 unmodified lines130 To pass variable parts to the SQL statement, use a question mark in the131 statement and pass in the arguments as a list. Never directly add them to132 the SQL statement with string formatting because this makes it possible133 to attack the application using `SQL Injections117-<http://en.wikipedia.org/wiki/SQL_injection>`_.134+<https://en.wikipedia.org/wiki/SQL_injection>`_.135 136 Initial Schemas137 ---------------138 16 unmodified linesmodified:docs/patterns/wtforms.rst+2 added-2 removed
17 unmodified lines18 few little helpers that make working with forms and Flask more19 fun. You can get it from `PyPI20 <https://pypi.python.org/pypi/Flask-WTF>`_.21 22-.. _Flask-WTF: http://pythonhosted.org/Flask-WTF/22+.. _Flask-WTF: https://flask-wtf.readthedocs.io/en/stable/23 24 The Forms25 ---------26 80 unmodified lines107 108 .. sourcecode:: html+jinja109 110 {% from "_formhelpers.html" import render_field %}111- <form method=post action="/register">111+ <form method=post>112 <dl>113 {{ render_field(form.username) }}114 {{ render_field(form.email) }}115 {{ render_field(form.password) }}11 unmodified linesmodified:docs/tutorial/css.rst+2 added-2 removed
1 .. _tutorial-css:2 3-Step 7: Adding Style3+Step 8: Adding Style4 ====================5 6 Now that everything else works, it's time to add some style to the7 application. Just create a stylesheet called :file:`style.css` in the8-:file:`static` folder we created before:8+:file:`static` folder:9 10 .. sourcecode:: css11 12 body { font-family: sans-serif; background: #eee; }19 unmodified linesmodified:docs/tutorial/dbcon.rst+13 added-15 removed
1 .. _tutorial-dbcon:2 3-Step 3: Database Connections3+Step 4: Database Connections4 ----------------------------5 6-We have created a function for establishing a database connection with7-`connect_db`, but by itself, that's not particularly useful. Creating and8-closing database connections all the time is very inefficient, so we want9-to keep it around for longer. Because database connections encapsulate a10-transaction, we also need to make sure that only one request at the time11-uses the connection. How can we elegantly do that with Flask?6+You currently have a function for establishing a database connection with7+`connect_db`, but by itself, it is not particularly useful. Creating and8+closing database connections all the time is very inefficient, so you will9+need to keep it around for longer. Because database connections10+encapsulate a transaction, you will need to make sure that only one11+request at a time uses the connection. An elegant way to do this is by12+utilizing the *application context*.13 13-This is where the application context comes into play, so let's start14-there.15-16-Flask provides us with two contexts: the application context and the17-request context. For the time being, all you have to know is that there14+Flask provides two contexts: the *application context* and the15+*request context*. For the time being, all you have to know is that there16 are special variables that use these. For instance, the17 :data:`~flask.request` variable is the request object associated with18 the current request, whereas :data:`~flask.g` is a general purpose21-variable associated with the current application context. We will go into22-the details of this a bit later.19+variable associated with the current application context. The tutorial20+will cover some more details of this later on.21 22 For the time being, all you have to know is that you can store information23 safely on the :data:`~flask.g` object.24 9 unmodified lines34 if not hasattr(g, 'sqlite_db'):35 g.sqlite_db = connect_db()36 return g.sqlite_db37 40-So now we know how to connect, but how do we properly disconnect? For38+Now you know how to connect, but how can you properly disconnect? For39 that, Flask provides us with the :meth:`~flask.Flask.teardown_appcontext`40 decorator. It's executed every time the application context tears down::41 42 @app.teardown_appcontext33 unmodified linesmodified:docs/tutorial/dbinit.rst+16 added-15 removed
1 .. _tutorial-dbinit:2 3-Step 4: Creating The Database3+Step 5: Creating The Database4 =============================5 6 As outlined earlier, Flaskr is a database powered application, and more7 precisely, it is an application powered by a relational database system. Such7 unmodified lines15 sqlite3 /tmp/flaskr.db < schema.sql16 17 The downside of this is that it requires the ``sqlite3`` command to be18 installed, which is not necessarily the case on every system. This also19-requires that we provide the path to the database, which can introduce19+requires that you provide the path to the database, which can introduce20 errors. It's a good idea to add a function that initializes the database21-for you to the application.21+for you, to the application.22 23-To do this, we can create a function and hook it into the :command:`flask`24-command that initializes the database. Let me show you the code first. Just25-add this function below the `connect_db` function in :file:`flaskr.py`::23+To do this, you can create a function and hook it into a :command:`flask`24+command that initializes the database. For now just take a look at the25+code segment below. A good place to add this function, and command, is26+just below the `connect_db` function in :file:`flaskr.py`::27 28 def init_db():29 db = get_db()30 with app.open_resource('schema.sql', mode='r') as f:3 unmodified lines34 @app.cli.command('initdb')35 def initdb_command():36 """Initializes the database."""37 init_db()37- print 'Initialized the database.'38+ print('Initialized the database.')39 40 The ``app.cli.command()`` decorator registers a new command with the41 :command:`flask` script. When the command executes, Flask will automatically41-create an application context for us bound to the right application.42-Within the function, we can then access :attr:`flask.g` and other things as43-we would expect. When the script ends, the application context tears down42+create an application context which is bound to the right application.43+Within the function, you can then access :attr:`flask.g` and other things as44+you might expect. When the script ends, the application context tears down45 and the database connection is released.46 46-We want to keep an actual function around that initializes the database,47+You will want to keep an actual function around that initializes the database,48 though, so that we can easily create databases in unit tests later on. (For49 more information see :ref:`testing`.)50 51 The :func:`~flask.Flask.open_resource` method of the application object52 is a convenient helper function that will open a resource that the53 application provides. This function opens a file from the resource53-location (your ``flaskr`` folder) and allows you to read from it. We are54-using this here to execute a script on the database connection.54+location (the :file:`flaskr/flaskr` folder) and allows you to read from it.55+It is used in this example to execute a script on the database connection.56 56-The connection object provided by SQLite can give us a cursor object.57-On that cursor, there is a method to execute a complete script. Finally, we57+The connection object provided by SQLite can give you a cursor object.58+On that cursor, there is a method to execute a complete script. Finally, you59 only have to commit the changes. SQLite3 and other transactional60 databases will not commit unless you explicitly tell it to.61 62 Now, it is possible to create a database with the :command:`flask` script::11 unmodified linesmodified:docs/tutorial/folders.rst+15 added-11 removed
1 unmodified line2 3 Step 0: Creating The Folders4 ============================5 6-Before we get started, let's create the folders needed for this6+Before getting started, you will need to create the folders needed for this7 application::8 9 /flaskr10+ /flaskr10- /static11- /templates11+ /static12+ /templates13 13-The ``flaskr`` folder is not a Python package, but just something where we14-drop our files. Later on, we will put our database schema as well as main15-module into this folder. It is done in the following way. The files inside16-the :file:`static` folder are available to users of the application via HTTP.17-This is the place where CSS and Javascript files go. Inside the18-:file:`templates` folder, Flask will look for `Jinja2`_ templates. The19-templates you create later on in the tutorial will go in this directory.14+The application will be installed and run as Python package. This is the15+recommended way to install and run Flask applications. You will see exactly16+how to run ``flaskr`` later on in this tutorial. For now go ahead and create17+the applications directory structure. In the next few steps you will be18+creating the database schema as well as the main module.19 21-Continue with :ref:`tutorial-schema`.20+As a quick side note, the files inside of the :file:`static` folder are21+available to users of the application via HTTP. This is the place where CSS and22+JavaScript files go. Inside the :file:`templates` folder, Flask will look for23+`Jinja2`_ templates. You will see examples of this later on.24 25+For now you should continue with :ref:`tutorial-schema`.26+27 .. _Jinja2: http://jinja.pocoo.org/modified:docs/tutorial/index.rst+1 added
22 unmodified lines23 introduction24 folders25 schema26 setup27+ packaging28 dbcon29 dbinit30 views31 templates2 unmodified linesmodified:docs/tutorial/introduction.rst+6 added-5 removed
1 unmodified line2 3 Introducing Flaskr4 ==================5 6-We will call our blogging application Flaskr, but feel free to choose your own7-less Web-2.0-ish name ;) Essentially, we want it to do the following things:6+This tutorial will demonstrate a blogging application named Flaskr, but feel7+free to choose your own less Web-2.0-ish name ;) Essentially, it will do the8+following things:9 10 1. Let the user sign in and out with credentials specified in the11 configuration. Only one user is supported.12 2. When the user is logged in, they can add new entries to the page1 unmodified line14 is not sanitized because we trust the user here.15 3. The index page shows all entries so far in reverse chronological order16 (newest on top) and the user can add new ones from there if logged in.17 17-We will be using SQLite3 directly for this application because it's good18-enough for an application of this size. For larger applications, however,18+SQLite3 will be used directly for this application because it's good enough19+for an application of this size. For larger applications, however,20 it makes a lot of sense to use `SQLAlchemy`_, as it handles database21 connections in a more intelligent way, allowing you to target different22 relational databases at once and more. You might also want to consider23 one of the popular NoSQL databases if your data is more suited for those.6 unmodified lines30 :alt: screenshot of the final application31 32 Continue with :ref:`tutorial-folders`.33 33-.. _SQLAlchemy: http://www.sqlalchemy.org/34+.. _SQLAlchemy: https://www.sqlalchemy.org/added:docs/tutorial/packaging.rst+108 added
1+.. _tutorial-packaging:2+3+Step 3: Installing flaskr as a Package4+======================================5+6+Flask is now shipped with built-in support for `Click`_. Click provides7+Flask with enhanced and extensible command line utilities. Later in this8+tutorial you will see exactly how to extend the ``flask`` command line9+interface (CLI).10+11+A useful pattern to manage a Flask application is to install your app12+following the `Python Packaging Guide`_. Presently this involves 13+creating two new files; :file:`setup.py` and :file:`MANIFEST.in` in the 14+projects root directory. You also need to add an :file:`__init__.py` 15+file to make the :file:`flaskr/flaskr` directory a package. After these 16+changes, your code structure should be::17+18+ /flaskr19+ /flaskr20+ __init__.py21+ /static22+ /templates23+ flaskr.py24+ schema.sql25+ setup.py26+ MANIFEST.in27+28+The content of the ``setup.py`` file for ``flaskr`` is:29+30+.. sourcecode:: python31+32+ from setuptools import setup33+34+ setup(35+ name='flaskr',36+ packages=['flaskr'],37+ include_package_data=True,38+ install_requires=[39+ 'flask',40+ ],41+ )42+43+When using setuptools, it is also necessary to specify any special files44+that should be included in your package (in the :file:`MANIFEST.in`).45+In this case, the static and templates directories need to be included,46+as well as the schema. Create the :file:`MANIFEST.in` and add the47+following lines::48+49+ graft flaskr/templates50+ graft flaskr/static51+ include flaskr/schema.sql52+53+To simplify locating the application, add the following import statement 54+into this file, :file:`flaskr/__init__.py`:55+56+.. sourcecode:: python57+58+ from .flaskr import app59+60+This import statement brings the application instance into the top-level 61+of the application package. When it is time to run the application, the 62+Flask development server needs the location of the app instance. This 63+import statement simplifies the location process. Without it the export 64+statement a few steps below would need to be 65+``export FLASK_APP=flaskr.flaskr``.66+67+At this point you should be able to install the application. As usual, it68+is recommended to install your Flask application within a `virtualenv`_.69+With that said, go ahead and install the application with::70+71+ pip install --editable .72+73+The above installation command assumes that it is run within the projects 74+root directory, `flaskr/`. The `editable` flag allows editing 75+source code without having to reinstall the Flask app each time you make 76+changes. The flaskr app is now installed in your virtualenv (see output 77+of ``pip freeze``).78+79+With that out of the way, you should be able to start up the application.80+Do this with the following commands::81+82+ export FLASK_APP=flaskr83+ export FLASK_DEBUG=true84+ flask run85+86+(In case you are on Windows you need to use `set` instead of `export`).87+The :envvar:`FLASK_DEBUG` flag enables or disables the interactive debugger.88+*Never leave debug mode activated in a production system*, because it will89+allow users to execute code on the server!90+91+You will see a message telling you that server has started along with92+the address at which you can access it.93+94+When you head over to the server in your browser, you will get a 404 error95+because we don't have any views yet. That will be addressed a little later,96+but first, you should get the database working.97+98+.. admonition:: Externally Visible Server99+100+ Want your server to be publicly available? Check out the101+ :ref:`externally visible server <public-server>` section for more102+ information.103+104+Continue with :ref:`tutorial-dbcon`.105+106+.. _Click: http://click.pocoo.org107+.. _Python Packaging Guide: https://packaging.python.org108+.. _virtualenv: https://virtualenv.pypa.iomodified:docs/tutorial/schema.rst+5 added-5 removed
1 unmodified line2 3 Step 1: Database Schema4 =======================5 6-First, we want to create the database schema. Only a single table is needed7-for this application and we only want to support SQLite, so creating the8-database schema is quite easy. Just put the following contents into a file9-named `schema.sql` in the just created `flaskr` folder:6+In this step, you will create the database schema. Only a single table is7+needed for this application and it will only support SQLite. All you need to do8+is put the following contents into a file named :file:`schema.sql` in the9+:file:`flaskr/flaskr` folder:10 11 .. sourcecode:: sql12 13 drop table if exists entries;2 unmodified lines16 title text not null,17 'text' text not null18 );19 20-This schema consists of a single table called ``entries``. Each row in20+This schema consists of a single table called ``entries``. Each row in21 this table has an ``id``, a ``title``, and a ``text``. The ``id`` is an22 automatically incrementing integer and a primary key, the other two are23 strings that must not be null.24 1 unmodified linemodified:docs/tutorial/setup.rst+26 added-47 removed
1 unmodified line2 3 Step 2: Application Setup Code4 ==============================5 6-Now that we have the schema in place, we can create the application module.7-Let's call it ``flaskr.py``. We will place this file inside the ``flaskr``8-folder. We will begin by adding the imports we need and by adding the config9-section. For small applications, it is possible to drop the configuration10-directly into the module, and this is what we will be doing here. However,11-a cleaner solution would be to create a separate ``.ini`` or ``.py`` file,12-load that, and import the values from there.6+Now that the schema is in place, you can create the application module,7+:file:`flaskr.py`. This file should be placed inside of the8+:file:`flaskr/flaskr` folder. The first several lines of code in the9+application module are the needed import statements. After that there will be a10+few lines of configuration code. For small applications like ``flaskr``, it is11+possible to drop the configuration directly into the module. However, a cleaner12+solution is to create a separate ``.ini`` or ``.py`` file, load that, and13+import the values from there.14 14-First, we add the imports in :file:`flaskr.py`::15+Here are the import statements (in :file:`flaskr.py`)::16 17 # all the imports18 import os19 import sqlite320 from flask import Flask, request, session, g, redirect, url_for, abort, \21 render_template, flash22 22-Next, we can create our actual application and initialize it with the23-config from the same file in :file:`flaskr.py`::23+The next couple lines will create the actual application instance and24+initialize it with the config from the same file in :file:`flaskr.py`:25 25- # create our little application :)26- app = Flask(__name__)27- app.config.from_object(__name__)26+.. sourcecode:: python27 28+ app = Flask(__name__) # create the application instance :)29+ app.config.from_object(__name__) # load config from this file , flaskr.py30+31 # Load default config and override config from an environment variable32 app.config.update(dict(33 DATABASE=os.path.join(app.root_path, 'flaskr.db'),34 SECRET_KEY='development key',1 unmodified line36 PASSWORD='default'37 ))38 app.config.from_envvar('FLASKR_SETTINGS', silent=True)39 38-The :class:`~flask.Config` object works similarly to a dictionary so we39-can update it with new values.40+The :class:`~flask.Config` object works similarly to a dictionary, so it can be41+updated with new values.42 43 .. admonition:: Database Path44 45 Operating systems know the concept of a current working directory for10 unmodified lines56 :ref:`instance-folders` instead.57 58 Usually, it is a good idea to load a separate, environment-specific59 configuration file. Flask allows you to import multiple configurations and it58-will use the setting defined in the last import. This enables robust60+will use the setting defined in the last import. This enables robust61 configuration setups. :meth:`~flask.Config.from_envvar` can help achieve this.62 61-.. code-block:: python63+.. sourcecode:: python64 65 app.config.from_envvar('FLASKR_SETTINGS', silent=True)66 67 Simply define the environment variable :envvar:`FLASKR_SETTINGS` that points to7 unmodified lines75 76 The ``SECRET_KEY`` is needed to keep the client-side sessions secure.77 Choose that key wisely and as hard to guess and complex as possible.78 77-We will also add a method that allows for easy connections to the78-specified database. This can be used to open a connection on request and79+Lastly, you will add a method that allows for easy connections to the80+specified database. This can be used to open a connection on request and81 also from the interactive Python shell or a script. This will come in80-handy later. We create a simple database connection through SQLite and82+handy later. You can create a simple database connection through SQLite and83 then tell it to use the :class:`sqlite3.Row` object to represent rows.82-This allows us to treat the rows as if they were dictionaries instead of84+This allows the rows to be treated as if they were dictionaries instead of85 tuples.86 85-::87+.. sourcecode:: python88 89 def connect_db():90 """Connects to the specific database."""91 rv = sqlite3.connect(app.config['DATABASE'])92 rv.row_factory = sqlite3.Row93 return rv94 93-With that out of the way, you should be able to start up the application94-without problems. Do this with the following commands::95+In the next section you will see how to run the application.96 96- export FLASK_APP=flaskr97- export FLASK_DEBUG=198- flask run99-100-(In case you are on Windows you need to use `set` instead of `export`).101-The :envvar:`FLASK_DEBUG` flag enables or disables the interactive debugger.102-*Never leave debug mode activated in a production system*, because it will103-allow users to execute code on the server!104-105-You will see a message telling you that server has started along with106-the address at which you can access it.107-108-When you head over to the server in your browser, you will get a 404 error109-because we don't have any views yet. We will focus on that a little later,110-but first, we should get the database working.111-112-.. admonition:: Externally Visible Server113-114- Want your server to be publicly available? Check out the115- :ref:`externally visible server <public-server>` section for more116- information.117-118-Continue with :ref:`tutorial-dbcon`.97+Continue with :ref:`tutorial-packaging`.modified:docs/tutorial/templates.rst+10 added-9 removed
1 .. _tutorial-templates:2 3-Step 6: The Templates3+Step 7: The Templates4 =====================5 6-Now we should start working on the templates. If we were to request the URLs7-now, we would only get an exception that Flask cannot find the templates. The8-templates are using `Jinja2`_ syntax and have autoescaping enabled by6+Now it is time to start working on the templates. As you may have7+noticed, if you make requests with the app running, you will get8+an exception that Flask cannot find the templates. The templates9+are using `Jinja2`_ syntax and have autoescaping enabled by10 default. This means that unless you mark a value in the code with11 :class:`~flask.Markup` or with the ``|safe`` filter in the template,12 Jinja2 will ensure that special characters such as ``<`` or ``>`` are13 escaped with their XML equivalents.43 unmodified lines57 -----------------58 59 This template extends the :file:`layout.html` template from above to display the60 messages. Note that the ``for`` loop iterates over the messages we passed60-in with the :func:`~flask.render_template` function. We also tell the61-form to submit to your `add_entry` function and use ``POST`` as HTTP62-method:61+in with the :func:`~flask.render_template` function. Notice that the form is62+configured to submit to the `add_entry` view function and use ``POST`` as63+HTTP method:64 65 .. sourcecode:: html+jinja66 67 {% extends "layout.html" %}10 unmodified lines78 </form>79 {% endif %}80 <ul class=entries>81 {% for entry in entries %}81- <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}82+ <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}</li>83 {% else %}83- <li><em>Unbelievable. No entries here so far</em>84+ <li><em>Unbelievable. No entries here so far</em></li>85 {% endfor %}86 </ul>87 {% endblock %}88 24 unmodified linesmodified:docs/tutorial/testing.rst+86 added
6 unmodified lines7 expected, it's probably not a bad idea to add automated tests to simplify8 modifications in the future. The application above is used as a basic9 example of how to perform unit testing in the :ref:`testing` section of the10 documentation. Go there to see how easy it is to test Flask applications.11+12+Adding tests to flaskr13+----------------------14+15+Assuming you have seen the :ref:`testing` section and have either written16+your own tests for ``flaskr`` or have followed along with the examples17+provided, you might be wondering about ways to organize the project.18+19+One possible and recommended project structure is::20+21+ flaskr/22+ flaskr/23+ __init__.py24+ static/25+ templates/26+ tests/27+ test_flaskr.py28+ setup.py29+ MANIFEST.in30+31+For now go ahead a create the :file:`tests/` directory as well as the 32+:file:`test_flaskr.py` file.33+34+Running the tests35+-----------------36+37+At this point you can run the tests. Here ``pytest`` will be used. 38+39+.. note:: Make sure that ``pytest`` is installed in the same virtualenv 40+ as flaskr. Otherwise ``pytest`` test will not be able to import the 41+ required components to test the application::42+43+ pip install -e .44+ pip install pytest 45+46+Run and watch the tests pass, within the top-level :file:`flaskr/` 47+directory as::48+49+ pytest50+51+Testing + setuptools52+--------------------53+54+One way to handle testing is to integrate it with ``setuptools``. Here55+that requires adding a couple of lines to the :file:`setup.py` file and56+creating a new file :file:`setup.cfg`. One benefit of running the tests 57+this way is that you do not have to install ``pytest``. Go ahead and 58+update the :file:`setup.py` file to contain::59+60+ from setuptools import setup61+62+ setup(63+ name='flaskr',64+ packages=['flaskr'],65+ include_package_data=True,66+ install_requires=[67+ 'flask',68+ ],69+ setup_requires=[70+ 'pytest-runner',71+ ],72+ tests_require=[73+ 'pytest',74+ ],75+ )76+77+Now create :file:`setup.cfg` in the project root (alongside78+:file:`setup.py`)::79+80+ [aliases]81+ test=pytest82+83+Now you can run::84+85+ python setup.py test86+87+This calls on the alias created in :file:`setup.cfg` which in turn runs88+``pytest`` via ``pytest-runner``, as the :file:`setup.py` script has89+been called. (Recall the `setup_requires` argument in :file:`setup.py`)90+Following the standard rules of test-discovery your tests will be91+found, run, and hopefully pass.92+93+This is one possible way to run and manage testing. Here ``pytest`` is94+used, but there are other options such as ``nose``. Integrating testing95+with ``setuptools`` is convenient because it is not necessary to actually96+download ``pytest`` or any other testing framework one might use.modified:docs/tutorial/views.rst+19 added-19 removed
1 .. _tutorial-views:2 3-Step 5: The View Functions3+Step 6: The View Functions4 ==========================5 6-Now that the database connections are working, we can start writing the7-view functions. We will need four of them:6+Now that the database connections are working, you can start writing the7+view functions. You will need four of them:8 9 Show Entries10 ------------11 17 unmodified lines29 -------------30 31 This view lets the user add new entries if they are logged in. This only32 responds to ``POST`` requests; the actual form is shown on the33-`show_entries` page. If everything worked out well, we will33+`show_entries` page. If everything worked out well, it will34 :func:`~flask.flash` an information message to the next request and35 redirect back to the `show_entries` page::36 37 @app.route('/add', methods=['POST'])6 unmodified lines44 db.commit()45 flash('New entry was successfully posted')46 return redirect(url_for('show_entries'))47 48-Note that we check that the user is logged in here (the `logged_in` key is49-present in the session and ``True``).48+Note that this view checks that the user is logged in (that is, if the49+`logged_in` key is present in the session and ``True``).50 51 .. admonition:: Security Note52 53 Be sure to use question marks when building SQL statements, as done in the26 unmodified lines80 return redirect(url_for('show_entries'))81 return render_template('login.html', error=error)82 83 The `logout` function, on the other hand, removes that key from the session84-again. We use a neat trick here: if you use the :meth:`~dict.pop` method84+again. There is a neat trick here: if you use the :meth:`~dict.pop` method85 of the dict and pass a second parameter to it (the default), the method86 will delete the key from the dictionary if present or do nothing when that87-key is not in there. This is helpful because now we don't have to check88-if the user was logged in.87+key is not in there. This is helpful because now it is not necessary to88+check if the user was logged in.89 90 ::91 92 @app.route('/logout')3 unmodified lines96 return redirect(url_for('show_entries'))97 98 .. admonition:: Security Note99 100- Passwords should never be stored in plain text in a production 101- system. This tutorial uses plain text passwords for simplicity. If you 102- plan to release a project based off this tutorial out into the world, 103- passwords should be both `hashed and salted`_ before being stored in a 104- database or file. 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 of 107- hashing passwords and verifying passwords against hashes, so adding 108- this functionality is fairly straight forward. There are also 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 extensions 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/117+.. _hashed and salted: https://blog.codinghorror.com/youre-probably-storing-passwords-incorrectly/modified:docs/api.rst+3 added-65 removed
28 unmodified lines29 ---------------------30 31 .. autoclass:: Request32 :members:33+ :inherited-members:34 34- .. attribute:: form35-36- A :class:`~werkzeug.datastructures.MultiDict` with the parsed form data from ``POST``37- or ``PUT`` requests. Please keep in mind that file uploads will not38- end up here, but instead in the :attr:`files` attribute.39-40- .. attribute:: args41-42- A :class:`~werkzeug.datastructures.MultiDict` with the parsed contents of the query43- string. (The part in the URL after the question mark).44-45- .. attribute:: values46-47- A :class:`~werkzeug.datastructures.CombinedMultiDict` with the contents of both48- :attr:`form` and :attr:`args`.49-50- .. attribute:: cookies51-52- A :class:`dict` with the contents of all cookies transmitted with53- the request.54-55- .. attribute:: stream56-57- If the incoming form data was not encoded with a known mimetype58- the data is stored unmodified in this stream for consumption. Most59- of the time it is a better idea to use :attr:`data` which will give60- you that data as a string. The stream only returns the data once.61-62- .. attribute:: headers63-64- The incoming request headers as a dictionary like object.65-66- .. attribute:: data67-68- Contains the incoming request data as string in case it came with69- a mimetype Flask does not handle.70-71- .. attribute:: files72-73- A :class:`~werkzeug.datastructures.MultiDict` with files uploaded as part of a74- ``POST`` or ``PUT`` request. Each file is stored as75- :class:`~werkzeug.datastructures.FileStorage` object. It basically behaves like a76- standard file object you know from Python, with the difference that77- it also has a :meth:`~werkzeug.datastructures.FileStorage.save` function that can78- store the file on the filesystem.79-35 .. attribute:: environ36 37 The underlying WSGI environment.38 84- .. attribute:: method85-86- The current request method (``POST``, ``GET`` etc.)87-39 .. attribute:: path40 .. attribute:: full_path41 .. attribute:: script_root42 .. attribute:: url21 unmodified lines64 `url` ``u'http://www.example.com/myapplication/π/page.html?x=y'``65 `url_root` ``u'http://www.example.com/myapplication/'``66 ============= ======================================================67 117- .. attribute:: is_xhr68 119- ``True`` if the request was triggered via a JavaScript120- `XMLHttpRequest`. This only works with libraries that support the121- ``X-Requested-With`` header and set it to `XMLHttpRequest`.122- Libraries that do that are prototype, jQuery and Mochikit and123- probably some more.69+.. attribute:: request70 125-.. class:: request126-71 To access incoming request data, you can use the global `request`72 object. Flask parses incoming request data for you and gives you73 access to it through that global object. Internally Flask makes74 sure that you always get the correct data for the active thread if you184 unmodified lines259 .. autofunction:: has_app_context260 261 .. autofunction:: url_for262 319-.. function:: abort(code)263+.. autofunction:: abort264 321- Raises an :exc:`~werkzeug.exceptions.HTTPException` for the given322- status code. For example to abort request handling with a page not323- found exception, you would call ``abort(404)``.324-325- :param code: the HTTP error code.326-265 .. autofunction:: redirect266 267 .. autofunction:: make_response268 567 unmodified linesmodified:docs/appcontext.rst+3 added-3 removed
72 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 has 78-not been explicitly set, a ``RuntimeError`` will be raised.79-::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 -----------------------55 unmodified linesmodified:docs/becomingbig.rst+1 added-1 removed
10 unmodified lines11 Flask started in part to demonstrate how to build your own framework on top of12 existing well-used tools Werkzeug (WSGI) and Jinja (templating), and as it13 developed, it became useful to a wide audience. As you grow your codebase,14 don't just use Flask -- understand it. Read the source. Flask's code is15-written to be read; it's documentation is published so you can use its internal15+written to be read; its documentation is published so you can use its internal16 APIs. Flask sticks to documented APIs in upstream libraries, and documents its17 internal utilities so that you can find the hook points needed for your18 project.19 82 unmodified linesmodified:docs/blueprints.rst+23 added-5 removed
175 unmodified lines176 177 admin = Blueprint('admin', __name__, template_folder='templates')178 179 For static files, the path can be absolute or relative to the blueprint180-resource folder. 180+resource folder.181 182-The template folder is added to the search path of templates but with a lower 183-priority than the actual application's template folder. That way you can 184-easily override templates that a blueprint provides in the actual application. 182+The template folder is added to the search path of templates but with a lower183+priority than the actual application's template folder. That way you can184+easily override templates that a blueprint provides in the actual application.185 This also means that if you don't want a blueprint template to be accidentally186 overridden, make sure that no other blueprint or actual application template187 has the same relative path. When multiple blueprints provide the same relative188 template path the first blueprint registered takes precedence over the others.4 unmodified lines193 ``templates`` as a `template_folder` you will have to create a file like194 this: :file:`yourapplication/admin/templates/admin/index.html`. The reason195 for the extra ``admin`` folder is to avoid getting our template overridden196 by a template named ``index.html`` in the actual application template197-folder. 197+folder.198 199 To further reiterate this: if you have a blueprint named ``admin`` and you200 want to render a template called :file:`index.html` which is specific to this201 blueprint, the best idea is to lay out your templates like this::42 unmodified lines244 @simple_page.errorhandler(404)245 def page_not_found(e):246 return render_template('pages/404.html')247 248+Most errorhandlers will simply work as expected; however, there is a caveat249+concerning handlers for 404 and 405 exceptions. These errorhandlers are only250+invoked from an appropriate ``raise`` statement or a call to ``abort`` in another251+of the blueprint's view functions; they are not invoked by, e.g., an invalid URL252+access. This is because the blueprint does not "own" a certain URL space, so253+the application instance has no way of knowing which blueprint errorhandler it254+should run if given an invalid URL. If you would like to execute different255+handling strategies for these errors based on URL prefixes, they may be defined256+at the application level using the ``request`` proxy object::257+258+ @app.errorhandler(404)259+ @app.errorhandler(405)260+ def _handle_api_error(ex):261+ if request.path.startswith('/api/'):262+ return jsonify_error(ex)263+ else:264+ return ex265+266 More information on error handling see :ref:`errorpages`.modified:docs/cli.rst+21 added-11 removed
30 unmodified lines31 Python module that contains a Flask application.32 33 In that imported file the name of the app needs to be called ``app`` or34 optionally be specified after a colon. For instance35-`mymodule:application` would tell it to use the `application` object in35+``mymodule:application`` would tell it to use the `application` object in36 the :file:`mymodule.py` file.37 38 Given a :file:`hello.py` file with the application in it named ``app``39 this is how it can be run.15 unmodified lines55 ``export FLASK_APP`` into your ``activate`` script by adding it to the56 bottom of the file. That way every time you activate your virtualenv you57 automatically also activate the correct application name.58 59+Edit the activate script for the shell you use. For example:60+61+Unix Bash: ``venv/bin/activate``::62+63+ FLASK_APP=hello64+ export FLASK_APP65+66+Windows CMD.exe: ``venv\Scripts\activate.bat``::67+68+ set "FLASK_APP=hello"69+ :END70+71 Debug Flag72 ----------73 74 The :command:`flask` script can also be instructed to enable the debug75 mode of the application automatically by exporting ``FLASK_DEBUG``. If64-set to ``1`` debug is enabled or ``0`` disables it.76+set to ``1`` debug is enabled or ``0`` disables it::77 66-Or with a filename::67-78 export FLASK_DEBUG=179 80 Running a Shell81 ---------------68 unmodified lines150 import os151 from yourapplication import create_app152 app = create_app(os.environ['YOURAPPLICATION_CONFIG'])153 144-Once this has happened you can make the flask command automatically pick145-it up::154+Once this has happened you can make the :command:`flask` command automatically155+pick it up::156 157 export YOURAPPLICATION_CONFIG=/path/to/config.cfg158 export FLASK_APP=/path/to/autoapp.py159 67 unmodified lines227 228 CLI Plugins229 -----------230 221-Flask extensions can always patch the `Flask.cli` instance with more231+Flask extensions can always patch the :attr:`Flask.cli` instance with more232 commands if they want. However there is a second way to add CLI plugins223-to Flask which is through `setuptools`. If you make a Python package that224-should export a Flask command line plugin you can ship a `setup.py` file233+to Flask which is through ``setuptools``. If you make a Python package that234+should export a Flask command line plugin you can ship a :file:`setup.py` file235 that declares an entrypoint that points to a click command:236 227-Example `setup.py`::237+Example :file:`setup.py`::238 239 from setuptools import setup240 241 setup(4 unmodified lines246 my-command=mypackage.commands:cli247 ''',248 )249 240-Inside `mypackage/commands.py` you can then export a Click object::250+Inside :file:`mypackage/commands.py` you can then export a Click object::251 252 import click253 254 @click.command()6 unmodified linesmodified:docs/conf.py+54 added-37 removed
9 unmodified lines10 #11 # All configuration values have a default; values that are commented out12 # serve to show the default.13 from __future__ import print_function14-import sys, os14+import os15+import sys16+import pkg_resources17+import time18+import datetime19 20+BUILD_DATE = datetime.datetime.utcfromtimestamp(int(os.environ.get('SOURCE_DATE_EPOCH', time.time())))21+22 # If extensions (or modules to document with autodoc) are in another directory,23 # add these directories to sys.path here. If the directory is relative to the24 # documentation root, use os.path.abspath to make it absolute, like shown here.19-sys.path.append(os.path.abspath('_themes'))20-sys.path.append(os.path.abspath('.'))25+sys.path.append(os.path.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.6 unmodified lines37 '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'49-copyright = u'2015, 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.54-import pkg_resources68 try:69 release = pkg_resources.get_distribution('Flask').version70 except pkg_resources.DistributionNotFound: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)61-del pkg_resources74 75 if 'dev' in release:64- 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'.103-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.108-html_theme_options = {109- 'touch_icon': 'touch-icon.png'110-}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.129-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 = {146- 'index': ['sidebarintro.html', 'sourcelink.html', 'searchbox.html'],147- '**': ['sidebarlogo.html', 'localtoc.html', 'relations.html',148- '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 = [190- ('latexindex', 'Flask.tex', u'Flask Documentation',191- 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 = {201- 'fontpkg': r'\usepackage{mathpazo}',202- 'papersize': 'a4paper',203- 'pointsize': '12pt',204- '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 226-# 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 = {248- 'https://docs.python.org/dev': None,249- 'http://werkzeug.pocoo.org/docs/': None,250- 'http://click.pocoo.org/': None,251- 'http://jinja.pocoo.org/docs/': None,252- 'http://www.sqlalchemy.org/docs/': None,253- 'https://wtforms.readthedocs.io/en/latest/': None,254- 'https://pythonhosted.org/blinker/': 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 257-pygments_style = 'flask_theme_support.FlaskyStyle'258-259-# fall back if theme is not there276 try:277 __import__('flask_theme_support')278+ pygments_style = 'flask_theme_support.FlaskyStyle'279+ html_theme = 'flask'280+ html_theme_options = {281+ 'touch_icon': 'touch-icon.png'282+ }262-except ImportError as e: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 270- pygments_style = 'tango'271- html_theme = 'default'272- html_theme_options = {}291 274-292 # unwrap decorators293 def unwrap_decorators():294 import sphinx.util.inspect as inspect295 import functools15 unmodified linesmodified:docs/config.rst+29 added-15 removed
42 unmodified lines43 DEBUG=True,44 SECRET_KEY='...'45 )46 47+.. admonition:: Debug Mode with the ``flask`` Script48+49+ If you use the :command:`flask` script to start a local development50+ server, to enable the debug mode, you need to export the ``FLASK_DEBUG``51+ environment variable before running the server::52+53+ $ export FLASK_DEBUG=154+ $ flask run55+56+ (On Windows you need to use ``set`` instead of ``export``).57+ 58+ ``app.debug`` and ``app.config['DEBUG']`` are not compatible with 59+ the :command:`flask` script. They only worked when using ``Flask.run()``60+ method.61+ 62 Builtin Configuration Values63 ----------------------------64 65 The following configuration values are used internally by Flask:66 67 .. tabularcolumns:: |p{6.5cm}|p{8.5cm}|68 69 ================================= =========================================55-``DEBUG`` enable/disable debug mode70+``DEBUG`` enable/disable debug mode when using 71+ ``Flask.run()`` method to start server72 ``TESTING`` enable/disable testing mode73 ``PROPAGATE_EXCEPTIONS`` explicitly enable or disable the74 propagation of exceptions. If not set or75 explicitly set to ``None`` this is55 unmodified lines131 help. Setting a ``SERVER_NAME`` also132 by default enables URL generation133 without a request context but with an134 application context.119-``APPLICATION_ROOT`` If the application does not occupy120- a whole domain or subdomain this can121- be set to the path where the application122- is configured to live. This is for123- session cookie as path value. If124- domains are used, this should be125- ``None``.135+``APPLICATION_ROOT`` The path value used for the session136+ cookie if ``SESSION_COOKIE_PATH`` isn't137+ set. If it's also ``None`` ``'/'`` is used.138+ Note that to actually serve your Flask139+ app under a subpath you need to tell140+ your WSGI container the ``SCRIPT_NAME``141+ WSGI environment variable.142 ``MAX_CONTENT_LENGTH`` If set to a value in bytes, Flask will143 reject incoming requests with a144 content length greater than this by145 returning a 413 status code.46 unmodified lines192 caches. You can override the default193 behavior by changing this variable.194 This is not recommended but might give195 you a performance improvement on the180- cost of cachability.181-``JSONIFY_PRETTYPRINT_REGULAR`` If this is set to ``True`` (the default)182- jsonify responses will be pretty printed183- if they are not requested by an184- XMLHttpRequest object (controlled by185- the ``X-Requested-With`` header)196+ cost of cacheability.197+``JSONIFY_PRETTYPRINT_REGULAR`` If this is set to ``True`` or the Flask app198+ is running in debug mode, jsonify responses199+ will be pretty printed.200 ``JSONIFY_MIMETYPE`` MIME type used for jsonify responses.201 ``TEMPLATES_AUTO_RELOAD`` Whether to check for modifications of202 the template source and reload it203 automatically. By default the value is71 unmodified lines275 app.config.from_envvar('YOURAPPLICATION_SETTINGS')276 277 This first loads the configuration from the278 `yourapplication.default_settings` module and then overrides the values265-with the contents of the file the :envvar:``YOURAPPLICATION_SETTINGS``279+with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS`280 environment variable points to. This environment variable can be set on281 Linux or OS X with the export command in the shell before starting the282 server::283 196 unmodified linesmodified:docs/errorhandling.rst+8 added-7 removed
32 unmodified lines33 34 Sending error mails, even if just for critical ones, can become35 overwhelming if enough users are hitting the error and log files are36 typically never looked at. This is why we recommend using `Sentry37-<http://www.getsentry.com/>`_ for dealing with application errors. It's37+<https://www.getsentry.com/>`_ for dealing with application errors. It's38 available as an Open Source project `on GitHub39 <https://github.com/getsentry/sentry>`__ and is also available as a `hosted version40 <https://getsentry.com/signup/>`_ which you can try for free. Sentry41 aggregates duplicate errors, captures the full stack trace and local8 unmodified lines50 51 from raven.contrib.flask import Sentry52 sentry = Sentry(app, dsn='YOUR_DSN_HERE')53 54-Of if you are using factories you can also init it later::54+Or if you are using factories you can also init it later::55 56 from raven.contrib.flask import Sentry57 sentry = Sentry(dsn='YOUR_DSN_HERE')58 17 unmodified lines76 You might want to show custom error pages to the user when an error occurs.77 This can be done by registering error handlers.78 79 Error handlers are normal :ref:`views` but instead of being registered for80-routes they are registered for exceptions that are rised while trying to80+routes, they are registered for exceptions that are raised while trying to81 do something else.82 83 Registering84 ```````````3 unmodified lines88 89 @app.errorhandler(werkzeug.exceptions.BadRequest)90 def handle_bad_request(e):91 return 'bad request!'92- 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 that118 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 219-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 +------------------+----------------------------------------------------+279-| ``%(asctime)s`` | Human-readable time when the LogRecord` was |280-| | 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+1 added-9 removed
27 unmodified lines28 "Flask" somewhere in that name and that you check the capitalization.29 This is how users can then register dependencies to your extension in30 their :file:`setup.py` files.31 32-Flask sets up a redirect package called :data:`flask.ext` where users33-should import the extensions from. If you for instance have a package34-called ``flask_something`` users would import it as35-``flask.ext.something``. This is done to transition from the old36-namespace packages. See :ref:`ext-import-transition` for more details.37-32 But what do extensions look like themselves? An extension has to ensure33 that it works with multiple Flask application instances at once. This is34 a requirement because many people will use patterns like the35 :ref:`app-factories` pattern to create their application as needed to aid350 unmodified lines386 10. An extension currently has to support Python 2.6 as well as387 Python 2.7388 389 396-.. _ext-import-transition:397-390 Extension Import Transition391 ---------------------------392 393 In early versions of Flask we recommended using namespace packages for Flask10 unmodified lines404 schema. The ``flask.ext.foo`` compatibility alias is still in Flask 0.11 but is405 now deprecated -- you should use ``flask_foo``.406 407 416-.. _OAuth extension: http://pythonhosted.org/Flask-OAuth/408+.. _OAuth extension: https://pythonhosted.org/Flask-OAuth/409 .. _mailinglist: http://flask.pocoo.org/mailinglist/410 .. _IRC channel: http://flask.pocoo.org/community/irc/modified:docs/installation.rst+115 added-116 removed
1 unmodified line2 3 Installation4 ============5 6-Flask depends on some external libraries, like `Werkzeug7-<http://werkzeug.pocoo.org/>`_ and `Jinja2 <http://jinja.pocoo.org/>`_.8-Werkzeug is a toolkit for WSGI, the standard Python interface between web9-applications and a variety of servers for both development and deployment.10-Jinja2 renders templates.6+Python Version7+--------------8 12-So how do you get all that on your computer quickly? There are many ways you13-could do that, but the most kick-ass method is virtualenv, so let's have a look14-at that first.9+We recommend using the latest version of Python 3. Flask supports Python 3.310+and newer, Python 2.6 and newer, and PyPy.11 16-You will need Python 2.6 or newer to get started, so be sure to have an17-up-to-date Python 2.x installation. For using Flask with Python 3 have a18-look at :ref:`python3-support`.12+Dependencies13+------------14 20-.. _virtualenv:15+These distributions will be installed automatically when installing Flask.16 22-virtualenv23-----------17+* `Werkzeug`_ implements WSGI, the standard Python interface between18+ applications and servers.19+* `Jinja`_ is a template language that renders the pages your application20+ serves.21+* `MarkupSafe`_ comes with Jinja. It escapes untrusted input when rendering22+ templates to avoid injection attacks.23+* `ItsDangerous`_ securely signs data to ensure its integrity. This is used24+ to protect Flask's session cookie.25+* `Click`_ is a framework for writing command line applications. It provides26+ the ``flask`` command and allows adding custom management commands.27 25-Virtualenv is probably what you want to use during development, and if you have26-shell access to your production machines, you'll probably want to use it there,27-too.28+.. _Werkzeug: http://werkzeug.pocoo.org/29+.. _Jinja: http://jinja.pocoo.org/30+.. _MarkupSafe: https://pypi.python.org/pypi/MarkupSafe31+.. _ItsDangerous: https://pythonhosted.org/itsdangerous/32+.. _Click: http://click.pocoo.org/33 29-What problem does virtualenv solve? If you like Python as much as I do,30-chances are you want to use it for other projects besides Flask-based web31-applications. But the more projects you have, the more likely it is that you32-will be working with different versions of Python itself, or at least different33-versions of Python libraries. Let's face it: quite often libraries break34-backwards compatibility, and it's unlikely that any serious application will35-have zero dependencies. So what do you do if two or more of your projects have36-conflicting dependencies?34+Optional dependencies35+~~~~~~~~~~~~~~~~~~~~~36 38-Virtualenv to the rescue! Virtualenv enables multiple side-by-side39-installations of Python, one for each project. It doesn't actually install40-separate copies of Python, but it does provide a clever way to keep different41-project environments isolated. Let's see how virtualenv works.37+These distributions will not be installed automatically. Flask will detect and38+use them if you install them.39 43-If you are on Mac OS X or Linux, chances are that one of the following two44-commands will work for you::40+* `Blinker`_ provides support for :ref:`signals`.41+* `SimpleJSON`_ is a fast JSON implementation that is compatible with42+ Python's ``json`` module. It is preferred for JSON operations if it is43+ installed.44 46- $ sudo easy_install virtualenv45+.. _Blinker: https://pythonhosted.org/blinker/46+.. _SimpleJSON: https://simplejson.readthedocs.io/47 48-or even better::48+Virtual environments49+--------------------50 50- $ sudo pip install virtualenv51+Use a virtual environment to manage the dependencies for your project, both in52+development and in production.53 52-One of these will probably install virtualenv on your system. Maybe it's even53-in your package manager. If you use Ubuntu, try::54+What problem does a virtual environment solve? The more Python projects you55+have, the more likely it is that you need to work with different versions of56+Python libraries, or even Python itself. Newer versions of libraries for one57+project can break compatibility in another project.58 55- $ sudo apt-get install python-virtualenv59+Virtual environments are independent groups of Python libraries, one for each60+project. Packages installed for one project will not affect other projects or61+the operating system's packages.62 57-If you are on Windows and don't have the :command:`easy_install` command, you must58-install it first. Check the :ref:`windows-easy-install` section for more59-information about how to do that. Once you have it installed, run the same60-commands as above, but without the :command:`sudo` prefix.63+Python 3 comes bundled with the :mod:`venv` module to create virtual64+environments. If you're using a modern version of Python, you can continue on65+to the next section.66 62-Once you have virtualenv installed, just fire up a shell and create63-your own environment. I usually create a project folder and a :file:`venv`64-folder within::67+If you're using Python 2, see :ref:`install-install-virtualenv` first.68 66- $ mkdir myproject67- $ cd myproject68- $ virtualenv venv69- New python executable in venv/bin/python70- Installing setuptools, pip............done.69+.. _install-create-env:70 72-Now, whenever you want to work on a project, you only have to activate the73-corresponding environment. On OS X and Linux, do the following::71+Create an environment72+~~~~~~~~~~~~~~~~~~~~~73 75- $ . venv/bin/activate74+Create a project folder and a :file:`venv` folder within:75 77-If you are a Windows user, the following command is for you::76+.. code-block:: sh77 79- $ venv\scripts\activate78+ mkdir myproject79+ cd myproject80+ python3 -m venv venv81 81-Either way, you should now be using your virtualenv (notice how the prompt of82-your shell has changed to show the active environment).82+On Windows:83 84-And if you want to go back to the real world, use the following command::84+.. code-block:: bat85 86- $ deactivate86+ py -3 -m venv venv87 88-After doing this, the prompt of your shell should be as familiar as before.88+If you needed to install virtualenv because you are on an older version of89+Python, use the following command instead:90 90-Now, let's move on. Enter the following command to get Flask activated in your91-virtualenv::91+.. code-block:: sh92 93- $ pip install Flask93+ virtualenv venv94 95-A few seconds later and you are good to go.95+On Windows:96 97+.. code-block:: bat98 98-System-Wide Installation99-------------------------99+ \Python27\Scripts\virtualenv.exe venv100 101-This is possible as well, though I do not recommend it. Just run102-:command:`pip` with root privileges::101+Activate the environment102+~~~~~~~~~~~~~~~~~~~~~~~~103 104- $ sudo pip install Flask104+Before you work on your project, activate the corresponding environment:105 106-(On Windows systems, run it in a command-prompt window with administrator107-privileges, and leave out :command:`sudo`.)106+.. code-block:: sh107 108+ . venv/bin/activate109 110-Living on the Edge111-------------------110+On Windows:111 113-If you want to work with the latest version of Flask, there are two ways: you114-can either let :command:`pip` pull in the development version, or you can tell115-it to operate on a git checkout. Either way, virtualenv is recommended.112+.. code-block:: bat113 117-Get the git checkout in a new virtualenv and run in development mode::114+ venv\Scripts\activate115 119- $ git clone http://github.com/pallets/flask.git120- Initialized empty Git repository in ~/dev/flask/.git/121- $ cd flask122- $ virtualenv venv123- New python executable in venv/bin/python124- Installing setuptools, pip............done.125- $ . venv/bin/activate126- $ python setup.py develop127- ...128- Finished processing dependencies for Flask116+Your shell prompt will change to show the name of the activated environment.117 130-This will pull in the dependencies and activate the git head as the current131-version inside the virtualenv. Then all you have to do is run ``git pull132-origin`` to update to the latest version.118+Install Flask119+-------------120 121+Within the activated environment, use the following command to install Flask:122 135-.. _windows-easy-install:123+.. code-block:: sh124 137-`pip` and `setuptools` on Windows138----------------------------------125+ pip install Flask126 140-Sometimes getting the standard "Python packaging tools" like *pip*, *setuptools*141-and *virtualenv* can be a little trickier, but nothing very hard. The two crucial142-packages you will need are setuptools and pip - these will let you install143-anything else (like virtualenv). Fortunately there are two "bootstrap scripts"144-you can run to install either.127+Living on the edge128+~~~~~~~~~~~~~~~~~~129 146-If you don't currently have either, then `get-pip.py` will install both for you147-(you won't need to run ez_setup.py).130+If you want to work with the latest Flask code before it's released, install or131+update the code from the master branch:132 149-`get-pip.py`_133+.. code-block:: sh134 151-To install the latest setuptools, you can use its bootstrap file:135+ pip install -U https://github.com/pallets/flask/archive/master.tar.gz136 153-`ez_setup.py`_137+.. _install-install-virtualenv:138 155-Either should be double-clickable once you download them. If you already have pip,156-you can upgrade them by running::139+Install virtualenv140+------------------141 158- > pip install --upgrade pip setuptools142+If you are using Python 2, the venv module is not available. Instead,143+install `virtualenv`_.144 160-Most often, once you pull up a command prompt you want to be able to type :command:`pip`161-and :command:`python` which will run those things, but this might not automatically happen162-on Windows, because it doesn't know where those executables are (give either a try!).145+On Linux, virtualenv is provided by your package manager:146 164-To fix this, you should be able to navigate to your Python install directory165-(e.g :file:`C:\Python27`), then go to :file:`Tools`, then :file:`Scripts`, then find the166-:file:`win_add2path.py` file and run that. Open a **new** Command Prompt and167-check that you can now just type :command:`python` to bring up the interpreter.147+.. code-block:: sh148 169-Finally, to install `virtualenv`_, you can simply run::149+ # Debian, Ubuntu150+ sudo apt-get install python-virtualenv151 171- > pip install virtualenv152+ # CentOS, Fedora153+ sudo yum install python-virtualenv154 173-Then you can be off on your way following the installation instructions above.155+ # Arch156+ sudo pacman -S python-virtualenv157 158+If you are on Mac OS X or Windows, download `get-pip.py`_, then:159+160+.. code-block:: sh161+162+ sudo python2 Downloads/get-pip.py163+ sudo python2 -m pip install virtualenv164+165+On Windows, as an administrator:166+167+.. code-block:: bat168+169+ \Python27\python.exe Downloads\get-pip.py170+ \Python27\python.exe -m pip install virtualenv171+172+Now you can continue to :ref:`install-create-env`.173+174+.. _virtualenv: https://virtualenv.pypa.io/175 .. _get-pip.py: https://bootstrap.pypa.io/get-pip.py176-.. _ez_setup.py: https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.pymodified:docs/quickstart.rst+142 added-194 removed
24 unmodified lines25 1. First we imported the :class:`~flask.Flask` class. An instance of this26 class will be our WSGI application.27 2. Next we create an instance of this class. The first argument is the name of28 the application's module or package. If you are using a single module (as29- in this example), you should use `__name__` because depending on if it's29+ in this example), you should use ``__name__`` because depending on if it's30 started as application or imported as module the name will be different31 (``'__main__'`` versus the actual import name). This is needed so that32 Flask knows where to look for templates, static files, and so on. For more33 information have a look at the :class:`~flask.Flask` documentation.7 unmodified lines41 your application :file:`flask.py` because this would conflict with Flask42 itself.43 44 To run the application you can either use the :command:`flask` command or45-python's :option:`-m` switch with Flask. Before you can do that you need45+python's ``-m`` switch with Flask. Before you can do that you need46 to tell your terminal the application to work with by exporting the47-`FLASK_APP` environment variable::47+``FLASK_APP`` environment variable::48 49 $ export FLASK_APP=hello.py50 $ flask run51 * Running on http://127.0.0.1:5000/52 53-If you are on Windows you need to use `set` instead of `export`.53+If you are on Windows you need to use ``set`` instead of ``export``.54 55-Alternatively you can use `python -m flask`::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/25 unmodified lines85 86 What to do if the Server does not Start87 ---------------------------------------88 89-In case the ``python -m flask`` fails or :command:`flask` does not exist,89+In case the :command:`python -m flask` fails or :command:`flask` does not exist,90 there are multiple reasons this might be the case. First of all you need91 to look at the error message.92 93 Old Version of Flask94 ````````````````````95 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 ``python -m flask``. In that case you have two options:98+neither did :command:`python -m flask`. In that case you have two options:99 either upgrade to newer Flask versions or have a look at the :ref:`server`100 docs to see the alternative method for running a server.101 102 Invalid Import Name103 ```````````````````104 105-The :option:`-a` argument to :command:`flask` is the name of the module to106-import. In case that module is incorrectly named you will get an import107-error upon start (or if debug is enabled when you navigate to the108-application). It will tell you what it tried to import and why it failed.105+The ``FLASK_APP`` environment variable is the name of the module to import at106+:command:`flask run`. In case that module is incorrectly named you will get an107+import error upon start (or if debug is enabled when you navigate to the108+application). It will tell you what it tried to import and why it failed.109 110 The most common reason is a typo or because you did not actually create an111 ``app`` object.112 9 unmodified lines122 That is not very nice and Flask can do better. If you enable debug123 support the server will reload itself on code changes, and it will also124 provide you with a helpful debugger if things go wrong.125 126-To enable debug mode you can export the `FLASK_DEBUG` environment variable126+To enable debug mode you can export the ``FLASK_DEBUG`` environment variable127 before running the server::128 129 $ export FLASK_DEBUG=1130 $ flask run131 132-(On Windows you need to use `set` instead of `export`).132+(On Windows you need to use ``set`` instead of ``export``).133 134 This does the following things:135 136 1. it activates the debugger15 unmodified lines152 :align: center153 :class: screenshot154 :alt: screenshot of debugger in action155 156+More information on using the debugger can be found in the `Werkzeug 157+documentation`_.158+159+.. _Werkzeug documentation: http://werkzeug.pocoo.org/docs/debug/#using-the-debugger160+161 Have another debugger in mind? See :ref:`working-with-debuggers`.162 163 164 Routing165 -------166 162-Modern web applications have beautiful URLs. This helps people remember163-the URLs, which is especially handy for applications that are used from164-mobile devices with slower network connections. If the user can directly165-go to the desired page without having to hit the index page it is more166-likely they will like the page and come back next time.167+Modern web applications use meaningful URLs to help users. Users are more168+likely to like a page and come back if the page uses a meaningful URL they can169+remember and use to directly visit a page.170 168-As you have seen above, the :meth:`~flask.Flask.route` decorator is used to169-bind a function to a URL. Here are some basic examples::171+Use the :meth:`~flask.Flask.route` decorator to bind a function to a URL. ::172 173 @app.route('/')174 def index():175 return 'Index Page'1 unmodified line177 @app.route('/hello')178 def hello():179 return 'Hello, World'180 179-But there is more to it! You can make certain parts of the URL dynamic and180-attach multiple rules to a function.181+You can do more! You can make parts of the URL dynamic and attach multiple182+rules to a function.183 184 Variable Rules185 ``````````````186 185-To add variable parts to a URL you can mark these special sections as186-``<variable_name>``. Such a part is then passed as a keyword argument to your187-function. Optionally a converter can be used by specifying a rule with188-``<converter:variable_name>``. Here are some nice examples::187+You can add variable sections to a URL by marking sections with188+``<variable_name>``. Your function then receives the ``<variable_name>``189+as a keyword argument. Optionally, you can use a converter to specify the type190+of the argument like ``<converter:variable_name>``. ::191 192 @app.route('/user/<username>')193 def show_user_profile(username):194 # show the user profile for that user3 unmodified lines198 def show_post(post_id):199 # show the post with the given id, the id is an integer200 return 'Post %d' % post_id201 200-The following converters exist:202+ @app.route('/path/<path:subpath>')203+ def show_subpath(subpath):204+ # show the subpath after /path/205+ return 'Subpath %s' % subpath206 202-=========== ===============================================203-`string` accepts any text without a slash (the default)204-`int` accepts integers205-`float` like `int` but for floating point values206-`path` like the default but also accepts slashes207-`any` matches one of the items provided208-`uuid` accepts UUID strings209-=========== ===============================================207+Converter types:208 211-.. admonition:: Unique URLs / Redirection Behavior209+========== ==========================================210+``string`` (default) accepts any text without a slash211+``int`` accepts positive integers212+``float`` accepts positive floating point values213+``path`` like ``string`` but also accepts slashes214+``uuid`` accepts UUID strings215+========== ==========================================216 213- Flask's URL rules are based on Werkzeug's routing module. The idea214- behind that module is to ensure beautiful and unique URLs based on215- precedents laid down by Apache and earlier HTTP servers.217+Unique URLs / Redirection Behavior218+``````````````````````````````````219 217- Take these two rules::220+Take these two rules::221 219- @app.route('/projects/')220- def projects():221- return 'The project page'222+ @app.route('/projects/')223+ def projects():224+ return 'The project page'225 223- @app.route('/about')224- def about():225- return 'The about page'226+ @app.route('/about')227+ def about():228+ return 'The about page'229 227- Though they look rather similar, they differ in their use of the trailing228- slash in the URL *definition*. In the first case, the canonical URL for the229- `projects` endpoint has a trailing slash. In that sense, it is similar to230- a folder on a filesystem. Accessing it without a trailing slash will cause231- Flask to redirect to the canonical URL with the trailing slash.230+Though they look similar, they differ in their use of the trailing slash in231+the URL. In the first case, the canonical URL for the ``projects`` endpoint232+uses a trailing slash. It's similar to a folder in a file system; if you233+access the URL without a trailing slash, Flask redirects you to the234+canonical URL with the trailing slash.235 233- In the second case, however, the URL is defined without a trailing slash,234- rather like the pathname of a file on UNIX-like systems. Accessing the URL235- with a trailing slash will produce a 404 "Not Found" error.236+In the second case, however, the URL definition lacks a trailing slash,237+like the pathname of a file on UNIX-like systems. Accessing the URL with a238+trailing slash produces a 404 “Not Found” error.239 237- This behavior allows relative URLs to continue working even if the trailing238- slash is omitted, consistent with how Apache and other servers work. Also,239- the URLs will stay unique, which helps search engines avoid indexing the240- same page twice.240+This behavior allows relative URLs to continue working even if the trailing241+slash is omitted, consistent with how Apache and other servers work. Also,242+the URLs will stay unique, which helps search engines avoid indexing the243+same page twice.244 242-245 .. _url-building:246 247 URL Building248 ````````````249 248-If it can match URLs, can Flask also generate them? Of course it can. To249-build a URL to a specific function you can use the :func:`~flask.url_for`250-function. It accepts the name of the function as first argument and a number251-of keyword arguments, each corresponding to the variable part of the URL rule.252-Unknown variable parts are appended to the URL as query parameters. Here are253-some examples:250+To build a URL to a specific function, use the :func:`~flask.url_for` function.251+It accepts the name of the function as its first argument and any number of252+keyword arguments, each corresponding to a variable part of the URL rule.253+Unknown variable parts are appended to the URL as query parameters.254 255->>> from flask import Flask, url_for256->>> app = Flask(__name__)257->>> @app.route('/')258-... def index(): pass259-...260->>> @app.route('/login')261-... def login(): pass262-...263->>> @app.route('/user/<username>')264-... def profile(username): pass265-...266->>> with app.test_request_context():267-... print url_for('index')268-... print url_for('login')269-... print url_for('login', next='/')270-... print url_for('profile', username='John Doe')271-...272-/273-/login274-/login?next=/275-/user/John%20Doe276-277-(This also uses the :meth:`~flask.Flask.test_request_context` method, explained278-below. It tells Flask to behave as though it is handling a request, even279-though we are interacting with it through a Python shell. Have a look at the280-explanation below. :ref:`context-locals`).281-255 Why would you want to build URLs using the URL reversing function256 :func:`~flask.url_for` instead of hard-coding them into your templates?284-There are three good reasons for this:257 286-1. Reversing is often more descriptive than hard-coding the URLs. More287- importantly, it allows you to change URLs in one go, without having to288- remember to change URLs all over the place.289-2. URL building will handle escaping of special characters and Unicode290- data transparently for you, so you don't have to deal with them.291-3. If your application is placed outside the URL root (say, in292- ``/myapplication`` instead of ``/``), :func:`~flask.url_for` will handle293- that properly for you.258+1. Reversing is often more descriptive than hard-coding the URLs.259+2. You can change your URLs in one go instead of needing to remember to260+ manually change hard-coded URLs.261+3. URL building handles escaping of special characters and Unicode data262+ transparently.263+4. If your application is placed outside the URL root, for example, in264+ ``/myapplication`` instead of ``/``, :func:`~flask.url_for` properly265+ handles that for you.266 267+For example, here we use the :meth:`~flask.Flask.test_request_context` method268+to try out :func:`~flask.url_for`. :meth:`~flask.Flask.test_request_context`269+tells Flask to behave as though it's handling a request even while we use a270+Python shell. See :ref:`context-locals`. ::271 272+ from flask import Flask, url_for273+274+ app = Flask(__name__)275+276+ @app.route('/')277+ def index():278+ return 'index'279+280+ @app.route('/login')281+ def login():282+ return 'login'283+284+ @app.route('/user/<username>')285+ def profile(username):286+ return '{}'s profile'.format(username)287+288+ with app.test_request_context():289+ print(url_for('index'))290+ print(url_for('login'))291+ print(url_for('login', next='/'))292+ print(url_for('profile', username='John Doe'))293+294+ /295+ /login296+ /login?next=/297+ /user/John%20Doe298+299 HTTP Methods300 ````````````301 299-HTTP (the protocol web applications are speaking) knows different methods for300-accessing URLs. By default, a route only answers to ``GET`` requests, but that301-can be changed by providing the `methods` argument to the302-:meth:`~flask.Flask.route` decorator. Here are some examples::302+Web applications use different HTTP methods when accessing URLs. You should303+familiarize yourself with the HTTP methods as you work with Flask. By default,304+a route only answers to ``GET`` requests. You can use the ``methods`` argument305+of the :meth:`~flask.Flask.route` decorator to handle different HTTP methods.306+::307 304- from flask import request305-308 @app.route('/login', methods=['GET', 'POST'])309 def login():310 if request.method == 'POST':311 do_the_login()312 else:313 show_the_login_form()314 313-If ``GET`` is present, ``HEAD`` will be added automatically for you. You314-don't have to deal with that. It will also make sure that ``HEAD`` requests315-are handled as the `HTTP RFC`_ (the document describing the HTTP316-protocol) demands, so you can completely ignore that part of the HTTP317-specification. Likewise, as of Flask 0.6, ``OPTIONS`` is implemented for you318-automatically as well.315+If ``GET`` is present, Flask automatically adds support for the ``HEAD`` method316+and handles ``HEAD`` requests according to the the `HTTP RFC`_. Likewise,317+``OPTIONS`` is automatically implemented for you.318 320-You have no idea what an HTTP method is? Worry not, here is a quick321-introduction to HTTP methods and why they matter:319+.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt320 323-The HTTP method (also often called "the verb") tells the server what the324-client wants to *do* with the requested page. The following methods are325-very common:326-327-``GET``328- The browser tells the server to just *get* the information stored on329- that page and send it. This is probably the most common method.330-331-``HEAD``332- The browser tells the server to get the information, but it is only333- interested in the *headers*, not the content of the page. An334- application is supposed to handle that as if a ``GET`` request was335- received but to not deliver the actual content. In Flask you don't336- have to deal with that at all, the underlying Werkzeug library handles337- that for you.338-339-``POST``340- The browser tells the server that it wants to *post* some new341- information to that URL and that the server must ensure the data is342- stored and only stored once. This is how HTML forms usually343- transmit data to the server.344-345-``PUT``346- Similar to ``POST`` but the server might trigger the store procedure347- multiple times by overwriting the old values more than once. Now you348- might be asking why this is useful, but there are some good reasons349- to do it this way. Consider that the connection is lost during350- transmission: in this situation a system between the browser and the351- server might receive the request safely a second time without breaking352- things. With ``POST`` that would not be possible because it must only353- be triggered once.354-355-``DELETE``356- Remove the information at the given location.357-358-``OPTIONS``359- Provides a quick way for a client to figure out which methods are360- supported by this URL. Starting with Flask 0.6, this is implemented361- for you automatically.362-363-Now the interesting part is that in HTML4 and XHTML1, the only methods a364-form can submit to the server are ``GET`` and ``POST``. But with JavaScript365-and future HTML standards you can use the other methods as well. Furthermore366-HTTP has become quite popular lately and browsers are no longer the only367-clients that are using HTTP. For instance, many revision control systems368-use it.369-370-.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt371-321 Static Files322 ------------323 324 Dynamic web applications also need static files. That's usually where69 unmodified lines394 know how that works, head over to the :ref:`template-inheritance` pattern395 documentation. Basically template inheritance makes it possible to keep396 certain elements on each page (like header, navigation and footer).397 449-Automatic escaping is enabled, so if `name` contains HTML it will be escaped398+Automatic escaping is enabled, so if ``name`` contains HTML it will be escaped399 automatically. If you can trust a variable and you know that it will be400 safe HTML (for example because it came from a module that converts wiki401 markup to HTML) you can mark it as safe by using the402 :class:`~jinja2.Markup` class or by using the ``|safe`` filter in the403 template. Head over to the Jinja 2 documentation for more examples.404 456-Here is a basic introduction to how the :class:`~jinja2.Markup` class works:405+Here is a basic introduction to how the :class:`~jinja2.Markup` class works::406 458->>> from flask import Markup459->>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'460-Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')461->>> Markup.escape('<blink>hacker</blink>')462-Markup(u'<blink>hacker</blink>')463->>> Markup('<em>Marked up</em> » HTML').striptags()464-u'Marked up \xbb HTML'407+ >>> from flask import Markup408+ >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'409+ Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')410+ >>> Markup.escape('<blink>hacker</blink>')411+ Markup(u'<blink>hacker</blink>')412+ >>> Markup('<em>Marked up</em> » HTML').striptags()413+ u'Marked up \xbb HTML'414 415 .. versionchanged:: 0.5416 417 Autoescaping is no longer enabled for all templates. The following68 unmodified lines486 The Request Object487 ``````````````````488 489 The request object is documented in the API section and we will not cover541-it here in detail (see :class:`~flask.request`). Here is a broad overview of490+it here in detail (see :class:`~flask.Request`). Here is a broad overview of491 some of the most common operations. First of all you have to import it from543-the `flask` module::492+the ``flask`` module::493 494 from flask import request495 496 The current request method is available by using the548-:attr:`~flask.request.method` attribute. To access form data (data497+:attr:`~flask.Request.method` attribute. To access form data (data498 transmitted in a ``POST`` or ``PUT`` request) you can use the550-:attr:`~flask.request.form` attribute. Here is a full example of the two499+:attr:`~flask.Request.form` attribute. Here is a full example of the two500 attributes mentioned above::501 502 @app.route('/login', methods=['POST', 'GET'])503 def login():7 unmodified lines511 # the code below is executed if the request method512 # was GET or the credentials were invalid513 return render_template('login.html', error=error)514 566-What happens if the key does not exist in the `form` attribute? In that515+What happens if the key does not exist in the ``form`` attribute? In that516 case a special :exc:`KeyError` is raised. You can catch it like a517 standard :exc:`KeyError` but if you don't do that, a HTTP 400 Bad Request518 error page is shown instead. So for many situations you don't have to519 deal with that problem.520 521 To access parameters submitted in the URL (``?key=value``) you can use the573-:attr:`~flask.request.args` attribute::522+:attr:`~flask.Request.args` attribute::523 524 searchword = request.args.get('key', '')525 526 We recommend accessing URL parameters with `get` or by catching the527 :exc:`KeyError` because users might change the URL and presenting them a 400528 bad request page in that case is not user friendly.529 530 For a full list of methods and attributes of the request object, head over582-to the :class:`~flask.request` documentation.531+to the :class:`~flask.Request` documentation.532 533 534 File Uploads535 ````````````137 unmodified lines673 default parameters.674 3. If a tuple is returned the items in the tuple can provide extra675 information. Such tuples have to be in the form ``(response, status,676 headers)`` or ``(response, headers)`` where at least one item has728- to be in the tuple. The `status` value will override the status code729- and `headers` can be a list or dictionary of additional header values.677+ to be in the tuple. The ``status`` value will override the status code678+ and ``headers`` can be a list or dictionary of additional header values.679 4. If none of that works, Flask will assume the return value is a680 valid WSGI application and convert that into a response object.681 682 If you want to get hold of the resulting response object inside the view683 you can use the :func:`~flask.make_response` function.684 736-Imagine you have a view like this:685+Imagine you have a view like this::686 738-.. sourcecode:: python739-687 @app.errorhandler(404)688 def not_found(error):689 return render_template('error.html'), 404690 691 You just need to wrap the return expression with692 :func:`~flask.make_response` and get the response object to modify it, then746-return it:693+return it::694 748-.. sourcecode:: python749-695 @app.errorhandler(404)696 def not_found(error):697 resp = make_response(render_template('error.html'), 404)698 resp.headers['X-Something'] = 'A value'29 unmodified lines728 if request.method == 'POST':729 session['username'] = request.form['username']730 return redirect(url_for('index'))731 return '''787- <form action="" method="post">732+ <form method="post">733 <p><input type=text name=username>734 <p><input type=submit value=Login>735 </form>736 '''14 unmodified lines751 752 The problem with random is that it's hard to judge what is truly random. And753 a secret key should be as random as possible. Your operating system754 has ways to generate pretty random stuff based on a cryptographic810- random generator which can be used to get such a key:755+ random generator which can be used to get such a key::756 812- >>> import os813- >>> os.urandom(24)814- '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'757+ >>> import os758+ >>> os.urandom(24)759+ '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'760 816- Just take that thing and copy/paste it into your code and you're done.761+ Just take that thing and copy/paste it into your code and you're done.762 763 A note on cookie-based sessions: Flask will take the values you put into the764 session object and serialize them into a cookie. If you are finding some765 values do not persist across requests, cookies are indeed enabled, and you are766 not getting a clear error message, check the size of the cookie in your page767 responses compared to the size supported by web browsers.768 769+Besides the default client-side based sessions, if you want to handle770+sessions on the server-side instead, there are several771+Flask extensions that support this.772 773 Message Flashing774 ----------------775 67 unmodified linesmodified:docs/reqcontext.rst+8 added-7 removed
117 unmodified lines118 unhandled exception down the road or if a before-request handler was119 not executed yet or at all (for example in test environments sometimes120 you might want to not execute before-request callbacks).121 122-Now what happens on errors? In production mode if an exception is not123-caught, the 500 internal server handler is called. In development mode124-however the exception is not further processed and bubbles up to the WSGI122+Now what happens on errors? If you are not in debug mode and an exception is not 123+caught, the 500 internal server handler is called. In debug mode 124+however the exception is not further processed and bubbles up to the WSGI 125 server. That way things like the interactive debugger can provide helpful126 debug information.127 128 An important change in 0.7 is that the internal server error is now no84 unmodified lines213 214 Starting with Flask 0.7 you have finer control over that behavior by215 setting the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable. By216 default it's linked to the setting of ``DEBUG``. If the application is in217-debug mode the context is preserved, in production mode it's not.217+debug mode the context is preserved. If debug mode is set to off, the context218+is not preserved.219 219-Do not force activate ``PRESERVE_CONTEXT_ON_EXCEPTION`` in production mode220-as it will cause your application to leak memory on exceptions. However220+Do not force activate ``PRESERVE_CONTEXT_ON_EXCEPTION`` if debug mode is set to off221+as it will cause your application to leak memory on exceptions. However,222 it can be useful during development to get the same error preserving222-behavior as in development mode when attempting to debug an error that223+behavior as debug mode when attempting to debug an error that224 only occurs under production settings.modified:docs/security.rst+1 added-1 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 be84 unmodified linesmodified:docs/styleguide.rst+1 added-1 removed
165 unmodified lines166 is on its own line.167 """168 169 Module header:170- The module header consists of an utf-8 encoding declaration (if non170+ The module header consists of a utf-8 encoding declaration (if non171 ASCII letters are used, but it is recommended all the time) and a172 standard docstring::173 174 # -*- coding: utf-8 -*-26 unmodified linesmodified:docs/testing.rst+13 added-11 removed
31 unmodified lines32 In order to test the application, we add a second module33 (:file:`flaskr_tests.py`) and create a unittest skeleton there::34 35 import os36- import flaskr36+ from flaskr import flaskr37 import unittest38 import tempfile39 40 class FlaskrTestCase(unittest.TestCase):41 42 def setUp(self):43 self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()44- flaskr.app.config['TESTING'] = True44+ flaskr.app.testing = True45 self.app = flaskr.app.test_client()46 with flaskr.app.app_context():47 flaskr.init_db()48 48 unmodified lines97 class FlaskrTestCase(unittest.TestCase):98 99 def setUp(self):100 self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()101+ flaskr.app.testing = True102 self.app = flaskr.app.test_client()103+ with flaskr.app.app_context():102- flaskr.init_db()104+ flaskr.init_db()105 106 def tearDown(self):107 os.close(self.db_fd)108 os.unlink(flaskr.app.config['DATABASE'])44 unmodified lines153 invalid credentials. Add this new test to the class::154 155 def test_login_logout(self):156 rv = self.login('admin', 'default')155- assert 'You were logged in' in rv.data157+ assert b'You were logged in' in rv.data158 rv = self.logout()157- assert 'You were logged out' in rv.data159+ assert b'You were logged out' in rv.data160 rv = self.login('adminx', 'default')159- assert 'Invalid username' in rv.data161+ assert b'Invalid username' in rv.data162 rv = self.login('admin', 'defaultx')161- assert 'Invalid password' in rv.data163+ assert b'Invalid password' in rv.data164 165 Test Adding Messages166 --------------------167 5 unmodified lines173 rv = self.app.post('/add', data=dict(174 title='<Hello>',175 text='<strong>HTML</strong> allowed here'176 ), follow_redirects=True)175- assert 'No entries here so far' not in rv.data176- assert '<Hello>' in rv.data177- assert '<strong>HTML</strong> allowed here' in rv.data177+ assert b'No entries here so far' not in rv.data178+ assert b'<Hello>' in rv.data179+ assert b'<strong>HTML</strong> allowed here' in rv.data180 181 Here we check that HTML is allowed in the text but not in the title,182 which is the intended behavior.183 25 unmodified lines209 :class:`~flask.g` and :class:`~flask.session` objects like in view210 functions. Here is a full example that demonstrates this approach::211 212 import flask211- 213+214 app = flask.Flask(__name__)215 216 with app.test_request_context('/?name=Peter'):217 assert flask.request.path == '/'140 unmodified linesmodified:docs/upgrading.rst+52 added-14 removed
12 unmodified lines13 This section of the documentation enumerates all the changes in Flask from14 release to release and how you can change your code to have a painless15 updating experience.16 17-If you want to use the :command:`easy_install` command to upgrade your Flask18-installation, make sure to pass it the :option:`-U` parameter::17+Use the :command:`pip` command to upgrade your existing Flask installation by18+providing the ``--upgrade`` parameter::19 20- $ easy_install -U Flask20+ $ pip install --upgrade Flask21 22-.. _upgrading-to-10:22+.. _upgrading-to-012:23 24+Version 0.1225+------------26+27+Changes to send_file28+````````````````````29+30+The ``filename`` is no longer automatically inferred from file-like objects.31+This means that the following code will no longer automatically have32+``X-Sendfile`` support, etag generation or MIME-type guessing::33+34+ response = send_file(open('/path/to/file.txt'))35+36+Any of the following is functionally equivalent::37+38+ fname = '/path/to/file.txt'39+40+ # Just pass the filepath directly41+ response = send_file(fname)42+43+ # Set the MIME-type and ETag explicitly44+ response = send_file(open(fname), mimetype='text/plain')45+ response.set_etag(...)46+47+ # Set `attachment_filename` for MIME-type guessing48+ # ETag still needs to be manually set49+ response = send_file(open(fname), attachment_filename=fname)50+ response.set_etag(...)51+52+The reason for this is that some file-like objects have an invalid or even53+misleading ``name`` attribute. Silently swallowing errors in such cases was not54+a satisfying solution.55+56+Additionally the default of falling back to ``application/octet-stream`` has57+been restricted. If Flask can't guess one or the user didn't provide one, the58+function fails if no filename information was provided.59+60+.. _upgrading-to-011:61+62 Version 0.1163 ------------64 65 0.11 is an odd release in the Flask release cycle because it was supposed1 unmodified line67 to the release we decided to push out a 0.11 release first with some68 changes removed to make the transition easier. If you have been tracking69 the master branch which was 1.0 you might see some unexpected changes.70 33-In case you did track the master branch you will notice that `flask --app`71+In case you did track the master branch you will notice that :command:`flask --app`72 is removed now. You need to use the environment variable to specify an73 application.74 75 Debugging29 unmodified lines105 106 The :func:`~flask.templating.render_template_string` function has changed to107 autoescape template variables by default. This better matches the behavior108 of :func:`~flask.templating.render_template`.71- 109+110 Extension imports111 `````````````````112 113 Extension imports of the form ``flask.ext.foo`` are deprecated, you should use28 unmodified lines142 when there is no request context yet but an application context. The old143 ``flask.Flask.request_globals_class`` attribute was renamed to144 :attr:`flask.Flask.app_ctx_globals_class`.145 108-.. _Flask-OldSessions: http://pythonhosted.org/Flask-OldSessions/146+.. _Flask-OldSessions: https://pythonhosted.org/Flask-OldSessions/147 148 Version 0.9149 -----------150 19 unmodified lines170 Version 0.8171 -----------172 173 Flask introduced a new session interface system. We also noticed that136-there was a naming collision between `flask.session` the module that174+there was a naming collision between ``flask.session`` the module that175 implements sessions and :data:`flask.session` which is the global session176 object. With that introduction we moved the implementation details for177 the session system into a new module called :mod:`flask.sessions`. If you178 used the previously undocumented session support we urge you to upgrade.18 unmodified lines197 applications with Flask. Because we want to make upgrading as easy as198 possible we tried to counter the problems arising from these changes by199 providing a script that can ease the transition.200 163-The script scans your whole application and generates an unified diff with201+The script scans your whole application and generates a unified diff with202 changes it assumes are safe to apply. However as this is an automated203 tool it won't be able to find all use cases and it might miss some. We204 internally spread a lot of deprecation warnings all over the place to make205 it easy to find pieces of code that it was unable to upgrade.30 unmodified lines236 Please note that deprecation warnings are disabled by default starting237 with Python 2.7. In order to see the deprecation warnings that might be238 emitted you have to enabled them with the :mod:`warnings` module.239 202-If you are working with windows and you lack the `patch` command line240+If you are working with windows and you lack the ``patch`` command line241 utility you can get it as part of various Unix runtime environments for242 windows including cygwin, msysgit or ming32. Also source control systems243 like svn, hg or git have builtin support for applying unified diffs as244 generated by the tool. Check the manual of your version control system108 unmodified lines353 that name but it might fail as this information could change at354 runtime.355 - Blueprints have an inverse behavior for :meth:`url_for`. Previously356 ``.foo`` told :meth:`url_for` that it should look for the endpoint319- `foo` on the application. Now it means “relative to current module”.357+ ``foo`` on the application. Now it means “relative to current module”.358 The script will inverse all calls to :meth:`url_for` automatically for359 you. It will do this in a very eager way so you might end up with360 some unnecessary leading dots in your code if you're not using361 modules.9 unmodified lines371 This means that you need to add another subfolder with the blueprint's372 name into that folder if you want :file:`blueprintname/template.html` as373 the template name.374 337-If you continue to use the `Module` object which is deprecated, Flask will375+If you continue to use the ``Module`` object which is deprecated, Flask will376 restore the previous behavior as good as possible. However we strongly377 recommend upgrading to the new blueprints as they provide a lot of useful378 improvement such as the ability to attach a blueprint multiple times,379 blueprint specific error handlers and a lot more.11 unmodified lines391 change the order.392 393 Another change that breaks backwards compatibility is that context394 processors will no longer override values passed directly to the template357-rendering function. If for example `request` is as variable passed395+rendering function. If for example ``request`` is as variable passed396 directly to the template, the default context processor will not override397 it with the current request object. This makes it easier to extend398 context processors later to inject additional variables without breaking399 existing template not expecting them.17 unmodified lines417 functionality might come back in future releases if there is demand418 for this feature. Removing support for this makes the Flask internal419 code easier to understand and fixes a couple of small issues that make420 debugging harder than necessary.383-- The `create_jinja_loader` function is gone. If you want to customize421+- The ``create_jinja_loader`` function is gone. If you want to customize422 the Jinja loader now, use the423 :meth:`~flask.Flask.create_jinja_environment` method instead.424 425 Version 0.447 unmodified linesadded:examples/flaskr/flaskr/static/style.css+18 added
1+body { font-family: sans-serif; background: #eee; }2+a, h1, h2 { color: #377BA8; }3+h1, h2 { font-family: 'Georgia', serif; margin: 0; }4+h1 { border-bottom: 2px solid #eee; }5+h2 { font-size: 1.2em; }6+7+.page { margin: 2em auto; width: 35em; border: 5px solid #ccc;8+ padding: 0.8em; background: white; }9+.entries { list-style: none; margin: 0; padding: 0; }10+.entries li { margin: 0.8em 1.2em; }11+.entries li h2 { margin-left: -1em; }12+.add-entry { font-size: 0.9em; border-bottom: 1px solid #ccc; }13+.add-entry dl { font-weight: bold; }14+.metanav { text-align: right; font-size: 0.8em; padding: 0.3em;15+ margin-bottom: 1em; background: #fafafa; }16+.flash { background: #CEE5F5; padding: 0.5em;17+ border: 1px solid #AACBE2; }18+.error { background: #F0D6D6; padding: 0.5em; }added:examples/flaskr/flaskr/templates/layout.html+17 added
1+<!doctype html>2+<title>Flaskr</title>3+<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">4+<div class="page">5+ <h1>Flaskr</h1>6+ <div class="metanav">7+ {% if not session.logged_in %}8+ <a href="{{ url_for('login') }}">log in</a>9+ {% else %}10+ <a href="{{ url_for('logout') }}">log out</a>11+ {% endif %}12+ </div>13+ {% for message in get_flashed_messages() %}14+ <div class="flash">{{ message }}</div>15+ {% endfor %}16+ {% block body %}{% endblock %}17+</div>added:examples/flaskr/flaskr/templates/login.html+14 added
1+{% extends "layout.html" %}2+{% block body %}3+ <h2>Login</h2>4+ {% if error %}<p class="error"><strong>Error:</strong> {{ error }}{% endif %}5+ <form action="{{ url_for('login') }}" method="post">6+ <dl>7+ <dt>Username:8+ <dd><input type="text" name="username">9+ <dt>Password:10+ <dd><input type="password" name="password">11+ <dd><input type="submit" value="Login">12+ </dl>13+ </form>14+{% endblock %}added:examples/flaskr/flaskr/templates/show_entries.html+21 added
1+{% extends "layout.html" %}2+{% block body %}3+ {% if session.logged_in %}4+ <form action="{{ url_for('add_entry') }}" method="post" class="add-entry">5+ <dl>6+ <dt>Title:7+ <dd><input type="text" size="30" name="title">8+ <dt>Text:9+ <dd><textarea name="text" rows="5" cols="40"></textarea>10+ <dd><input type="submit" value="Share">11+ </dl>12+ </form>13+ {% endif %}14+ <ul class="entries">15+ {% for entry in entries %}16+ <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}</li>17+ {% else %}18+ <li><em>Unbelievable. No entries here so far</em></li>19+ {% endfor %}20+ </ul>21+{% endblock %}added:examples/flaskr/flaskr/__init__.py+1 added
1+from .flaskr import appadded:examples/flaskr/flaskr/flaskr.py+110 added
1+# -*- coding: utf-8 -*-2+"""3+ Flaskr4+ ~~~~~~5+6+ A microblog example application written as Flask tutorial with7+ Flask and sqlite3.8+9+ :copyright: (c) 2015 by Armin Ronacher.10+ :license: BSD, see LICENSE for more details.11+"""12+13+import os14+from sqlite3 import dbapi2 as sqlite315+from flask import Flask, request, session, g, redirect, url_for, abort, \16+ render_template, flash17+18+19+# create our little application :)20+app = Flask(__name__)21+22+# Load default config and override config from an environment variable23+app.config.update(dict(24+ DATABASE=os.path.join(app.root_path, 'flaskr.db'),25+ DEBUG=True,26+ SECRET_KEY='development key',27+ USERNAME='admin',28+ PASSWORD='default'29+))30+app.config.from_envvar('FLASKR_SETTINGS', silent=True)31+32+33+def connect_db():34+ """Connects to the specific database."""35+ rv = sqlite3.connect(app.config['DATABASE'])36+ rv.row_factory = sqlite3.Row37+ return rv38+39+40+def init_db():41+ """Initializes the database."""42+ db = get_db()43+ with app.open_resource('schema.sql', mode='r') as f:44+ db.cursor().executescript(f.read())45+ db.commit()46+47+48+@app.cli.command('initdb')49+def initdb_command():50+ """Creates the database tables."""51+ init_db()52+ print('Initialized the database.')53+54+55+def get_db():56+ """Opens a new database connection if there is none yet for the57+ current application context.58+ """59+ if not hasattr(g, 'sqlite_db'):60+ g.sqlite_db = connect_db()61+ return g.sqlite_db62+63+64+@app.teardown_appcontext65+def close_db(error):66+ """Closes the database again at the end of the request."""67+ if hasattr(g, 'sqlite_db'):68+ g.sqlite_db.close()69+70+71+@app.route('/')72+def show_entries():73+ db = get_db()74+ cur = db.execute('select title, text from entries order by id desc')75+ entries = cur.fetchall()76+ return render_template('show_entries.html', entries=entries)77+78+79+@app.route('/add', methods=['POST'])80+def add_entry():81+ if not session.get('logged_in'):82+ abort(401)83+ db = get_db()84+ db.execute('insert into entries (title, text) values (?, ?)',85+ [request.form['title'], request.form['text']])86+ db.commit()87+ flash('New entry was successfully posted')88+ return redirect(url_for('show_entries'))89+90+91+@app.route('/login', methods=['GET', 'POST'])92+def login():93+ error = None94+ if request.method == 'POST':95+ if request.form['username'] != app.config['USERNAME']:96+ error = 'Invalid username'97+ elif request.form['password'] != app.config['PASSWORD']:98+ error = 'Invalid password'99+ else:100+ session['logged_in'] = True101+ flash('You were logged in')102+ return redirect(url_for('show_entries'))103+ return render_template('login.html', error=error)104+105+106+@app.route('/logout')107+def logout():108+ session.pop('logged_in', None)109+ flash('You were logged out')110+ return redirect(url_for('show_entries'))added:examples/flaskr/flaskr/schema.sql+6 added
1+drop table if exists entries;2+create table entries (3+ id integer primary key autoincrement,4+ title text not null,5+ 'text' text not null6+);deleted:examples/flaskr/static/style.css-18 removed
1-body { font-family: sans-serif; background: #eee; }2-a, h1, h2 { color: #377BA8; }3-h1, h2 { font-family: 'Georgia', serif; margin: 0; }4-h1 { border-bottom: 2px solid #eee; }5-h2 { font-size: 1.2em; }6-7-.page { margin: 2em auto; width: 35em; border: 5px solid #ccc;8- padding: 0.8em; background: white; }9-.entries { list-style: none; margin: 0; padding: 0; }10-.entries li { margin: 0.8em 1.2em; }11-.entries li h2 { margin-left: -1em; }12-.add-entry { font-size: 0.9em; border-bottom: 1px solid #ccc; }13-.add-entry dl { font-weight: bold; }14-.metanav { text-align: right; font-size: 0.8em; padding: 0.3em;15- margin-bottom: 1em; background: #fafafa; }16-.flash { background: #CEE5F5; padding: 0.5em;17- border: 1px solid #AACBE2; }18-.error { background: #F0D6D6; padding: 0.5em; }deleted:examples/flaskr/templates/layout.html-17 removed
1-<!doctype html>2-<title>Flaskr</title>3-<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">4-<div class="page">5- <h1>Flaskr</h1>6- <div class="metanav">7- {% if not session.logged_in %}8- <a href="{{ url_for('login') }}">log in</a>9- {% else %}10- <a href="{{ url_for('logout') }}">log out</a>11- {% endif %}12- </div>13- {% for message in get_flashed_messages() %}14- <div class="flash">{{ message }}</div>15- {% endfor %}16- {% block body %}{% endblock %}17-</div>deleted:examples/flaskr/templates/login.html-14 removed
1-{% extends "layout.html" %}2-{% block body %}3- <h2>Login</h2>4- {% if error %}<p class="error"><strong>Error:</strong> {{ error }}{% endif %}5- <form action="{{ url_for('login') }}" method="post">6- <dl>7- <dt>Username:8- <dd><input type="text" name="username">9- <dt>Password:10- <dd><input type="password" name="password">11- <dd><input type="submit" value="Login">12- </dl>13- </form>14-{% endblock %}deleted:examples/flaskr/templates/show_entries.html-21 removed
1-{% extends "layout.html" %}2-{% block body %}3- {% if session.logged_in %}4- <form action="{{ url_for('add_entry') }}" method="post" class="add-entry">5- <dl>6- <dt>Title:7- <dd><input type="text" size="30" name="title">8- <dt>Text:9- <dd><textarea name="text" rows="5" cols="40"></textarea>10- <dd><input type="submit" value="Share">11- </dl>12- </form>13- {% endif %}14- <ul class="entries">15- {% for entry in entries %}16- <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}17- {% else %}18- <li><em>Unbelievable. No entries here so far</em>19- {% endfor %}20- </ul>21-{% endblock %}added:examples/flaskr/tests/test_flaskr.py+76 added
1+# -*- coding: utf-8 -*-2+"""3+ Flaskr Tests4+ ~~~~~~~~~~~~5+6+ Tests the Flaskr application.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import os13+import tempfile14+import pytest15+from flaskr import flaskr16+17+18+@pytest.fixture19+def client(request):20+ db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()21+ flaskr.app.config['TESTING'] = True22+ client = flaskr.app.test_client()23+ with flaskr.app.app_context():24+ flaskr.init_db()25+26+ def teardown():27+ os.close(db_fd)28+ os.unlink(flaskr.app.config['DATABASE'])29+ request.addfinalizer(teardown)30+31+ return client32+33+34+def login(client, username, password):35+ return client.post('/login', data=dict(36+ username=username,37+ password=password38+ ), follow_redirects=True)39+40+41+def logout(client):42+ return client.get('/logout', follow_redirects=True)43+44+45+def test_empty_db(client):46+ """Start with a blank database."""47+ rv = client.get('/')48+ assert b'No entries here so far' in rv.data49+50+51+def test_login_logout(client):52+ """Make sure login and logout works"""53+ rv = login(client, flaskr.app.config['USERNAME'],54+ flaskr.app.config['PASSWORD'])55+ assert b'You were logged in' in rv.data56+ rv = logout(client)57+ assert b'You were logged out' in rv.data58+ rv = login(client, flaskr.app.config['USERNAME'] + 'x',59+ flaskr.app.config['PASSWORD'])60+ assert b'Invalid username' in rv.data61+ rv = login(client, flaskr.app.config['USERNAME'],62+ flaskr.app.config['PASSWORD'] + 'x')63+ assert b'Invalid password' in rv.data64+65+66+def test_messages(client):67+ """Test that messages work"""68+ login(client, flaskr.app.config['USERNAME'],69+ flaskr.app.config['PASSWORD'])70+ rv = client.post('/add', data=dict(71+ title='<Hello>',72+ text='<strong>HTML</strong> allowed here'73+ ), follow_redirects=True)74+ assert b'No entries here so far' not in rv.data75+ assert b'<Hello>' in rv.data76+ assert b'<strong>HTML</strong> allowed here' in rv.datamodified:examples/flaskr/.gitignore+1 added
1 flaskr.db2+.eggs/deleted:examples/flaskr/flaskr.py-110 removed
1-# -*- coding: utf-8 -*-2-"""3- Flaskr4- ~~~~~~5-6- A microblog example application written as Flask tutorial with7- Flask and sqlite3.8-9- :copyright: (c) 2015 by Armin Ronacher.10- :license: BSD, see LICENSE for more details.11-"""12-13-import os14-from sqlite3 import dbapi2 as sqlite315-from flask import Flask, request, session, g, redirect, url_for, abort, \16- render_template, flash17-18-19-# create our little application :)20-app = Flask(__name__)21-22-# Load default config and override config from an environment variable23-app.config.update(dict(24- DATABASE=os.path.join(app.root_path, 'flaskr.db'),25- DEBUG=True,26- SECRET_KEY='development key',27- USERNAME='admin',28- PASSWORD='default'29-))30-app.config.from_envvar('FLASKR_SETTINGS', silent=True)31-32-33-def connect_db():34- """Connects to the specific database."""35- rv = sqlite3.connect(app.config['DATABASE'])36- rv.row_factory = sqlite3.Row37- return rv38-39-40-def init_db():41- """Initializes the database."""42- db = get_db()43- with app.open_resource('schema.sql', mode='r') as f:44- db.cursor().executescript(f.read())45- db.commit()46-47-48-@app.cli.command('initdb')49-def initdb_command():50- """Creates the database tables."""51- init_db()52- print('Initialized the database.')53-54-55-def get_db():56- """Opens a new database connection if there is none yet for the57- current application context.58- """59- if not hasattr(g, 'sqlite_db'):60- g.sqlite_db = connect_db()61- return g.sqlite_db62-63-64-@app.teardown_appcontext65-def close_db(error):66- """Closes the database again at the end of the request."""67- if hasattr(g, 'sqlite_db'):68- g.sqlite_db.close()69-70-71-@app.route('/')72-def show_entries():73- db = get_db()74- cur = db.execute('select title, text from entries order by id desc')75- entries = cur.fetchall()76- return render_template('show_entries.html', entries=entries)77-78-79-@app.route('/add', methods=['POST'])80-def add_entry():81- if not session.get('logged_in'):82- abort(401)83- db = get_db()84- db.execute('insert into entries (title, text) values (?, ?)',85- [request.form['title'], request.form['text']])86- db.commit()87- flash('New entry was successfully posted')88- return redirect(url_for('show_entries'))89-90-91-@app.route('/login', methods=['GET', 'POST'])92-def login():93- error = None94- if request.method == 'POST':95- if request.form['username'] != app.config['USERNAME']:96- error = 'Invalid username'97- elif request.form['password'] != app.config['PASSWORD']:98- error = 'Invalid password'99- else:100- session['logged_in'] = True101- flash('You were logged in')102- return redirect(url_for('show_entries'))103- return render_template('login.html', error=error)104-105-106-@app.route('/logout')107-def logout():108- session.pop('logged_in', None)109- flash('You were logged out')110- return redirect(url_for('show_entries'))added:examples/flaskr/MANIFEST.in+3 added
1+graft flaskr/templates2+graft flaskr/static3+include flaskr/schema.sqlmodified:examples/flaskr/README+8 added-4 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. Instruct flask to use the right application16+ 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 20- 3. initialize the database with this command:24+ 4. initialize the database with this command:25 26 flask initdb27 24- 4. now you can run flaskr: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 33- You betcha. Run the `test_flaskr.py` file to see37+ You betcha. Run `python setup.py test` to see38 the tests pass.deleted:examples/flaskr/schema.sql-6 removed
1-drop table if exists entries;2-create table entries (3- id integer primary key autoincrement,4- title text not null,5- 'text' text not null6-);added:examples/flaskr/setup.cfg+2 added
1+[tool:pytest]2+test=pytestadded:examples/flaskr/setup.py+16 added
1+from setuptools import setup2+3+setup(4+ name='flaskr',5+ packages=['flaskr'],6+ include_package_data=True,7+ install_requires=[8+ 'flask',9+ ],10+ setup_requires=[11+ 'pytest-runner',12+ ],13+ tests_require=[14+ 'pytest',15+ ],16+)deleted:examples/flaskr/test_flaskr.py-77 removed
1-# -*- coding: utf-8 -*-2-"""3- Flaskr Tests4- ~~~~~~~~~~~~5-6- Tests the Flaskr application.7-8- :copyright: (c) 2015 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-12-import pytest13-14-import os15-import flaskr16-import tempfile17-18-19-@pytest.fixture20-def client(request):21- db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()22- flaskr.app.config['TESTING'] = True23- client = flaskr.app.test_client()24- with flaskr.app.app_context():25- flaskr.init_db()26-27- def teardown():28- os.close(db_fd)29- os.unlink(flaskr.app.config['DATABASE'])30- request.addfinalizer(teardown)31-32- return client33-34-35-def login(client, username, password):36- return client.post('/login', data=dict(37- username=username,38- password=password39- ), follow_redirects=True)40-41-42-def logout(client):43- return client.get('/logout', follow_redirects=True)44-45-46-def test_empty_db(client):47- """Start with a blank database."""48- rv = client.get('/')49- assert b'No entries here so far' in rv.data50-51-52-def test_login_logout(client):53- """Make sure login and logout works"""54- rv = login(client, flaskr.app.config['USERNAME'],55- flaskr.app.config['PASSWORD'])56- assert b'You were logged in' in rv.data57- rv = logout(client)58- assert b'You were logged out' in rv.data59- rv = login(client, flaskr.app.config['USERNAME'] + 'x',60- flaskr.app.config['PASSWORD'])61- assert b'Invalid username' in rv.data62- rv = login(client, flaskr.app.config['USERNAME'],63- flaskr.app.config['PASSWORD'] + 'x')64- assert b'Invalid password' in rv.data65-66-67-def test_messages(client):68- """Test that messages work"""69- login(client, flaskr.app.config['USERNAME'],70- flaskr.app.config['PASSWORD'])71- rv = client.post('/add', data=dict(72- title='<Hello>',73- text='<strong>HTML</strong> allowed here'74- ), follow_redirects=True)75- assert b'No entries here so far' not in rv.data76- assert b'<Hello>' in rv.data77- assert b'<strong>HTML</strong> allowed here' in rv.dataadded:examples/minitwit/minitwit/static/style.css+178 added
1+body {2+ background: #CAECE9;3+ font-family: 'Trebuchet MS', sans-serif;4+ font-size: 14px;5+}6+7+a {8+ color: #26776F;9+}10+11+a:hover {12+ color: #333;13+}14+15+input[type="text"],16+input[type="password"] {17+ background: white;18+ border: 1px solid #BFE6E2;19+ padding: 2px;20+ font-family: 'Trebuchet MS', sans-serif;21+ font-size: 14px;22+ -moz-border-radius: 2px;23+ -webkit-border-radius: 2px;24+ color: #105751;25+}26+27+input[type="submit"] {28+ background: #105751;29+ border: 1px solid #073B36;30+ padding: 1px 3px;31+ font-family: 'Trebuchet MS', sans-serif;32+ font-size: 14px;33+ font-weight: bold;34+ -moz-border-radius: 2px;35+ -webkit-border-radius: 2px;36+ color: white;37+}38+39+div.page {40+ background: white;41+ border: 1px solid #6ECCC4;42+ width: 700px;43+ margin: 30px auto;44+}45+46+div.page h1 {47+ background: #6ECCC4;48+ margin: 0;49+ padding: 10px 14px;50+ color: white;51+ letter-spacing: 1px;52+ text-shadow: 0 0 3px #24776F;53+ font-weight: normal;54+}55+56+div.page div.navigation {57+ background: #DEE9E8;58+ padding: 4px 10px;59+ border-top: 1px solid #ccc;60+ border-bottom: 1px solid #eee;61+ color: #888;62+ font-size: 12px;63+ letter-spacing: 0.5px;64+}65+66+div.page div.navigation a {67+ color: #444;68+ font-weight: bold;69+}70+71+div.page h2 {72+ margin: 0 0 15px 0;73+ color: #105751;74+ text-shadow: 0 1px 2px #ccc;75+}76+77+div.page div.body {78+ padding: 10px;79+}80+81+div.page div.footer {82+ background: #eee;83+ color: #888;84+ padding: 5px 10px;85+ font-size: 12px;86+}87+88+div.page div.followstatus {89+ border: 1px solid #ccc;90+ background: #E3EBEA;91+ -moz-border-radius: 2px;92+ -webkit-border-radius: 2px;93+ padding: 3px;94+ font-size: 13px;95+}96+97+div.page ul.messages {98+ list-style: none;99+ margin: 0;100+ padding: 0;101+}102+103+div.page ul.messages li {104+ margin: 10px 0;105+ padding: 5px;106+ background: #F0FAF9;107+ border: 1px solid #DBF3F1;108+ -moz-border-radius: 5px;109+ -webkit-border-radius: 5px;110+ min-height: 48px;111+}112+113+div.page ul.messages p {114+ margin: 0;115+}116+117+div.page ul.messages li img {118+ float: left;119+ padding: 0 10px 0 0;120+}121+122+div.page ul.messages li small {123+ font-size: 0.9em;124+ color: #888;125+}126+127+div.page div.twitbox {128+ margin: 10px 0;129+ padding: 5px;130+ background: #F0FAF9;131+ border: 1px solid #94E2DA;132+ -moz-border-radius: 5px;133+ -webkit-border-radius: 5px;134+}135+136+div.page div.twitbox h3 {137+ margin: 0;138+ font-size: 1em;139+ color: #2C7E76;140+}141+142+div.page div.twitbox p {143+ margin: 0;144+}145+146+div.page div.twitbox input[type="text"] {147+ width: 585px;148+}149+150+div.page div.twitbox input[type="submit"] {151+ width: 70px;152+ margin-left: 5px;153+}154+155+ul.flashes {156+ list-style: none;157+ margin: 10px 10px 0 10px;158+ padding: 0;159+}160+161+ul.flashes li {162+ background: #B9F3ED;163+ border: 1px solid #81CEC6;164+ -moz-border-radius: 2px;165+ -webkit-border-radius: 2px;166+ padding: 4px;167+ font-size: 13px;168+}169+170+div.error {171+ margin: 10px 0;172+ background: #FAE4E4;173+ border: 1px solid #DD6F6F;174+ -moz-border-radius: 2px;175+ -webkit-border-radius: 2px;176+ padding: 4px;177+ font-size: 13px;178+}added:examples/minitwit/minitwit/templates/layout.html+32 added
1+<!doctype html>2+<title>{% block title %}Welcome{% endblock %} | MiniTwit</title>3+<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">4+<div class="page">5+ <h1>MiniTwit</h1>6+ <div class="navigation">7+ {% if g.user %}8+ <a href="{{ url_for('timeline') }}">my timeline</a> |9+ <a href="{{ url_for('public_timeline') }}">public timeline</a> |10+ <a href="{{ url_for('logout') }}">sign out [{{ g.user.username }}]</a>11+ {% else %}12+ <a href="{{ url_for('public_timeline') }}">public timeline</a> |13+ <a href="{{ url_for('register') }}">sign up</a> |14+ <a href="{{ url_for('login') }}">sign in</a>15+ {% endif %}16+ </div>17+ {% with flashes = get_flashed_messages() %}18+ {% if flashes %}19+ <ul class="flashes">20+ {% for message in flashes %}21+ <li>{{ message }}22+ {% endfor %}23+ </ul>24+ {% endif %}25+ {% endwith %}26+ <div class="body">27+ {% block body %}{% endblock %}28+ </div>29+ <div class="footer">30+ MiniTwit — A Flask Application31+ </div>32+</div>added:examples/minitwit/minitwit/templates/login.html+16 added
1+{% extends "layout.html" %}2+{% block title %}Sign In{% endblock %}3+{% block body %}4+ <h2>Sign In</h2>5+ {% if error %}<div class="error"><strong>Error:</strong> {{ error }}</div>{% endif %}6+ <form action="" method="post">7+ <dl>8+ <dt>Username:9+ <dd><input type="text" name="username" size="30" value="{{ request.form.username }}">10+ <dt>Password:11+ <dd><input type="password" name="password" size="30">12+ </dl>13+ <div class="actions"><input type="submit" value="Sign In"></div>14+ </form>15+{% endblock %}16+added:examples/minitwit/minitwit/templates/register.html+19 added
1+{% extends "layout.html" %}2+{% block title %}Sign Up{% endblock %}3+{% block body %}4+ <h2>Sign Up</h2>5+ {% if error %}<div class="error"><strong>Error:</strong> {{ error }}</div>{% endif %}6+ <form action="" method="post">7+ <dl>8+ <dt>Username:9+ <dd><input type="text" name="username" size="30" value="{{ request.form.username }}">10+ <dt>E-Mail:11+ <dd><input type="text" name="email" size="30" value="{{ request.form.email }}">12+ <dt>Password:13+ <dd><input type="password" name="password" size="30">14+ <dt>Password <small>(repeat)</small>:15+ <dd><input type="password" name="password2" size="30">16+ </dl>17+ <div class="actions"><input type="submit" value="Sign Up"></div>18+ </form>19+{% endblock %}added:examples/minitwit/minitwit/templates/timeline.html+49 added
1+{% extends "layout.html" %}2+{% block title %}3+ {% if request.endpoint == 'public_timeline' %}4+ Public Timeline5+ {% elif request.endpoint == 'user_timeline' %}6+ {{ profile_user.username }}'s Timeline7+ {% else %}8+ My Timeline9+ {% endif %}10+{% endblock %}11+{% block body %}12+ <h2>{{ self.title() }}</h2>13+ {% if g.user %}14+ {% if request.endpoint == 'user_timeline' %}15+ <div class="followstatus">16+ {% if g.user.user_id == profile_user.user_id %}17+ This is you!18+ {% elif followed %}19+ You are currently following this user.20+ <a class="unfollow" href="{{ url_for('unfollow_user', username=profile_user.username)21+ }}">Unfollow user</a>.22+ {% else %}23+ You are not yet following this user.24+ <a class="follow" href="{{ url_for('follow_user', username=profile_user.username)25+ }}">Follow user</a>.26+ {% endif %}27+ </div>28+ {% elif request.endpoint == 'timeline' %}29+ <div class="twitbox">30+ <h3>What's on your mind {{ g.user.username }}?</h3>31+ <form action="{{ url_for('add_message') }}" method="post">32+ <p><input type="text" name="text" size="60"><!--33+ --><input type="submit" value="Share">34+ </form>35+ </div>36+ {% endif %}37+ {% endif %}38+ <ul class="messages">39+ {% for message in messages %}40+ <li><img src="{{ message.email|gravatar(size=48) }}"><p>41+ <strong><a href="{{ url_for('user_timeline', username=message.username)42+ }}">{{ message.username }}</a></strong>43+ {{ message.text }}44+ <small>— {{ message.pub_date|datetimeformat }}</small>45+ {% else %}46+ <li><em>There's no message so far.</em>47+ {% endfor %}48+ </ul>49+{% endblock %}added:examples/minitwit/minitwit/__init__.py+1 added
1+from .minitwit import appadded:examples/minitwit/minitwit/minitwit.py+256 added
1+# -*- coding: utf-8 -*-2+"""3+ MiniTwit4+ ~~~~~~~~5+6+ A microblogging application written with Flask and sqlite3.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import time13+from sqlite3 import dbapi2 as sqlite314+from hashlib import md515+from datetime import datetime16+from flask import Flask, request, session, url_for, redirect, \17+ render_template, abort, g, flash, _app_ctx_stack18+from werkzeug import check_password_hash, generate_password_hash19+20+21+# configuration22+DATABASE = '/tmp/minitwit.db'23+PER_PAGE = 3024+DEBUG = True25+SECRET_KEY = 'development key'26+27+# create our little application :)28+app = Flask(__name__)29+app.config.from_object(__name__)30+app.config.from_envvar('MINITWIT_SETTINGS', silent=True)31+32+33+def get_db():34+ """Opens a new database connection if there is none yet for the35+ current application context.36+ """37+ top = _app_ctx_stack.top38+ if not hasattr(top, 'sqlite_db'):39+ top.sqlite_db = sqlite3.connect(app.config['DATABASE'])40+ top.sqlite_db.row_factory = sqlite3.Row41+ return top.sqlite_db42+43+44+@app.teardown_appcontext45+def close_database(exception):46+ """Closes the database again at the end of the request."""47+ top = _app_ctx_stack.top48+ if hasattr(top, 'sqlite_db'):49+ top.sqlite_db.close()50+51+52+def init_db():53+ """Initializes the database."""54+ db = get_db()55+ with app.open_resource('schema.sql', mode='r') as f:56+ db.cursor().executescript(f.read())57+ db.commit()58+59+60+@app.cli.command('initdb')61+def initdb_command():62+ """Creates the database tables."""63+ init_db()64+ print('Initialized the database.')65+66+67+def query_db(query, args=(), one=False):68+ """Queries the database and returns a list of dictionaries."""69+ cur = get_db().execute(query, args)70+ rv = cur.fetchall()71+ return (rv[0] if rv else None) if one else rv72+73+74+def get_user_id(username):75+ """Convenience method to look up the id for a username."""76+ rv = query_db('select user_id from user where username = ?',77+ [username], one=True)78+ return rv[0] if rv else None79+80+81+def format_datetime(timestamp):82+ """Format a timestamp for display."""83+ return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d @ %H:%M')84+85+86+def gravatar_url(email, size=80):87+ """Return the gravatar image for the given email address."""88+ return 'https://www.gravatar.com/avatar/%s?d=identicon&s=%d' % \89+ (md5(email.strip().lower().encode('utf-8')).hexdigest(), size)90+91+92+@app.before_request93+def before_request():94+ g.user = None95+ if 'user_id' in session:96+ g.user = query_db('select * from user where user_id = ?',97+ [session['user_id']], one=True)98+99+100+@app.route('/')101+def timeline():102+ """Shows a users timeline or if no user is logged in it will103+ redirect to the public timeline. This timeline shows the user's104+ messages as well as all the messages of followed users.105+ """106+ if not g.user:107+ return redirect(url_for('public_timeline'))108+ return render_template('timeline.html', messages=query_db('''109+ select message.*, user.* from message, user110+ where message.author_id = user.user_id and (111+ user.user_id = ? or112+ user.user_id in (select whom_id from follower113+ where who_id = ?))114+ order by message.pub_date desc limit ?''',115+ [session['user_id'], session['user_id'], PER_PAGE]))116+117+118+@app.route('/public')119+def public_timeline():120+ """Displays the latest messages of all users."""121+ return render_template('timeline.html', messages=query_db('''122+ select message.*, user.* from message, user123+ where message.author_id = user.user_id124+ order by message.pub_date desc limit ?''', [PER_PAGE]))125+126+127+@app.route('/<username>')128+def user_timeline(username):129+ """Display's a users tweets."""130+ profile_user = query_db('select * from user where username = ?',131+ [username], one=True)132+ if profile_user is None:133+ abort(404)134+ followed = False135+ if g.user:136+ followed = query_db('''select 1 from follower where137+ follower.who_id = ? and follower.whom_id = ?''',138+ [session['user_id'], profile_user['user_id']],139+ one=True) is not None140+ return render_template('timeline.html', messages=query_db('''141+ select message.*, user.* from message, user where142+ user.user_id = message.author_id and user.user_id = ?143+ order by message.pub_date desc limit ?''',144+ [profile_user['user_id'], PER_PAGE]), followed=followed,145+ profile_user=profile_user)146+147+148+@app.route('/<username>/follow')149+def follow_user(username):150+ """Adds the current user as follower of the given user."""151+ if not g.user:152+ abort(401)153+ whom_id = get_user_id(username)154+ if whom_id is None:155+ abort(404)156+ db = get_db()157+ db.execute('insert into follower (who_id, whom_id) values (?, ?)',158+ [session['user_id'], whom_id])159+ db.commit()160+ flash('You are now following "%s"' % username)161+ return redirect(url_for('user_timeline', username=username))162+163+164+@app.route('/<username>/unfollow')165+def unfollow_user(username):166+ """Removes the current user as follower of the given user."""167+ if not g.user:168+ abort(401)169+ whom_id = get_user_id(username)170+ if whom_id is None:171+ abort(404)172+ db = get_db()173+ db.execute('delete from follower where who_id=? and whom_id=?',174+ [session['user_id'], whom_id])175+ db.commit()176+ flash('You are no longer following "%s"' % username)177+ return redirect(url_for('user_timeline', username=username))178+179+180+@app.route('/add_message', methods=['POST'])181+def add_message():182+ """Registers a new message for the user."""183+ if 'user_id' not in session:184+ abort(401)185+ if request.form['text']:186+ db = get_db()187+ db.execute('''insert into message (author_id, text, pub_date)188+ values (?, ?, ?)''', (session['user_id'], request.form['text'],189+ int(time.time())))190+ db.commit()191+ flash('Your message was recorded')192+ return redirect(url_for('timeline'))193+194+195+@app.route('/login', methods=['GET', 'POST'])196+def login():197+ """Logs the user in."""198+ if g.user:199+ return redirect(url_for('timeline'))200+ error = None201+ if request.method == 'POST':202+ user = query_db('''select * from user where203+ username = ?''', [request.form['username']], one=True)204+ if user is None:205+ error = 'Invalid username'206+ elif not check_password_hash(user['pw_hash'],207+ request.form['password']):208+ error = 'Invalid password'209+ else:210+ flash('You were logged in')211+ session['user_id'] = user['user_id']212+ return redirect(url_for('timeline'))213+ return render_template('login.html', error=error)214+215+216+@app.route('/register', methods=['GET', 'POST'])217+def register():218+ """Registers the user."""219+ if g.user:220+ return redirect(url_for('timeline'))221+ error = None222+ if request.method == 'POST':223+ if not request.form['username']:224+ error = 'You have to enter a username'225+ elif not request.form['email'] or \226+ '@' not in request.form['email']:227+ error = 'You have to enter a valid email address'228+ elif not request.form['password']:229+ error = 'You have to enter a password'230+ elif request.form['password'] != request.form['password2']:231+ error = 'The two passwords do not match'232+ elif get_user_id(request.form['username']) is not None:233+ error = 'The username is already taken'234+ else:235+ db = get_db()236+ db.execute('''insert into user (237+ username, email, pw_hash) values (?, ?, ?)''',238+ [request.form['username'], request.form['email'],239+ generate_password_hash(request.form['password'])])240+ db.commit()241+ flash('You were successfully registered and can login now')242+ return redirect(url_for('login'))243+ return render_template('register.html', error=error)244+245+246+@app.route('/logout')247+def logout():248+ """Logs the user out."""249+ flash('You were logged out')250+ session.pop('user_id', None)251+ return redirect(url_for('public_timeline'))252+253+254+# add some filters to jinja255+app.jinja_env.filters['datetimeformat'] = format_datetime256+app.jinja_env.filters['gravatar'] = gravatar_urladded:examples/minitwit/minitwit/schema.sql+21 added
1+drop table if exists user;2+create table user (3+ user_id integer primary key autoincrement,4+ username text not null,5+ email text not null,6+ pw_hash text not null7+);8+9+drop table if exists follower;10+create table follower (11+ who_id integer,12+ whom_id integer13+);14+15+drop table if exists message;16+create table message (17+ message_id integer primary key autoincrement,18+ author_id integer not null,19+ text text not null,20+ pub_date integer21+);deleted:examples/minitwit/static/style.css-178 removed
1-body {2- background: #CAECE9;3- font-family: 'Trebuchet MS', sans-serif;4- font-size: 14px;5-}6-7-a {8- color: #26776F;9-}10-11-a:hover {12- color: #333;13-}14-15-input[type="text"],16-input[type="password"] {17- background: white;18- border: 1px solid #BFE6E2;19- padding: 2px;20- font-family: 'Trebuchet MS', sans-serif;21- font-size: 14px;22- -moz-border-radius: 2px;23- -webkit-border-radius: 2px;24- color: #105751;25-}26-27-input[type="submit"] {28- background: #105751;29- border: 1px solid #073B36;30- padding: 1px 3px;31- font-family: 'Trebuchet MS', sans-serif;32- font-size: 14px;33- font-weight: bold;34- -moz-border-radius: 2px;35- -webkit-border-radius: 2px;36- color: white;37-}38-39-div.page {40- background: white;41- border: 1px solid #6ECCC4;42- width: 700px;43- margin: 30px auto;44-}45-46-div.page h1 {47- background: #6ECCC4;48- margin: 0;49- padding: 10px 14px;50- color: white;51- letter-spacing: 1px;52- text-shadow: 0 0 3px #24776F;53- font-weight: normal;54-}55-56-div.page div.navigation {57- background: #DEE9E8;58- padding: 4px 10px;59- border-top: 1px solid #ccc;60- border-bottom: 1px solid #eee;61- color: #888;62- font-size: 12px;63- letter-spacing: 0.5px;64-}65-66-div.page div.navigation a {67- color: #444;68- font-weight: bold;69-}70-71-div.page h2 {72- margin: 0 0 15px 0;73- color: #105751;74- text-shadow: 0 1px 2px #ccc;75-}76-77-div.page div.body {78- padding: 10px;79-}80-81-div.page div.footer {82- background: #eee;83- color: #888;84- padding: 5px 10px;85- font-size: 12px;86-}87-88-div.page div.followstatus {89- border: 1px solid #ccc;90- background: #E3EBEA;91- -moz-border-radius: 2px;92- -webkit-border-radius: 2px;93- padding: 3px;94- font-size: 13px;95-}96-97-div.page ul.messages {98- list-style: none;99- margin: 0;100- padding: 0;101-}102-103-div.page ul.messages li {104- margin: 10px 0;105- padding: 5px;106- background: #F0FAF9;107- border: 1px solid #DBF3F1;108- -moz-border-radius: 5px;109- -webkit-border-radius: 5px;110- min-height: 48px;111-}112-113-div.page ul.messages p {114- margin: 0;115-}116-117-div.page ul.messages li img {118- float: left;119- padding: 0 10px 0 0;120-}121-122-div.page ul.messages li small {123- font-size: 0.9em;124- color: #888;125-}126-127-div.page div.twitbox {128- margin: 10px 0;129- padding: 5px;130- background: #F0FAF9;131- border: 1px solid #94E2DA;132- -moz-border-radius: 5px;133- -webkit-border-radius: 5px;134-}135-136-div.page div.twitbox h3 {137- margin: 0;138- font-size: 1em;139- color: #2C7E76;140-}141-142-div.page div.twitbox p {143- margin: 0;144-}145-146-div.page div.twitbox input[type="text"] {147- width: 585px;148-}149-150-div.page div.twitbox input[type="submit"] {151- width: 70px;152- margin-left: 5px;153-}154-155-ul.flashes {156- list-style: none;157- margin: 10px 10px 0 10px;158- padding: 0;159-}160-161-ul.flashes li {162- background: #B9F3ED;163- border: 1px solid #81CEC6;164- -moz-border-radius: 2px;165- -webkit-border-radius: 2px;166- padding: 4px;167- font-size: 13px;168-}169-170-div.error {171- margin: 10px 0;172- background: #FAE4E4;173- border: 1px solid #DD6F6F;174- -moz-border-radius: 2px;175- -webkit-border-radius: 2px;176- padding: 4px;177- font-size: 13px;178-}deleted:examples/minitwit/templates/layout.html-32 removed
1-<!doctype html>2-<title>{% block title %}Welcome{% endblock %} | MiniTwit</title>3-<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">4-<div class="page">5- <h1>MiniTwit</h1>6- <div class="navigation">7- {% if g.user %}8- <a href="{{ url_for('timeline') }}">my timeline</a> |9- <a href="{{ url_for('public_timeline') }}">public timeline</a> |10- <a href="{{ url_for('logout') }}">sign out [{{ g.user.username }}]</a>11- {% else %}12- <a href="{{ url_for('public_timeline') }}">public timeline</a> |13- <a href="{{ url_for('register') }}">sign up</a> |14- <a href="{{ url_for('login') }}">sign in</a>15- {% endif %}16- </div>17- {% with flashes = get_flashed_messages() %}18- {% if flashes %}19- <ul class="flashes">20- {% for message in flashes %}21- <li>{{ message }}22- {% endfor %}23- </ul>24- {% endif %}25- {% endwith %}26- <div class="body">27- {% block body %}{% endblock %}28- </div>29- <div class="footer">30- MiniTwit — A Flask Application31- </div>32-</div>deleted:examples/minitwit/templates/login.html-16 removed
1-{% extends "layout.html" %}2-{% block title %}Sign In{% endblock %}3-{% block body %}4- <h2>Sign In</h2>5- {% if error %}<div class="error"><strong>Error:</strong> {{ error }}</div>{% endif %}6- <form action="" method="post">7- <dl>8- <dt>Username:9- <dd><input type="text" name="username" size="30" value="{{ request.form.username }}">10- <dt>Password:11- <dd><input type="password" name="password" size="30">12- </dl>13- <div class="actions"><input type="submit" value="Sign In"></div>14- </form>15-{% endblock %}16-deleted:examples/minitwit/templates/register.html-19 removed
1-{% extends "layout.html" %}2-{% block title %}Sign Up{% endblock %}3-{% block body %}4- <h2>Sign Up</h2>5- {% if error %}<div class="error"><strong>Error:</strong> {{ error }}</div>{% endif %}6- <form action="" method="post">7- <dl>8- <dt>Username:9- <dd><input type="text" name="username" size="30" value="{{ request.form.username }}">10- <dt>E-Mail:11- <dd><input type="text" name="email" size="30" value="{{ request.form.email }}">12- <dt>Password:13- <dd><input type="password" name="password" size="30">14- <dt>Password <small>(repeat)</small>:15- <dd><input type="password" name="password2" size="30">16- </dl>17- <div class="actions"><input type="submit" value="Sign Up"></div>18- </form>19-{% endblock %}deleted:examples/minitwit/templates/timeline.html-49 removed
1-{% extends "layout.html" %}2-{% block title %}3- {% if request.endpoint == 'public_timeline' %}4- Public Timeline5- {% elif request.endpoint == 'user_timeline' %}6- {{ profile_user.username }}'s Timeline7- {% else %}8- My Timeline9- {% endif %}10-{% endblock %}11-{% block body %}12- <h2>{{ self.title() }}</h2>13- {% if g.user %}14- {% if request.endpoint == 'user_timeline' %}15- <div class="followstatus">16- {% if g.user.user_id == profile_user.user_id %}17- This is you!18- {% elif followed %}19- You are currently following this user.20- <a class="unfollow" href="{{ url_for('unfollow_user', username=profile_user.username)21- }}">Unfollow user</a>.22- {% else %}23- You are not yet following this user.24- <a class="follow" href="{{ url_for('follow_user', username=profile_user.username)25- }}">Follow user</a>.26- {% endif %}27- </div>28- {% elif request.endpoint == 'timeline' %}29- <div class="twitbox">30- <h3>What's on your mind {{ g.user.username }}?</h3>31- <form action="{{ url_for('add_message') }}" method="post">32- <p><input type="text" name="text" size="60"><!--33- --><input type="submit" value="Share">34- </form>35- </div>36- {% endif %}37- {% endif %}38- <ul class="messages">39- {% for message in messages %}40- <li><img src="{{ message.email|gravatar(size=48) }}"><p>41- <strong><a href="{{ url_for('user_timeline', username=message.username)42- }}">{{ message.username }}</a></strong>43- {{ message.text }}44- <small>— {{ message.pub_date|datetimeformat }}</small>45- {% else %}46- <li><em>There's no message so far.</em>47- {% endfor %}48- </ul>49-{% endblock %}added:examples/minitwit/tests/test_minitwit.py+151 added
1+# -*- coding: utf-8 -*-2+"""3+ MiniTwit Tests4+ ~~~~~~~~~~~~~~5+6+ Tests the MiniTwit application.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+import os12+import tempfile13+import pytest14+from minitwit import minitwit15+16+17+@pytest.fixture18+def client(request):19+ db_fd, minitwit.app.config['DATABASE'] = tempfile.mkstemp()20+ client = minitwit.app.test_client()21+ with minitwit.app.app_context():22+ minitwit.init_db()23+24+ def teardown():25+ """Get rid of the database again after each test."""26+ os.close(db_fd)27+ os.unlink(minitwit.app.config['DATABASE'])28+ request.addfinalizer(teardown)29+ return client30+31+32+def register(client, username, password, password2=None, email=None):33+ """Helper function to register a user"""34+ if password2 is None:35+ password2 = password36+ if email is None:37+ email = username + '@example.com'38+ return client.post('/register', data={39+ 'username': username,40+ 'password': password,41+ 'password2': password2,42+ 'email': email,43+ }, follow_redirects=True)44+45+46+def login(client, username, password):47+ """Helper function to login"""48+ return client.post('/login', data={49+ 'username': username,50+ 'password': password51+ }, follow_redirects=True)52+53+54+def register_and_login(client, username, password):55+ """Registers and logs in in one go"""56+ register(client, username, password)57+ return login(client, username, password)58+59+60+def logout(client):61+ """Helper function to logout"""62+ return client.get('/logout', follow_redirects=True)63+64+65+def add_message(client, text):66+ """Records a message"""67+ rv = client.post('/add_message', data={'text': text},68+ follow_redirects=True)69+ if text:70+ assert b'Your message was recorded' in rv.data71+ return rv72+73+74+def test_register(client):75+ """Make sure registering works"""76+ rv = register(client, 'user1', 'default')77+ assert b'You were successfully registered ' \78+ b'and can login now' in rv.data79+ rv = register(client, 'user1', 'default')80+ assert b'The username is already taken' in rv.data81+ rv = register(client, '', 'default')82+ assert b'You have to enter a username' in rv.data83+ rv = register(client, 'meh', '')84+ assert b'You have to enter a password' in rv.data85+ rv = register(client, 'meh', 'x', 'y')86+ assert b'The two passwords do not match' in rv.data87+ rv = register(client, 'meh', 'foo', email='broken')88+ assert b'You have to enter a valid email address' in rv.data89+90+91+def test_login_logout(client):92+ """Make sure logging in and logging out works"""93+ rv = register_and_login(client, 'user1', 'default')94+ assert b'You were logged in' in rv.data95+ rv = logout(client)96+ assert b'You were logged out' in rv.data97+ rv = login(client, 'user1', 'wrongpassword')98+ assert b'Invalid password' in rv.data99+ rv = login(client, 'user2', 'wrongpassword')100+ assert b'Invalid username' in rv.data101+102+103+def test_message_recording(client):104+ """Check if adding messages works"""105+ register_and_login(client, 'foo', 'default')106+ add_message(client, 'test message 1')107+ add_message(client, '<test message 2>')108+ rv = client.get('/')109+ assert b'test message 1' in rv.data110+ assert b'<test message 2>' in rv.data111+112+113+def test_timelines(client):114+ """Make sure that timelines work"""115+ register_and_login(client, 'foo', 'default')116+ add_message(client, 'the message by foo')117+ logout(client)118+ register_and_login(client, 'bar', 'default')119+ add_message(client, 'the message by bar')120+ rv = client.get('/public')121+ assert b'the message by foo' in rv.data122+ assert b'the message by bar' in rv.data123+124+ # bar's timeline should just show bar's message125+ rv = client.get('/')126+ assert b'the message by foo' not in rv.data127+ assert b'the message by bar' in rv.data128+129+ # now let's follow foo130+ rv = client.get('/foo/follow', follow_redirects=True)131+ assert b'You are now following "foo"' in rv.data132+133+ # we should now see foo's message134+ rv = client.get('/')135+ assert b'the message by foo' in rv.data136+ assert b'the message by bar' in rv.data137+138+ # but on the user's page we only want the user's message139+ rv = client.get('/bar')140+ assert b'the message by foo' not in rv.data141+ assert b'the message by bar' in rv.data142+ rv = client.get('/foo')143+ assert b'the message by foo' in rv.data144+ assert b'the message by bar' not in rv.data145+146+ # now unfollow and check if that worked147+ rv = client.get('/foo/unfollow', follow_redirects=True)148+ assert b'You are no longer following "foo"' in rv.data149+ rv = client.get('/')150+ assert b'the message by foo' not in rv.data151+ assert b'the message by bar' in rv.dataadded:examples/minitwit/.gitignore+2 added
1+minitwit.db2+.eggs/added:examples/minitwit/MANIFEST.in+3 added
1+graft minitwit/templates2+graft minitwit/static3+include minitwit/schema.sqldeleted:examples/minitwit/minitwit.py-256 removed
1-# -*- coding: utf-8 -*-2-"""3- MiniTwit4- ~~~~~~~~5-6- A microblogging application written with Flask and sqlite3.7-8- :copyright: (c) 2015 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-12-import time13-from sqlite3 import dbapi2 as sqlite314-from hashlib import md515-from datetime import datetime16-from flask import Flask, request, session, url_for, redirect, \17- render_template, abort, g, flash, _app_ctx_stack18-from werkzeug import check_password_hash, generate_password_hash19-20-21-# configuration22-DATABASE = '/tmp/minitwit.db'23-PER_PAGE = 3024-DEBUG = True25-SECRET_KEY = 'development key'26-27-# create our little application :)28-app = Flask(__name__)29-app.config.from_object(__name__)30-app.config.from_envvar('MINITWIT_SETTINGS', silent=True)31-32-33-def get_db():34- """Opens a new database connection if there is none yet for the35- current application context.36- """37- top = _app_ctx_stack.top38- if not hasattr(top, 'sqlite_db'):39- top.sqlite_db = sqlite3.connect(app.config['DATABASE'])40- top.sqlite_db.row_factory = sqlite3.Row41- return top.sqlite_db42-43-44-@app.teardown_appcontext45-def close_database(exception):46- """Closes the database again at the end of the request."""47- top = _app_ctx_stack.top48- if hasattr(top, 'sqlite_db'):49- top.sqlite_db.close()50-51-52-def init_db():53- """Initializes the database."""54- db = get_db()55- with app.open_resource('schema.sql', mode='r') as f:56- db.cursor().executescript(f.read())57- db.commit()58-59-60-@app.cli.command('initdb')61-def initdb_command():62- """Creates the database tables."""63- init_db()64- print('Initialized the database.')65-66-67-def query_db(query, args=(), one=False):68- """Queries the database and returns a list of dictionaries."""69- cur = get_db().execute(query, args)70- rv = cur.fetchall()71- return (rv[0] if rv else None) if one else rv72-73-74-def get_user_id(username):75- """Convenience method to look up the id for a username."""76- rv = query_db('select user_id from user where username = ?',77- [username], one=True)78- return rv[0] if rv else None79-80-81-def format_datetime(timestamp):82- """Format a timestamp for display."""83- return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d @ %H:%M')84-85-86-def gravatar_url(email, size=80):87- """Return the gravatar image for the given email address."""88- return 'http://www.gravatar.com/avatar/%s?d=identicon&s=%d' % \89- (md5(email.strip().lower().encode('utf-8')).hexdigest(), size)90-91-92-@app.before_request93-def before_request():94- g.user = None95- if 'user_id' in session:96- g.user = query_db('select * from user where user_id = ?',97- [session['user_id']], one=True)98-99-100-@app.route('/')101-def timeline():102- """Shows a users timeline or if no user is logged in it will103- redirect to the public timeline. This timeline shows the user's104- messages as well as all the messages of followed users.105- """106- if not g.user:107- return redirect(url_for('public_timeline'))108- return render_template('timeline.html', messages=query_db('''109- select message.*, user.* from message, user110- where message.author_id = user.user_id and (111- user.user_id = ? or112- user.user_id in (select whom_id from follower113- where who_id = ?))114- order by message.pub_date desc limit ?''',115- [session['user_id'], session['user_id'], PER_PAGE]))116-117-118-@app.route('/public')119-def public_timeline():120- """Displays the latest messages of all users."""121- return render_template('timeline.html', messages=query_db('''122- select message.*, user.* from message, user123- where message.author_id = user.user_id124- order by message.pub_date desc limit ?''', [PER_PAGE]))125-126-127-@app.route('/<username>')128-def user_timeline(username):129- """Display's a users tweets."""130- profile_user = query_db('select * from user where username = ?',131- [username], one=True)132- if profile_user is None:133- abort(404)134- followed = False135- if g.user:136- followed = query_db('''select 1 from follower where137- follower.who_id = ? and follower.whom_id = ?''',138- [session['user_id'], profile_user['user_id']],139- one=True) is not None140- return render_template('timeline.html', messages=query_db('''141- select message.*, user.* from message, user where142- user.user_id = message.author_id and user.user_id = ?143- order by message.pub_date desc limit ?''',144- [profile_user['user_id'], PER_PAGE]), followed=followed,145- profile_user=profile_user)146-147-148-@app.route('/<username>/follow')149-def follow_user(username):150- """Adds the current user as follower of the given user."""151- if not g.user:152- abort(401)153- whom_id = get_user_id(username)154- if whom_id is None:155- abort(404)156- db = get_db()157- db.execute('insert into follower (who_id, whom_id) values (?, ?)',158- [session['user_id'], whom_id])159- db.commit()160- flash('You are now following "%s"' % username)161- return redirect(url_for('user_timeline', username=username))162-163-164-@app.route('/<username>/unfollow')165-def unfollow_user(username):166- """Removes the current user as follower of the given user."""167- if not g.user:168- abort(401)169- whom_id = get_user_id(username)170- if whom_id is None:171- abort(404)172- db = get_db()173- db.execute('delete from follower where who_id=? and whom_id=?',174- [session['user_id'], whom_id])175- db.commit()176- flash('You are no longer following "%s"' % username)177- return redirect(url_for('user_timeline', username=username))178-179-180-@app.route('/add_message', methods=['POST'])181-def add_message():182- """Registers a new message for the user."""183- if 'user_id' not in session:184- abort(401)185- if request.form['text']:186- db = get_db()187- db.execute('''insert into message (author_id, text, pub_date)188- values (?, ?, ?)''', (session['user_id'], request.form['text'],189- int(time.time())))190- db.commit()191- flash('Your message was recorded')192- return redirect(url_for('timeline'))193-194-195-@app.route('/login', methods=['GET', 'POST'])196-def login():197- """Logs the user in."""198- if g.user:199- return redirect(url_for('timeline'))200- error = None201- if request.method == 'POST':202- user = query_db('''select * from user where203- username = ?''', [request.form['username']], one=True)204- if user is None:205- error = 'Invalid username'206- elif not check_password_hash(user['pw_hash'],207- request.form['password']):208- error = 'Invalid password'209- else:210- flash('You were logged in')211- session['user_id'] = user['user_id']212- return redirect(url_for('timeline'))213- return render_template('login.html', error=error)214-215-216-@app.route('/register', methods=['GET', 'POST'])217-def register():218- """Registers the user."""219- if g.user:220- return redirect(url_for('timeline'))221- error = None222- if request.method == 'POST':223- if not request.form['username']:224- error = 'You have to enter a username'225- elif not request.form['email'] or \226- '@' not in request.form['email']:227- error = 'You have to enter a valid email address'228- elif not request.form['password']:229- error = 'You have to enter a password'230- elif request.form['password'] != request.form['password2']:231- error = 'The two passwords do not match'232- elif get_user_id(request.form['username']) is not None:233- error = 'The username is already taken'234- else:235- db = get_db()236- db.execute('''insert into user (237- username, email, pw_hash) values (?, ?, ?)''',238- [request.form['username'], request.form['email'],239- generate_password_hash(request.form['password'])])240- db.commit()241- flash('You were successfully registered and can login now')242- return redirect(url_for('login'))243- return render_template('register.html', error=error)244-245-246-@app.route('/logout')247-def logout():248- """Logs the user out."""249- flash('You were logged out')250- session.pop('user_id', None)251- return redirect(url_for('public_timeline'))252-253-254-# add some filters to jinja255-app.jinja_env.filters['datetimeformat'] = format_datetime256-app.jinja_env.filters['gravatar'] = gravatar_urlmodified:examples/minitwit/README+8 added-4 removed
12 unmodified lines13 1. edit the configuration in the minitwit.py file or14 export an MINITWIT_SETTINGS environment variable15 pointing to a configuration file.16 17- 2. tell flask about the right application:17+ 2. install the app from the root of the project directory18 19+ pip install --editable .20+21+ 3. tell flask about the right application:22+23 export FLASK_APP=minitwit24 21- 2. fire up a shell and run this:25+ 4. fire up a shell and run this:26 27 flask initdb28 25- 3. now you can run minitwit:29+ 5. now you can run minitwit:30 31 flask run32 33 the application will greet you on34 http://localhost:5000/35 36 ~ Is it tested?37 34- You betcha. Run the `test_minitwit.py` file to38+ You betcha. Run the `python setup.py test` file to39 see the tests pass.deleted:examples/minitwit/schema.sql-21 removed
1-drop table if exists user;2-create table user (3- user_id integer primary key autoincrement,4- username text not null,5- email text not null,6- pw_hash text not null7-);8-9-drop table if exists follower;10-create table follower (11- who_id integer,12- whom_id integer13-);14-15-drop table if exists message;16-create table message (17- message_id integer primary key autoincrement,18- author_id integer not null,19- text text not null,20- pub_date integer21-);added:examples/minitwit/setup.cfg+2 added
1+[aliases]2+test=pytestadded:examples/minitwit/setup.py+16 added
1+from setuptools import setup2+3+setup(4+ name='minitwit',5+ packages=['minitwit'],6+ include_package_data=True,7+ install_requires=[8+ 'flask',9+ ],10+ setup_requires=[11+ 'pytest-runner',12+ ],13+ tests_require=[14+ 'pytest',15+ ],16+)deleted:examples/minitwit/test_minitwit.py-151 removed
1-# -*- coding: utf-8 -*-2-"""3- MiniTwit Tests4- ~~~~~~~~~~~~~~5-6- Tests the MiniTwit application.7-8- :copyright: (c) 2015 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-import os12-import minitwit13-import tempfile14-import pytest15-16-17-@pytest.fixture18-def client(request):19- db_fd, minitwit.app.config['DATABASE'] = tempfile.mkstemp()20- client = minitwit.app.test_client()21- with minitwit.app.app_context():22- minitwit.init_db()23-24- def teardown():25- """Get rid of the database again after each test."""26- os.close(db_fd)27- os.unlink(minitwit.app.config['DATABASE'])28- request.addfinalizer(teardown)29- return client30-31-32-def register(client, username, password, password2=None, email=None):33- """Helper function to register a user"""34- if password2 is None:35- password2 = password36- if email is None:37- email = username + '@example.com'38- return client.post('/register', data={39- 'username': username,40- 'password': password,41- 'password2': password2,42- 'email': email,43- }, follow_redirects=True)44-45-46-def login(client, username, password):47- """Helper function to login"""48- return client.post('/login', data={49- 'username': username,50- 'password': password51- }, follow_redirects=True)52-53-54-def register_and_login(client, username, password):55- """Registers and logs in in one go"""56- register(client, username, password)57- return login(client, username, password)58-59-60-def logout(client):61- """Helper function to logout"""62- return client.get('/logout', follow_redirects=True)63-64-65-def add_message(client, text):66- """Records a message"""67- rv = client.post('/add_message', data={'text': text},68- follow_redirects=True)69- if text:70- assert b'Your message was recorded' in rv.data71- return rv72-73-74-def test_register(client):75- """Make sure registering works"""76- rv = register(client, 'user1', 'default')77- assert b'You were successfully registered ' \78- b'and can login now' in rv.data79- rv = register(client, 'user1', 'default')80- assert b'The username is already taken' in rv.data81- rv = register(client, '', 'default')82- assert b'You have to enter a username' in rv.data83- rv = register(client, 'meh', '')84- assert b'You have to enter a password' in rv.data85- rv = register(client, 'meh', 'x', 'y')86- assert b'The two passwords do not match' in rv.data87- rv = register(client, 'meh', 'foo', email='broken')88- assert b'You have to enter a valid email address' in rv.data89-90-91-def test_login_logout(client):92- """Make sure logging in and logging out works"""93- rv = register_and_login(client, 'user1', 'default')94- assert b'You were logged in' in rv.data95- rv = logout(client)96- assert b'You were logged out' in rv.data97- rv = login(client, 'user1', 'wrongpassword')98- assert b'Invalid password' in rv.data99- rv = login(client, 'user2', 'wrongpassword')100- assert b'Invalid username' in rv.data101-102-103-def test_message_recording(client):104- """Check if adding messages works"""105- register_and_login(client, 'foo', 'default')106- add_message(client, 'test message 1')107- add_message(client, '<test message 2>')108- rv = client.get('/')109- assert b'test message 1' in rv.data110- assert b'<test message 2>' in rv.data111-112-113-def test_timelines(client):114- """Make sure that timelines work"""115- register_and_login(client, 'foo', 'default')116- add_message(client, 'the message by foo')117- logout(client)118- register_and_login(client, 'bar', 'default')119- add_message(client, 'the message by bar')120- rv = client.get('/public')121- assert b'the message by foo' in rv.data122- assert b'the message by bar' in rv.data123-124- # bar's timeline should just show bar's message125- rv = client.get('/')126- assert b'the message by foo' not in rv.data127- assert b'the message by bar' in rv.data128-129- # now let's follow foo130- rv = client.get('/foo/follow', follow_redirects=True)131- assert b'You are now following "foo"' in rv.data132-133- # we should now see foo's message134- rv = client.get('/')135- assert b'the message by foo' in rv.data136- assert b'the message by bar' in rv.data137-138- # but on the user's page we only want the user's message139- rv = client.get('/bar')140- assert b'the message by foo' not in rv.data141- assert b'the message by bar' in rv.data142- rv = client.get('/foo')143- assert b'the message by foo' in rv.data144- assert b'the message by bar' not in rv.data145-146- # now unfollow and check if that worked147- rv = client.get('/foo/unfollow', follow_redirects=True)148- assert b'You are no longer following "foo"' in rv.data149- rv = client.get('/')150- assert b'the message by foo' not in rv.data151- assert b'the message by bar' in rv.dataadded:examples/patterns/largerapp/tests/test_largerapp.py+12 added
1+from yourapplication import app2+import pytest3+4+@pytest.fixture5+def client():6+ app.config['TESTING'] = True7+ client = app.test_client()8+ return client9+10+def test_index(client):11+ rv = client.get('/')12+ assert b"Hello World!" in rv.dataadded:examples/patterns/largerapp/yourapplication/static/style.css
added:examples/patterns/largerapp/yourapplication/templates/index.html
added:examples/patterns/largerapp/yourapplication/templates/layout.html
added:examples/patterns/largerapp/yourapplication/templates/login.html
added:examples/patterns/largerapp/yourapplication/__init__.py+4 added
1+from flask import Flask2+app = Flask(__name__)3+4+import yourapplication.viewsadded:examples/patterns/largerapp/yourapplication/views.py+5 added
1+from yourapplication import app2+3+@app.route('/')4+def index():5+ return 'Hello World!'added:examples/patterns/largerapp/setup.py+10 added
1+from setuptools import setup2+3+setup(4+ name='yourapplication',5+ packages=['yourapplication'],6+ include_package_data=True,7+ install_requires=[8+ 'flask',9+ ],10+)deleted:examples/persona/static/persona.js-52 removed
1-$(function() {2- /* convert the links into clickable buttons that go to the3- persona service */4- $('a.signin').on('click', function() {5- navigator.id.request({6- siteName: 'Flask Persona Example'7- });8- return false;9- });10-11- $('a.signout').on('click', function() {12- navigator.id.logout();13- return false;14- });15-16- /* watch persona state changes */17- navigator.id.watch({18- loggedInUser: $CURRENT_USER,19- onlogin: function(assertion) {20- /* because the login needs to verify the provided assertion21- with the persona service which requires an HTTP request,22- this could take a bit. To not confuse the user we show23- a progress box */24- var box = $('<div class=signinprogress></div>')25- .hide()26- .text('Please wait ...')27- .appendTo('body')28- .fadeIn('fast');29- $.ajax({30- type: 'POST',31- url: $URL_ROOT + '_auth/login',32- data: {assertion: assertion},33- success: function(res, status, xhr) { window.location.reload(); },34- error: function(xhr, status, err) {35- box.remove();36- navigator.id.logout();37- alert('Login failure: ' + err);38- }39- });40- },41- onlogout: function() {42- $.ajax({43- type: 'POST',44- url: $URL_ROOT + '_auth/logout',45- success: function(res, status, xhr) { window.location.reload(); },46- error: function(xhr, status, err) {47- alert('Logout failure: ' + err);48- }49- });50- }51- });52-});deleted:examples/persona/static/spinner.pngbinary
A binary file, deleted.
deleted:examples/persona/static/style.css-39 removed
1-html {2- background: #eee;3-}4-5-body {6- font-family: 'Verdana', sans-serif;7- font-size: 15px;8- margin: 30px auto;9- width: 720px;10- background: white;11- padding: 30px;12-}13-14-h1 {15- margin: 0;16-}17-18-h1, h2, a {19- color: #d00;20-}21-22-div.authbar {23- background: #eee;24- padding: 0 15px;25- margin: 10px -15px;26- line-height: 25px;27- height: 25px;28- vertical-align: middle;29-}30-31-div.signinprogress {32- position: fixed;33- top: 0;34- left: 0;35- right: 0;36- bottom: 0;37- background: rgba(255, 255, 255, 0.8) url(spinner.png) center center no-repeat;38- font-size: 0;39-}deleted:examples/persona/templates/index.html-23 removed
1-{% extends "layout.html" %}2-{% block title %}Welcome{% endblock %}3-{% block body %}4- <h2>Welcome</h2>5- <p>6- This is a small example application that shows how to integrate7- Mozilla's persona signin service into a Flask application.8- <p>9- The advantage of persona over your own login system is that the10- password is managed outside of your application and you get11- a verified mail address as primary identifier for your user.12- <p>13- In this example nothing is actually stored on the server, it14- just takes over the email address from the persona verifier15- and stores it in a session.16- {% if g.user %}17- <p>18- You are now logged in as <strong>{{ g.user }}</strong>19- {% else %}20- <p>21- To sign in click the sign in button above.22- {% endif %}23-{% endblock %}deleted:examples/persona/templates/layout.html-27 removed
1-<!doctype html>2-<title>{% block title %}{% endblock %} | Flask Persona Example</title>3-<meta http-equiv="X-UA-Compatible" content="IE=Edge">4-<script src="{{ config.PERSONA_JS }}"></script>5-<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>6-<script>7- /* the url root is useful for doing HTTP requests */8- var $URL_ROOT = {{ request.url_root|tojson }};9-10- /* we store the current user here so that the persona11- javascript support knows about the current user */12- var $CURRENT_USER = {{ g.user|tojson }};13-</script>14-<script src="{{ url_for('static', filename='persona.js') }}"></script>15-<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">16-<header>17- <h1>Mozilla Persona Example</h1>18- <div class="authbar">19- {% if g.user %}20- Signed in as <em>{{ g.user }}</em>21- (<a href="#" class="signout">Sign out</a>)22- {% else %}23- Not signed in. <a href="#" class="signin">Sign in</a>24- {% endif %}25- </div>26-</header>27-{% block body %}{% endblock %}deleted:examples/persona/persona.py-55 removed
1-from flask import Flask, render_template, session, request, abort, g2-3-import requests4-5-6-app = Flask(__name__)7-app.config.update(8- DEBUG=True,9- SECRET_KEY='my development key',10- PERSONA_JS='https://login.persona.org/include.js',11- PERSONA_VERIFIER='https://verifier.login.persona.org/verify',12-)13-app.config.from_envvar('PERSONA_SETTINGS', silent=True)14-15-16-@app.before_request17-def get_current_user():18- g.user = None19- email = session.get('email')20- if email is not None:21- g.user = email22-23-24-@app.route('/')25-def index():26- """Just a generic index page to show."""27- return render_template('index.html')28-29-30-@app.route('/_auth/login', methods=['GET', 'POST'])31-def login_handler():32- """This is used by the persona.js file to kick off the33- verification securely from the server side. If all is okay34- the email address is remembered on the server.35- """36- resp = requests.post(app.config['PERSONA_VERIFIER'], data={37- 'assertion': request.form['assertion'],38- 'audience': request.host_url,39- }, verify=True)40- if resp.ok:41- verification_data = resp.json()42- if verification_data['status'] == 'okay':43- session['email'] = verification_data['email']44- return 'OK'45-46- abort(400)47-48-49-@app.route('/_auth/logout', methods=['POST'])50-def logout_handler():51- """This is what persona.js will call to sign the user52- out again.53- """54- session.clear()55- return 'OK'deleted:examples/persona/README.md-3 removed
1-A simple example for integrating [Persona](https://login.persona.org/) into a2-Flask application. In addition to Flask, it requires the3-[requests](www.python-requests.org/) library.modified:flask/__init__.py+2 added-2 removed
8 unmodified lines9 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11 """12 13-__version__ = '0.11.2-dev'13+__version__ = '0.13-dev'14 15 # utilities we import from Werkzeug and Jinja2 that are unused16 # in the module but are exported as public interface.17 from werkzeug.exceptions import abort21 unmodified lines39 # We're not exposing the actual json module but a convenient wrapper around40 # it.41 from . import json42 43-# This was the only thing that flask used to export at one point and it had43+# This was the only thing that Flask used to export at one point and it had44 # a more generic name.45 jsonify = json.jsonify46 47 # backwards compat, goes away in 1.02 unmodified linesmodified:flask/_compat.py+13 added-5 removed
63 unmodified lines64 return type.__new__(metaclass, 'temporary_class', (), {})65 66 67 # Certain versions of pypy have a bug where clearing the exception stack68-# breaks the __exit__ function in a very peculiar way. This is currently69-# true for pypy 2.2.1 for instance. The second level of exception blocks70-# is necessary because pypy seems to forget to check if an exception71-# happened until the next bytecode instruction?68+# breaks the __exit__ function in a very peculiar way. The second level of69+# exception blocks is necessary because pypy seems to forget to check if an70+# exception happened until the next bytecode instruction?71+#72+# Relevant PyPy bugfix commit:73+# https://bitbucket.org/pypy/pypy/commits/77ecf91c635a287e88e60d8ddb0f4e9df400330174+# According to ronan on #pypy IRC, it is released in PyPy2 2.3 and later75+# versions.76+#77+# Ubuntu 14.04 has PyPy 2.2.1, which does exhibit this bug.78 BROKEN_PYPY_CTXMGR_EXIT = False79 if hasattr(sys, 'pypy_version_info'):80 class _Mgr(object):81 def __enter__(self):82 return self83 def __exit__(self, *args):84+ if hasattr(sys, 'exc_clear'):85+ # Python 3 (PyPy3) doesn't have exc_clear78- sys.exc_clear()86+ sys.exc_clear()87 try:88 try:89 with _Mgr():90 raise AssertionError()6 unmodified linesmodified:flask/app.py+230 added-154 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 import os12 import sys13-from threading import Lock13 from datetime import timedelta15-from itertools import chain14 from functools import update_wrapper17-from collections import deque15+from itertools import chain16+from threading import Lock17 19-from werkzeug.datastructures import ImmutableDict20-from werkzeug.routing import Map, Rule, RequestRedirect, BuildError21-from werkzeug.exceptions import HTTPException, InternalServerError, \22- MethodNotAllowed, BadRequest, default_exceptions18+from werkzeug.datastructures import ImmutableDict, Headers19+from werkzeug.exceptions import BadRequest, HTTPException, \20+ InternalServerError, MethodNotAllowed, default_exceptions21+from werkzeug.routing import BuildError, Map, RequestRedirect, Rule22 24-from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \25- locked_cached_property, _endpoint_from_view_func, find_package, \26- get_debug_flag27-from . import json, cli28-from .wrappers import Request, Response29-from .config import ConfigAttribute, Config30-from .ctx import RequestContext, AppContext, _AppCtxGlobals31-from .globals import _request_ctx_stack, request, session, g23+from . import cli, json24+from ._compat import integer_types, reraise, string_types, text_type25+from .config import Config, ConfigAttribute26+from .ctx import AppContext, RequestContext, _AppCtxGlobals27+from .globals import _request_ctx_stack, g, request, session28+from .helpers import _PackageBoundObject, \29+ _endpoint_from_view_func, find_package, get_debug_flag, \30+ get_flashed_messages, locked_cached_property, url_for31 from .sessions import SecureCookieSessionInterface32+from .signals import appcontext_tearing_down, got_request_exception, \33+ request_finished, request_started, request_tearing_down34 from .templating import DispatchingJinjaLoader, Environment, \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 81 unmodified lines122 123 .. 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.176 unmodified lines323 'EXPLAIN_TEMPLATE_LOADING': False,324 'PREFERRED_URL_SCHEME': 'http',325 'JSON_AS_ASCII': True,326 'JSON_SORT_KEYS': True,318- 'JSONIFY_PRETTYPRINT_REGULAR': True,327+ 'JSONIFY_PRETTYPRINT_REGULAR': False,328 'JSONIFY_MIMETYPE': 'application/json',329 'TEMPLATES_AUTO_RELOAD': None,330 })331 14 unmodified lines346 #: .. versionadded:: 0.8347 session_interface = SecureCookieSessionInterface()348 349 def __init__(self, import_name, static_path=None, static_url_path=None,341- static_folder='static', template_folder='templates',350+ static_folder='static', static_host=None,351+ host_matching=False, template_folder='templates',352 instance_path=None, instance_relative_config=False,353 root_path=None):354 _PackageBoundObject.__init__(self, import_name,355 template_folder=template_folder,45 unmodified lines401 #: special key ``None`` points to a list of tuples where the first item402 #: is the class for the instance check and the second the error handler403 #: function.404 #:395- #: 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 a4 unmodified lines414 #:415 #: .. versionadded:: 0.9416 self.url_build_error_handlers = []417 408- #: A dictionary with lists of functions that should be called at the409- #: beginning of the request. The key of the dictionary is the name of410- #: the blueprint this function is active for, ``None`` for all requests.411- #: This can for example be used to open database connections or412- #: getting hold of the currently logged in user. To register a413- #: function here, use the :meth:`before_request` decorator.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 416- #: A lists of functions that should be called at the beginning of the417- #: first request to this instance. To register a function here, use418- #: the :meth:`before_first_request` decorator.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 23 unmodified lines455 #:456 #: .. versionadded:: 0.9457 self.teardown_appcontext_funcs = []458 450- #: A dictionary with lists of functions that can be used as URL451- #: value processor functions. Whenever a URL is built these functions452- #: are called to modify the dictionary of values in place. The key453- #: ``None`` here is used for application wide454- #: callbacks, otherwise the key is the name of the blueprint.455- #: Each of these functions has the chance to modify the 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 58 unmodified lines526 #: class ListConverter(BaseConverter):527 #: def to_python(self, value):528 #: return value.split(',')529 #: def to_url(self, values):522- #: 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 534- # register the static folder for the application. Do that even535- # if the folder does not exist. First of all it might be created536- # while the server is running (usually happens during development)537- # but also because google appengine stores static files somewhere538- # else when mapped with the .yml file.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>',541- 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 the267 unmodified lines824 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 to817- ``'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_simple829- if host is None:830- host = '127.0.0.1'831- if port is None:832- server_name = self.config['SERVER_NAME']833- if server_name and ':' in server_name:834- port = int(server_name.rsplit(':', 1)[1])835- else:836- port = 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)841- options.setdefault('passthrough_errors', True)860 try:861 run_simple(host, port, self, **options)862 finally:863 # reset the first request information if the development server846- # 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 868 def test_client(self, use_cookies=True, **kwargs):25 unmodified lines894 895 from flask.testing import FlaskClient896 897 class CustomClient(FlaskClient):880- def __init__(self, authentication=None, *args, **kwargs):881- FlaskClient.__init__(*args, **kwargs)882- self._authentication = authentication898+ 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 47 unmodified lines952 return self.session_interface.make_null_session(self)953 954 @setupmethod955 def register_blueprint(self, blueprint, **options):938- """Register a blueprint on the application. For information about 939- blueprints head over to :ref:`blueprints`.956+ """Registers a blueprint on the application.957 941- The blueprint name is passed in as the first argument. 942- Options are passed as additional keyword arguments and forwarded to 943- `blueprints` in an "options" dictionary.944-945- :param subdomain: set a subdomain for the blueprint946- :param url_prefix: set the prefix for all URLs defined on the blueprint.947- ``(url_prefix='/<lang code>')``948- :param url_defaults: a dictionary with URL defaults that is added to 949- each and every URL defined with this blueprint950- :param static_folder: add a static folder to urls in this blueprint951- :param static_url_path: add a static url path to urls in this blueprint952- :param template_folder: set an alternate template folder953- :param root_path: set an alternate root path for this blueprint954-958 .. versionadded:: 0.7959 """960 first_registration = False961 if blueprint.name in self.blueprints:15 unmodified lines977 """978 return iter(self._blueprint_order)979 980 @setupmethod978- 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 31 unmodified lines1017 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 limited21 unmodified lines1050 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:1047- provide_automatic_options = getattr(view_func,1048- '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 = True77 unmodified lines1138 return exc_class, None1139 1140 @setupmethod1141 def errorhandler(self, code_or_exception):1134- """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):29 unmodified lines1176 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 1172- :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 f125 unmodified lines1311 1312 @setupmethod1313 def before_request(self, f):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 1307- The function will be called without any arguments.1308- If the function returns a non-None value, it's handled as1309- if it was the return value from the view and further1310- request handling is stopped.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 47 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 1366- 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 54 unmodified lines1436 return f1437 1438 @setupmethod1439 def url_value_preprocessor(self, f):1429- """Registers a function as URL value preprocessor for all view1430- functions of the application. It's called before the view functions1431- 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 15 unmodified lines1470 1471 def find_handler(handler_map):1472 if not handler_map:1473 return1455- queue = deque(exc_class.__mro__)1456- # Protect from geniuses who might create circular references in1457- # __mro__1458- done = set()1459-1460- while queue:1461- cls = queue.popleft()1462- if cls in done:1463- continue1464- done.add(cls)1474+ for cls in exc_class.__mro__:1475 handler = handler_map.get(cls)1476 if handler is not None:1477 # cache for next time exc_class is raised1478 handler_map[exc_class] = handler1479 return handler1480 1471- queue.extend(cls.__mro__)1472-1481 # try blueprint handlers1482 handler = find_handler(self.error_handler_spec1483 .get(request.blueprint, {})1484 .get(code))93 unmodified lines1578 1579 self.log_exception((exc_type, exc_value, tb))1580 if handler is None:1581 return InternalServerError()1574- 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:1643- response = self.process_response(response)1644- 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 triggers44 unmodified lines1722 """1723 return False1724 1725 def make_response(self, rv):1697- """Converts the return value from a view function to a real1698- 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 1700- 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 1702- .. 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 1704- ======================= ===========================================1705- :attr:`response_class` the object is returned unchanged1706- :class:`str` a response object is created with the1707- string as body1708- :class:`unicode` a response object is created with the1709- string encoded to utf-8 as body1710- a WSGI function the function is called as WSGI application1711- and buffered as response object1712- :class:`tuple` A tuple in the form ``(response, status,1713- headers)`` or ``(response, headers)``1714- where `response` is any of the1715- types defined here, `status` is a string1716- or an integer and `headers` is a list or1717- a dictionary with header values.1718- ======================= ===========================================1719-1720- :param rv: the return value from the view function1721-1760 .. versionchanged:: 0.91761 Previously a tuple was interpreted as the arguments for the1762 response object.1763 """1726- status_or_headers = headers = None1727- if isinstance(rv, tuple):1728- rv, status_or_headers, headers = rv + (None,) * (3 - len(rv))1764 1730- if rv is None:1731- raise ValueError('View function did not return a response')1765+ status = headers = None1766 1733- if isinstance(status_or_headers, (dict, list)):1734- 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):1737- # When we create a response object directly, we let the constructor1738- # set the headers and status. We do this because there can be1739- # some extra logic involved when creating these objects with1740- # specific values (like default content type selection).1798 if isinstance(rv, (text_type, bytes, bytearray)):1742- rv = self.response_class(rv, headers=headers,1743- status=status_or_headers)1744- 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:1746- 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 provided1748- if status_or_headers is not None:1749- if isinstance(status_or_headers, string_types):1750- rv.status = status_or_headers1819+ if status is not None:1820+ if isinstance(status, (text_type, bytes, bytearray)):1821+ rv.status = status1822 else:1752- 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 rv54 unmodified lines1884 reraise(exc_type, exc_value, tb)1885 raise error1886 1887 def preprocess_request(self):1815- """Called before the actual request dispatching and will1816- call each :meth:`before_request` decorated function, passing no1817- arguments.1818- If any of these functions returns a value, it's handled as1819- if it was the return value from the view and further1820- request handling is stopped.1821-1822- This also triggers the :meth:`url_value_processor` functions before1823- 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:151 unmodified lines2053 a list of headers and an optional2054 exception context to start the response2055 """2056 ctx = self.request_context(environ)1984- ctx.push()2057 error = None2058 try:2059 try:2060+ ctx.push()2061 response = self.full_dispatch_request()2062 except Exception as e:2063 error = e1991- 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 = None11 unmodified linesmodified:flask/blueprints.py+7 added
87 unmodified lines88 89 warn_on_modifications = False90 _got_registered_once = False91 92+ #: Blueprint local JSON decoder class to use.93+ #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_encoder`.94+ json_encoder = None95+ #: Blueprint local JSON decoder class to use.96+ #: Set to ``None`` to use the app's :class:`~flask.app.Flask.json_decoder`.97+ json_decoder = None98+99 def __init__(self, name, import_name, static_folder=None,100 static_url_path=None, template_folder=None,101 url_prefix=None, subdomain=None, url_defaults=None,102 root_path=None):318 unmodified linesmodified:flask/cli.py+84 added-9 removed
9 unmodified lines10 """11 12 import os13 import sys14-from threading import Lock, Thread14+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_flag21-from . import __version__25 26+27 class NoAppException(click.UsageError):28 """Raised if an application cannot be found or loaded."""29 30 58 unmodified lines89 else:90 module = app_id91 app_obj = None92 93+ try:89- __import__(module)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:30 unmodified lines142 callback=get_version,143 is_flag=True, is_eager=True)144 145 class DispatchingApp(object):128- """Special application that dispatches to a flask application which146+ """Special application that dispatches to a Flask application which147 is imported by name in a background thread. If an error happens130- it is is recorded and shows as part of the WSGI handling which in case148+ 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):150 unmodified lines303 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.289- :param add_version_option: adds the :option:`--version` option.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 9 unmodified lines321 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):44 unmodified lines374 # 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.359- pass378+ # 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')35 unmodified lines420 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:2 unmodified lines437 eager_loading = not reload438 439 app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)440 413- # Extra startup messages. This depends a but on Werkzeug internals to441+ # 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 an41 unmodified lines487 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 466-It loads the application configured (either through the FLASK_APP environment541+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.35 unmodified linesmodified:flask/config.py+1 added-1 removed
124 unmodified lines125 filename = os.path.join(self.root_path, filename)126 d = types.ModuleType('config')127 d.__file__ = filename128 try:129- with open(filename) as config_file:129+ with open(filename, mode='rb') as config_file:130 exec(compile(config_file.read(), filename, 'exec'), d.__dict__)131 except IOError as e:132 if silent and e.errno in (errno.ENOENT, errno.EISDIR):133 return False130 unmodified linesmodified:flask/debughelpers.py+12 added
6 unmodified lines7 8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11+import os12+from warnings import warn13+14 from ._compat import implements_to_string, text_type15 from .app import Flask16 from .blueprints import Blueprint17 from .globals import _request_ctx_stack137 unmodified lines155 info.append(' Maybe you did not place a template in the right folder?')156 info.append(' See http://flask.pocoo.org/docs/blueprints/#templates')157 158 app.logger.info('\n'.join(info))159+160+161+def explain_ignored_app_run():162+ if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':163+ warn(Warning('Silently ignoring app.run() because the '164+ 'application is run from the flask command line '165+ 'executable. Consider putting app.run() behind an '166+ 'if __name__ == "__main__" guard to silence this '167+ 'warning.'), stacklevel=3)modified:flask/helpers.py+122 added-40 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 12 import os13+import socket14 import sys15 import pkgutil16 import posixpath17 import mimetypes18 from time import time19 from zlib import adler3220 from threading import RLock21+import unicodedata22 from werkzeug.routing import BuildError23 from functools import update_wrapper24 25 try:26 from werkzeug.urls import url_quote27 except ImportError:28 from urlparse import quote as url_quote29 28-from werkzeug.datastructures import Headers29-from werkzeug.exceptions import BadRequest, NotFound30+from werkzeug.datastructures import Headers, Range31+from werkzeug.exceptions import BadRequest, NotFound, \32+ RequestedRangeNotSatisfiable33 34 # this was moved in 0.735 try:36 from werkzeug.wsgi import wrap_file4 unmodified lines41 42 from .signals import message_flashed43 from .globals import session, _request_ctx_stack, _app_ctx_stack, \44 current_app, request42-from ._compat import string_types, text_type, PY245+from ._compat import string_types, text_type46 47 48 # sentinel49 _missing = object()9 unmodified lines59 def get_debug_flag(default=None):60 val = os.environ.get('FLASK_DEBUG')61 if not val:62 return default60- return val not in ('0', 'false', 'no')63+ return val.lower() not in ('0', 'false', 'no')64 65 66 def _endpoint_from_view_func(view_func):67 """Internal helper that returns the default endpoint for a given263 unmodified lines331 # deal with that sort of stuff.332 values['_external'] = external333 values['_anchor'] = anchor334 values['_method'] = method335+ values['_scheme'] = scheme336 return appctx.app.handle_url_build_error(error, endpoint, values)337 338 if anchor is not None:339 rv += '#' + url_quote(anchor)100 unmodified lines440 you can set the application's :attr:`~Flask.use_x_sendfile` attribute441 to ``True`` to directly emit an ``X-Sendfile`` header. This however442 requires support of the underlying webserver for ``X-Sendfile``.443 440- You must explicitly provide the mimetype for the filename or file object.444+ By default it will try to guess the mimetype for you, but you can445+ also explicitly provide one. For extra security you probably want446+ to send certain files as attachment (HTML for instance). The mimetype447+ guessing requires a `filename` or an `attachment_filename` to be448+ provided.449 450+ ETags will also be attached automatically if a `filename` is provided. You451+ can turn this off by setting `add_etags=False`.452+453+ If `conditional=True` and `filename` is provided, this method will try to454+ upgrade the response stream to support range requests. This will allow455+ the request to be answered with partial content response.456+457 Please never pass filenames to this function from user sources;458 you should use :func:`send_from_directory` instead.459 460 .. versionadded:: 0.211 unmodified lines472 .. versionchanged:: 0.9473 cache_timeout pulls its default from application config, when None.474 475 .. versionchanged:: 0.12461- mimetype guessing and etag support removed for file objects.462- If no mimetype or attachment_filename is provided, application/octet-stream463- will be used.476+ The filename is no longer automatically inferred from file objects. If477+ you want to use automatic mimetype and etag support, pass a filepath via478+ `filename_or_fp` or `attachment_filename`.479 480+ .. versionchanged:: 0.12481+ The `attachment_filename` is preferred over `filename` for MIME-type482+ detection.483+ 484+ .. versionchanged:: 0.13485+ UTF-8 filenames, as specified in `RFC 2231`_, are supported.486+ 487+ .. _RFC 2231: https://tools.ietf.org/html/rfc2231#section-4488+465- :param filename_or_fp: the filename of the file to send in `latin-1`.489+ :param filename_or_fp: the filename of the file to send.490 This is relative to the :attr:`~Flask.root_path`491 if a relative path is specified.492 Alternatively a file object might be provided in493 which case ``X-Sendfile`` might not work and fall494 back to the traditional method. Make sure that the495 file pointer is positioned at the start of data to496 send before calling :func:`send_file`.473- :param mimetype: the mimetype of the file if provided, otherwise474- auto detection happens.497+ :param mimetype: the mimetype of the file if provided. If a file path is498+ given, auto detection happens as fallback, otherwise an499+ error will be raised.500 :param as_attachment: set to ``True`` if you want to send this file with501 a ``Content-Disposition: attachment`` header.502 :param attachment_filename: the filename for the attachment if it503 differs from the file's filename.8 unmodified lines512 a :class:`~datetime.datetime` or timestamp.513 If a file was passed, this overrides its mtime.514 """515 mtime = None516+ fsize = None517 if isinstance(filename_or_fp, string_types):518 filename = filename_or_fp519+ if not os.path.isabs(filename):520+ filename = os.path.join(current_app.root_path, filename)521 file = None522+ if attachment_filename is None:523+ attachment_filename = os.path.basename(filename)524 else:525 file = filename_or_fp496- filename = getattr(file, 'name', None)526+ filename = None527 498- if filename is not None:499- if not os.path.isabs(filename):500- filename = os.path.join(current_app.root_path, filename)501- if mimetype is None and (filename or attachment_filename):502- mimetype = mimetypes.guess_type(filename or attachment_filename)[0]528 if mimetype is None:529+ if attachment_filename is not None:530+ mimetype = mimetypes.guess_type(attachment_filename)[0] \504- mimetype = 'application/octet-stream'531+ or 'application/octet-stream'532 533+ if mimetype is None:534+ raise ValueError(535+ 'Unable to infer MIME-type because no filename is available. '536+ 'Please set either `attachment_filename`, pass a filepath to '537+ '`filename_or_fp` or set your own MIME-type via `mimetype`.'538+ )539+540 headers = Headers()541 if as_attachment:542 if attachment_filename is None:509- if filename is None:510- raise TypeError('filename unavailable, required for '511- 'sending as attachment')543+ raise TypeError('filename unavailable, required for '544+ 'sending as attachment')512- attachment_filename = os.path.basename(filename)513- headers.add('Content-Disposition', 'attachment',514- filename=attachment_filename)545 546+ try:547+ attachment_filename = attachment_filename.encode('latin-1')548+ except UnicodeEncodeError:549+ filenames = {550+ 'filename': unicodedata.normalize(551+ 'NFKD', attachment_filename).encode('latin-1', 'ignore'),552+ 'filename*': "UTF-8''%s" % url_quote(attachment_filename),553+ }554+ else:555+ filenames = {'filename': attachment_filename}556+557+ headers.add('Content-Disposition', 'attachment', **filenames)558+559 if current_app.use_x_sendfile and filename:560 if file is not None:561 file.close()562 headers['X-Sendfile'] = filename520- headers['Content-Length'] = os.path.getsize(filename)563+ fsize = os.path.getsize(filename)564+ headers['Content-Length'] = fsize565 data = None566 else:567 if file is None:568 file = open(filename, 'rb')569 mtime = os.path.getmtime(filename)526- headers['Content-Length'] = os.path.getsize(filename)570+ fsize = os.path.getsize(filename)571+ headers['Content-Length'] = fsize572 data = wrap_file(request.environ, file)573 574 rv = current_app.response_class(data, mimetype=mimetype, headers=headers,575 direct_passthrough=True)9 unmodified lines585 if cache_timeout is not None:586 rv.cache_control.max_age = cache_timeout587 rv.expires = int(time() + cache_timeout)588 544- if add_etags and filename is not None and file is None:589+ if add_etags and filename is not None:590 from warnings import warn591 592 try:593 rv.set_etag('%s-%s-%s' % (7 unmodified lines601 except OSError:602 warn('Access %s failed, maybe it does not exist, so ignore etags in '603 'headers' % filename, stacklevel=2)604 560- if conditional:605+ if conditional:606+ if callable(getattr(Range, 'to_content_range_header', None)):607+ # Werkzeug supports Range Requests608+ # Remove this test when support for Werkzeug <0.12 is dropped609+ try:610+ rv = rv.make_conditional(request, accept_ranges=True,611+ complete_length=fsize)612+ except RequestedRangeNotSatisfiable:613+ file.close()614+ raise615+ else:616 rv = rv.make_conditional(request)562- # make sure we don't send x-sendfile for servers that563- # ignore the 304 status code for x-sendfile.564- if rv.status_code == 304:565- rv.headers.pop('x-sendfile', None)617+ # make sure we don't send x-sendfile for servers that618+ # ignore the 304 status code for x-sendfile.619+ if rv.status_code == 304:620+ rv.headers.pop('x-sendfile', None)621 return rv622 623 624 def safe_join(directory, *pathnames):12 unmodified lines637 :param pathnames: the untrusted pathnames relative to that directory.638 :raises: :class:`~werkzeug.exceptions.NotFound` if one or more passed639 paths fall out of its boundaries.640 """641+642+ parts = [directory]643+644 for filename in pathnames:645 if filename != '':646 filename = posixpath.normpath(filename)589- for sep in _os_alt_seps:590- if sep in filename:591- raise NotFound()592- if os.path.isabs(filename) or \593- filename == '..' or \594- filename.startswith('../'):647+648+ if (649+ any(sep in filename for sep in _os_alt_seps)650+ or os.path.isabs(filename)651+ or filename == '..'652+ or filename.startswith('../')653+ ):654 raise NotFound()596- directory = os.path.join(directory, filename)597- return directory655 656+ parts.append(filename)657 658+ return posixpath.join(*parts)659+660+661 def send_from_directory(directory, filename, **options):662 """Send a file from a given directory with :func:`send_file`. This663 is a secure way to quickly expose static files from an upload folder664 or something similar.317 unmodified lines982 :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+22 added-14 removed
1 # -*- coding: utf-8 -*-2 """3- flask.jsonimpl4- ~~~~~~~~~~~~~~3+ flask.json4+ ~~~~~~~~~~5 6 Implementation helpers for the JSON support in Flask.7 8 :copyright: (c) 2015 by Armin Ronacher.9 unmodified lines18 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.63 unmodified lines90 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 124 unmodified lines247 .. 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 242- This function's response will be pretty printed if it was not requested243- with ``X-Requested-With: XMLHttpRequest`` to simplify debugging unless244- the ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to false.245- Compressed (not pretty) formatting currently means no indents and no246- spaces after separators.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 = None260 separators = (',', ':')261 254- if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and not request.is_xhr:262+ if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug:263 indent = 2264 separators = (', ', ': ')265 266 if args and kwargs:14 unmodified linesmodified:flask/logging.py+4 added
85 unmodified lines86 del logger.handlers[:]87 logger.__class__ = DebugLogger88 logger.addHandler(debug_handler)89 logger.addHandler(prod_handler)90+91+ # Disable propagation by default92+ logger.propagate = False93+94 return loggermodified:flask/sessions.py+124 added-61 removed
9 unmodified lines10 """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_type20-from .helpers import total_seconds21+from .helpers import total_seconds, is_ip22 23 from itsdangerous import URLSafeTimedSerializer, BadSignature24 25 22 unmodified lines48 #: long as changes do not happen on mutable structures in the session.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:54+ #: Cookie` header to the response if the session is being accessed. This55+ #: allows caching proxy servers, like Varnish, to use both the URL and the56+ #: 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]}28 unmodified lines91 92 def dumps(self, value):93 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))92- if the_key == ' t':93- return tuple(the_value)94- elif the_key == ' u':95- return uuid.UUID(the_value)96- elif the_key == ' b':97- return b64decode(the_value)98- elif the_key == ' m':99- return Markup(the_value)100- elif the_key == ' d':101- return parse_date(the_value)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 5 unmodified lines123 124 def __init__(self, initial=None):125 def on_update(self):126 self.modified = True115- CallbackDict.__init__(self, initial, on_update)127+ self.accessed = True128+129+ super(SecureCookieSession, self).__init__(initial, on_update)130 self.modified = False131+ self.accessed = False132 133+ def __getitem__(self, key):134+ self.accessed = True135+ return super(SecureCookieSession, self).__getitem__(key)136 137+ def get(self, key, default=None):138+ self.accessed = True139+ return super(SecureCookieSession, self).get(key, default)140+141+ def setdefault(self, key, default=None):142+ self.accessed = True143+ return super(SecureCookieSession, self).setdefault(key, default)144+145+146 class NullSession(SecureCookieSession):147 """Class used to generate nicer error messages if sessions are not148 available. Will still allow read-only access to the empty session149 but fail on setting.44 unmodified lines194 #: this type.195 null_session_class = NullSession196 197 #: A flag that indicates if the session interface is pickle based.171- #: This can be used by flask extensions to make a decision in regards198+ #: This can be used by Flask extensions to make a decision in regards199 #: to how to deal with the session object.200 #:201 #: .. versionadded:: 0.10202 pickle_based = False19 unmodified lines222 """223 return isinstance(obj, self.null_session_class)224 225 def get_cookie_domain(self, app):199- """Helpful helper method that returns the cookie domain that should200- be used for the session cookie if session cookies are used.226+ """Returns the domain that should be set for the session cookie.227+ 228+ Uses ``SESSION_COOKIE_DOMAIN`` if it is configured, otherwise229+ falls back to detecting the domain based on ``SERVER_NAME``.230+ 231+ Once detected (or if not set at all), ``SESSION_COOKIE_DOMAIN`` is232+ updated to avoid re-running the logic.233 """202- if app.config['SESSION_COOKIE_DOMAIN'] is not None:203- return app.config['SESSION_COOKIE_DOMAIN']204- if app.config['SERVER_NAME'] is not None:205- # chop off the port which is usually not supported by browsers206- rv = '.' + app.config['SERVER_NAME'].rsplit(':', 1)[0]234 208- # Google chrome does not like cookies set to .localhost, so209- # we just go with no domain then. Flask documents anyways that210- # cross domain cookies need a fully qualified domain name211- if rv == '.localhost':212- rv = None235+ rv = app.config['SESSION_COOKIE_DOMAIN']236 214- # If we infer the cookie domain from the server name we need215- # to check if we are in a subpath. In that case we can't216- # set a cross domain cookie.217- if rv is not None:218- path = self.get_cookie_path(app)219- if path != '/':220- rv = rv.lstrip('.')237+ # set explicitly, or cached from SERVER_NAME detection238+ # if False, return None239+ if rv is not None:240+ return rv if rv else None241 222- return rv242+ rv = app.config['SERVER_NAME']243 244+ # server name not set, cache False to return none next time245+ if not rv:246+ app.config['SESSION_COOKIE_DOMAIN'] = False247+ return None248+249+ # chop off the port which is usually not supported by browsers250+ # remove any leading '.' since we'll add that later251+ rv = rv.rsplit(':', 1)[0].lstrip('.')252+253+ if '.' not in rv:254+ # Chrome doesn't allow names without a '.'255+ # this should only come up with localhost256+ # hack around this by not setting the name, and show a warning257+ warnings.warn(258+ '"{rv}" is not a valid cookie domain, it must contain a ".".'259+ ' Add an entry to your hosts file, for example'260+ ' "{rv}.localdomain", and use that instead.'.format(rv=rv)261+ )262+ app.config['SESSION_COOKIE_DOMAIN'] = False263+ return None264+265+ ip = is_ip(rv)266+267+ if ip:268+ warnings.warn(269+ 'The session cookie domain is an IP address. This may not work'270+ ' as intended in some browsers. Add an entry to your hosts'271+ ' file, for example "localhost.localdomain", and use that'272+ ' instead.'273+ )274+275+ # if this is not an ip and app is mounted at the root, allow subdomain276+ # matching by adding a '.' prefix277+ if self.get_cookie_path(app) == '/' and not ip:278+ rv = '.' + rv279+280+ app.config['SESSION_COOKIE_DOMAIN'] = rv281+ return rv282+283 def get_cookie_path(self, app):284 """Returns the path for which the cookie should be valid. The285 default implementation uses the value from the ``SESSION_COOKIE_PATH``286 config var if it's set, and falls back to ``APPLICATION_ROOT`` or24 unmodified lines311 if session.permanent:312 return datetime.utcnow() + app.permanent_session_lifetime313 314 def should_set_cookie(self, app, session):256- """Indicates whether a cookie should be set now or not. This is257- used by session backends to figure out if they should emit a258- set-cookie header or not. The default behavior is controlled by259- the ``SESSION_REFRESH_EACH_REQUEST`` config variable. If260- it's set to ``False`` then a cookie is only set if the session is261- modified, if set to ``True`` it's always set if the session is262- permanent.315+ """Used by session backends to determine if a ``Set-Cookie`` header316+ should be set for this session cookie for this response. If the session317+ has been modified, the cookie is set. If the session is permanent and318+ the ``SESSION_REFRESH_EACH_REQUEST`` config is true, the cookie is319+ always set.320+ 321+ This check is usually skipped if the session was deleted.322 264- This check is usually skipped if sessions get deleted.265-323 .. versionadded:: 0.11324 """268- if session.modified:269- return True270- save_each = app.config['SESSION_REFRESH_EACH_REQUEST']271- return save_each and session.permanent325 326+ return session.modified or (327+ session.permanent and app.config['SESSION_REFRESH_EACH_REQUEST']328+ )329+330 def open_session(self, app, request):331 """This method has to be implemented and must either return ``None``332 in case the loading failed because of a configuration error or an333 instance of a session object which implements a dictionary like56 unmodified lines390 def save_session(self, app, session, response):391 domain = self.get_cookie_domain(app)392 path = self.get_cookie_path(app)393 337- # Delete case. If there is no session we bail early.338- # If the session was modified to be empty we remove the339- # whole cookie.394+ # If the session is modified to be empty, remove the cookie.395+ # If the session is empty, return without setting the cookie.396 if not session:397 if session.modified:342- response.delete_cookie(app.session_cookie_name,343- domain=domain, path=path)398+ response.delete_cookie(399+ app.session_cookie_name,400+ domain=domain,401+ path=path402+ )403+404 return405 346- # Modification case. There are upsides and downsides to347- # emitting a set-cookie header each request. The behavior348- # is controlled by the :meth:`should_set_cookie` method349- # which performs a quick check to figure out if the cookie350- # should be set or not. This is controlled by the351- # SESSION_REFRESH_EACH_REQUEST config flag as well as352- # the permanent flag on the session itself.406+ # Add a "Vary: Cookie" header if the session was accessed at all.407+ if session.accessed:408+ response.headers.add('Vary', 'Cookie')409+410 if not self.should_set_cookie(app, session):411 return412 413 httponly = self.get_cookie_httponly(app)414 secure = self.get_cookie_secure(app)415 expires = self.get_expiration_time(app, session)416 val = self.get_signing_serializer(app).dumps(dict(session))360- response.set_cookie(app.session_cookie_name, val,361- expires=expires, httponly=httponly,362- domain=domain, path=path, secure=secure)417+ response.set_cookie(418+ app.session_cookie_name,419+ val,420+ expires=expires,421+ httponly=httponly,422+ domain=domain,423+ path=path,424+ secure=secure425+ )modified:flask/signals.py+1 added-1 removed
35 unmodified lines36 connect = disconnect = has_receivers_for = receivers_for = \37 temporarily_connected_to = connected_to = _fail38 del _fail39 40-# The namespace for code signals. If you are not flask code, do40+# The namespace for code signals. If you are not Flask code, do41 # not put signals in here. Create your own namespace instead.42 _signals = Namespace()43 44 12 unmodified linesmodified:flask/testing.py+14 added
8 unmodified lines9 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11 """12 13+import werkzeug14 from contextlib import contextmanager15 from werkzeug.test import Client, EnvironBuilder16 from flask import _request_ctx_stack17 25 unmodified lines43 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):66 """When used in combination with a ``with`` statement this opens a67 session transaction. This can be used to modify the session that45 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+22 added-18 removed
101 unmodified lines102 return view103 104 105 class MethodViewType(type):106+ """Metaclass for :class:`MethodView` that determines what methods the view107+ defines.108+ """109 107- def __new__(cls, name, bases, d):108- rv = type.__new__(cls, name, bases, d)110+ def __init__(cls, name, bases, d):111+ super(MethodViewType, cls).__init__(name, bases, d)112+113 if 'methods' not in d:110- methods = set(rv.methods or [])111- for key in d:112- if key in http_method_funcs:114+ methods = set()115+116+ for key in http_method_funcs:117+ if hasattr(cls, key):118 methods.add(key.upper())114- # If we have no method at all in there we don't want to115- # add a method list. (This is for instance the case for116- # the base class or another subclass of a base method view117- # that does not introduce new methods).119+120+ # If we have no method at all in there we don't want to add a121+ # method list. This is for instance the case for the base class122+ # or another subclass of a base method view that does not introduce123+ # new methods.124 if methods:119- rv.methods = sorted(methods)120- return rv125+ cls.methods = methods126 127 128 class MethodView(with_metaclass(MethodViewType, View)):124- """Like a regular class-based view but that dispatches requests to125- particular methods. For instance if you implement a method called126- :meth:`get` it means you will response to ``'GET'`` requests and127- the :meth:`dispatch_request` implementation will automatically128- forward your request to that. Also :attr:`options` is set for you129- automatically::129+ """A class-based view that dispatches request methods to the corresponding130+ class methods. For example, if you implement a ``get`` method, it will be131+ used to handle ``GET`` requests. ::132 133 class CounterAPI(MethodView):132-134 def get(self):135 return session.get('counter', 0)136 137 def post(self):1 unmodified line139 return 'OK'140 141 app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))142 """143+144 def dispatch_request(self, *args, **kwargs):145 meth = getattr(self, request.method.lower(), None)146+147 # If the request method is HEAD and we don't have a handler for it148 # retry with GET.149 if meth is None and request.method == 'HEAD':150 meth = getattr(self, 'get', None)151+152 assert meth is not None, 'Unimplemented method %r' % request.method153 return meth(*args, **kwargs)modified:flask/wrappers.py+2 added-1 removed
135 unmodified lines136 :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.140- if rv is not _missing:141+ if cache and rv is not _missing:142 return rv143 144 if not (force or self.is_json):145 return None60 unmodified linesmodified:scripts/flask-07-upgrade.py+1 added-1 removed
3 unmodified lines4 flask-07-upgrade5 ~~~~~~~~~~~~~~~~6 7 This command line script scans a whole application tree and attempts to8- output an unified diff with all the changes that are necessary to easily8+ output a unified diff with all the changes that are necessary to easily9 upgrade the application to 0.7 and to not yield deprecation warnings.10 11 This will also attempt to find `after_request` functions that don't modify12 the response and appear to be better suited for `teardown_request`.286 unmodified linesadded:tests/test_apps/cliapp/importerrorapp.py+7 added
1+from __future__ import absolute_import, print_function2+3+from flask import Flask4+5+raise ImportError()6+7+testapp = Flask('testapp')modified:tests/test_basic.py+316 added-50 removed
48 unmodified lines49 rv = app.test_client().open('/', method='OPTIONS')50 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']51 52 53-def test_options_handling_disabled():53+def test_provide_automatic_options_attr():54 app = flask.Flask(__name__)55 56 def index():57 return 'Hello World!'11 unmodified lines69 rv = app.test_client().open('/', method='OPTIONS')70 assert sorted(rv.allow) == ['OPTIONS']71 72 73+def test_provide_automatic_options_kwarg():74+ app = flask.Flask(__name__)75+76+ def index():77+ return flask.request.method78+79+ def more():80+ return flask.request.method81+82+ app.add_url_rule('/', view_func=index, provide_automatic_options=False)83+ app.add_url_rule(84+ '/more', view_func=more, methods=['GET', 'POST'],85+ provide_automatic_options=False86+ )87+88+ c = app.test_client()89+ assert c.get('/').data == b'GET'90+91+ rv = c.post('/')92+ assert rv.status_code == 40593+ assert sorted(rv.allow) == ['GET', 'HEAD']94+95+ # Older versions of Werkzeug.test.Client don't have an options method96+ if hasattr(c, 'options'):97+ rv = c.options('/')98+ else:99+ rv = c.open('/', method='OPTIONS')100+101+ assert rv.status_code == 405102+103+ rv = c.head('/')104+ assert rv.status_code == 200105+ assert not rv.data # head truncates106+ assert c.post('/more').data == b'POST'107+ assert c.get('/more').data == b'GET'108+109+ rv = c.delete('/more')110+ assert rv.status_code == 405111+ assert sorted(rv.allow) == ['GET', 'HEAD', 'POST']112+113+ if hasattr(c, 'options'):114+ rv = c.options('/more')115+ else:116+ rv = c.open('/more', method='OPTIONS')117+118+ assert rv.status_code == 405119+120+121 def test_request_dispatching():122 app = flask.Flask(__name__)123 124 @app.route('/')225 unmodified lines350 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):22 unmodified lines416 417 client = app.test_client()418 rv = client.get('/')419 assert 'set-cookie' in rv.headers336- match = re.search(r'\bexpires=([^;]+)(?i)', rv.headers['set-cookie'])420+ 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.month103 unmodified lines528 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')537+ def set_session():538+ flask.session['test'] = 'test'539+ return ''540+541+ @app.route('/get')542+ def get():543+ return flask.session.get('test')544+545+ @app.route('/getitem')546+ def getitem():547+ return flask.session['test']548+549+ @app.route('/setdefault')550+ def setdefault():551+ return flask.session.setdefault('test', 'default')552+553+ @app.route('/no-vary-header')554+ def no_vary_header():555+ return ''556+557+ c = app.test_client()558+559+ def expect(path, header=True):560+ rv = c.get(path)561+562+ if header:563+ assert rv.headers['Vary'] == 'Cookie'564+ else:565+ assert 'Vary' not in rv.headers566+567+ expect('/set')568+ expect('/get')569+ expect('/getitem')570+ expect('/setdefault')571+ expect('/no-vary-header', False)572+573+574 def test_flashes():575 app = flask.Flask(__name__)576 app.secret_key = 'testkey'577 315 unmodified lines893 assert rv.status_code == 403894 assert b'forbidden' == rv.data895 896 897+def test_error_handling_processing():898+ app = flask.Flask(__name__)899+ app.config['LOGGER_HANDLER_POLICY'] = 'never'900+901+ @app.errorhandler(500)902+ def internal_server_error(e):903+ return 'internal server error', 500904+905+ @app.route('/')906+ def broken_func():907+ 1 // 0908+909+ @app.after_request910+ def after_request(resp):911+ resp.mimetype = 'text/x-special'912+ return resp913+914+ with app.test_client() as c:915+ resp = c.get('/')916+ assert resp.mimetype == 'text/x-special'917+ assert resp.data == b'internal server error'918+919+920+def test_baseexception_error_handling():921+ app = flask.Flask(__name__)922+ app.config['LOGGER_HANDLER_POLICY'] = 'never'923+924+ @app.route('/')925+ def broken_func():926+ raise KeyboardInterrupt()927+928+ with app.test_client() as c:929+ with pytest.raises(KeyboardInterrupt):930+ c.get('/')931+932+ ctx = flask._request_ctx_stack.top933+ assert ctx.preserved934+ assert type(ctx._preserved_exc) is KeyboardInterrupt935+936+937 def test_before_request_and_routing_errors():938 app = flask.Flask(__name__)939 940 @app.before_request111 unmodified lines1052 assert 'no file contents were transmitted' in str(e.value)1053 assert 'This was submitted: "index.txt"' in str(e.value)1054 1055 890-def test_response_creation():1056+def test_response_types():1057 app = flask.Flask(__name__)1058+ app.testing = True1059 893- @app.route('/unicode')894- def from_unicode():1060+ @app.route('/text')1061+ def from_text():1062 return u'Hällo Wörld'1063 897- @app.route('/string')898- def from_string():1064+ @app.route('/bytes')1065+ def from_bytes():1066 return u'Hällo Wörld'.encode('utf-8')1067 901- @app.route('/args')902- def from_tuple():1068+ @app.route('/full_tuple')1069+ def from_full_tuple():1070 return 'Meh', 400, {1071 'X-Foo': 'Testing',1072 'Content-Type': 'text/plain; charset=utf-8'1073 }1074 908- @app.route('/two_args')909- def from_two_args_tuple():1075+ @app.route('/text_headers')1076+ def from_text_headers():1077 return 'Hello', {1078 'X-Foo': 'Test',1079 'Content-Type': 'text/plain; charset=utf-8'1080 }1081 915- @app.route('/args_status')916- def from_status_tuple():1082+ @app.route('/text_status')1083+ def from_text_status():1084 return 'Hi, status!', 4001085 919- @app.route('/args_header')920- def from_response_instance_status_tuple():921- return flask.Response('Hello world', 404), {1086+ @app.route('/response_headers')1087+ def from_response_headers():1088+ return flask.Response('Hello world', 404, {'X-Foo': 'Baz'}), {1089 "X-Foo": "Bar",1090 "X-Bar": "Foo"1091 }1092 1093+ @app.route('/response_status')1094+ def from_response_status():1095+ return app.response_class('Hello world', 400), 5001096+1097+ @app.route('/wsgi')1098+ def from_wsgi():1099+ return NotFound()1100+1101 c = app.test_client()927- assert c.get('/unicode').data == u'Hällo Wörld'.encode('utf-8')928- assert c.get('/string').data == u'Hällo Wörld'.encode('utf-8')929- rv = c.get('/args')1102+1103+ assert c.get('/text').data == u'Hällo Wörld'.encode('utf-8')1104+ assert c.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')1105+1106+ rv = c.get('/full_tuple')1107 assert rv.data == b'Meh'1108 assert rv.headers['X-Foo'] == 'Testing'1109 assert rv.status_code == 4001110 assert rv.mimetype == 'text/plain'934- rv2 = c.get('/two_args')935- assert rv2.data == b'Hello'936- assert rv2.headers['X-Foo'] == 'Test'937- assert rv2.status_code == 200938- assert rv2.mimetype == 'text/plain'939- rv3 = c.get('/args_status')940- assert rv3.data == b'Hi, status!'941- assert rv3.status_code == 400942- assert rv3.mimetype == 'text/html'943- rv4 = c.get('/args_header')944- assert rv4.data == b'Hello world'945- assert rv4.headers['X-Foo'] == 'Bar'946- assert rv4.headers['X-Bar'] == 'Foo'947- assert rv4.status_code == 4041111 1112+ rv = c.get('/text_headers')1113+ assert rv.data == b'Hello'1114+ assert rv.headers['X-Foo'] == 'Test'1115+ assert rv.status_code == 2001116+ assert rv.mimetype == 'text/plain'1117 1118+ rv = c.get('/text_status')1119+ assert rv.data == b'Hi, status!'1120+ assert rv.status_code == 4001121+ assert rv.mimetype == 'text/html'1122+1123+ rv = c.get('/response_headers')1124+ assert rv.data == b'Hello world'1125+ assert rv.headers.getlist('X-Foo') == ['Baz', 'Bar']1126+ assert rv.headers['X-Bar'] == 'Foo'1127+ assert rv.status_code == 4041128+1129+ rv = c.get('/response_status')1130+ assert rv.data == b'Hello world'1131+ assert rv.status_code == 5001132+1133+ rv = c.get('/wsgi')1134+ assert b'Not Found' in rv.data1135+ assert rv.status_code == 4041136+1137+1138+def test_response_type_errors():1139+ app = flask.Flask(__name__)1140+ app.testing = True1141+1142+ @app.route('/none')1143+ def from_none():1144+ pass1145+1146+ @app.route('/small_tuple')1147+ def from_small_tuple():1148+ return 'Hello',1149+1150+ @app.route('/large_tuple')1151+ def from_large_tuple():1152+ return 'Hello', 234, {'X-Foo': 'Bar'}, '???'1153+1154+ @app.route('/bad_type')1155+ def from_bad_type():1156+ return True1157+1158+ @app.route('/bad_wsgi')1159+ def from_bad_wsgi():1160+ return lambda: None1161+1162+ c = app.test_client()1163+1164+ with pytest.raises(TypeError) as e:1165+ c.get('/none')1166+ assert 'returned None' in str(e)1167+1168+ with pytest.raises(TypeError) as e:1169+ c.get('/small_tuple')1170+ assert 'tuple must have the form' in str(e)1171+1172+ pytest.raises(TypeError, c.get, '/large_tuple')1173+1174+ with pytest.raises(TypeError) as e:1175+ c.get('/bad_type')1176+ assert 'it was a bool' in str(e)1177+1178+ pytest.raises(TypeError, c.get, '/bad_wsgi')1179+1180+1181 def test_make_response():1182 app = flask.Flask(__name__)1183 with app.test_request_context():1184 rv = flask.make_response()17 unmodified lines1202 with app.test_request_context():1203 rv = flask.make_response(1204 flask.jsonify({'msg': 'W00t'}), 400)1205 assert rv.status_code == 400975- assert rv.data == b'{\n "msg": "W00t"\n}\n'1206+ assert rv.data == b'{"msg":"W00t"}\n'1207 assert rv.mimetype == 'application/json'1208 1209 rv = flask.make_response(1210 flask.Response(''), 400)110 unmodified lines1321 with app.test_request_context():1322 pytest.raises(BuildError, flask.url_for, 'not.existing')1323 1324 1325+def test_url_for_passes_special_values_to_build_error_handler():1326+ app = flask.Flask(__name__)1327+1328+ @app.url_build_error_handlers.append1329+ def handler(error, endpoint, values):1330+ assert values == {1331+ '_external': False,1332+ '_anchor': None,1333+ '_method': None,1334+ '_scheme': None,1335+ }1336+ return 'handled'1337+1338+ with app.test_request_context():1339+ flask.url_for('/')1340+1341+1342 def test_custom_converters():1343 from werkzeug.routing import BaseConverter1344 1345 class ListConverter(BaseConverter):49 unmodified lines1395 with app.test_request_context():1396 assert flask.url_for('static', filename='index.html') == '/foo/index.html'1397 1398 1151-def test_none_response():1152- app = flask.Flask(__name__)1153- app.testing = True1399+def test_static_route_with_host_matching():1400+ app = flask.Flask(__name__, host_matching=True, static_host='example.com')1401+ c = app.test_client()1402+ rv = c.get('http://example.com/static/index.html')1403+ assert rv.status_code == 2001404+ rv.close()1405+ with app.test_request_context():1406+ rv = flask.url_for('static', filename='index.html', _external=True)1407+ assert rv == 'http://example.com/static/index.html'1408+ # Providing static_host without host_matching=True should error.1409+ with pytest.raises(Exception):1410+ flask.Flask(__name__, static_host='example.com')1411+ # Providing host_matching=True with static_folder but without static_host should error.1412+ with pytest.raises(Exception):1413+ flask.Flask(__name__, host_matching=True)1414+ # Providing host_matching=True without static_host but with static_folder=None should not error.1415+ flask.Flask(__name__, host_matching=True, static_folder=None)1416 1155- @app.route('/')1156- def test():1157- return None1158- try:1159- app.test_client().get('/')1160- except ValueError as e:1161- assert str(e) == 'View function did not return a response'1162- pass1163- else:1164- assert "Expected ValueError"1417 1166-1418 def test_request_locals():1419 assert repr(flask.g) == '<LocalProxy unbound>'1420 assert not flask.g1421 96 unmodified lines1518 app = flask.Flask(__name__)1519 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1520 app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1521 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)1271- # make sure werkzeug always passes errors through1272- assert rv['passthrough_errors']1522 1523 1524 def test_max_content_length():1525 app = flask.Flask(__name__)382 unmodified lines1908 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1909 hostname, port = 'localhost', 80001910 app.run(hostname, port, debug=True)1911 assert rv['result'] == 'running on %s:%s ...' % (hostname, port)1912+1913+1914+@pytest.mark.parametrize('host,port,expect_host,expect_port', (1915+ (None, None, 'pocoo.org', 8080),1916+ ('localhost', None, 'localhost', 8080),1917+ (None, 80, 'pocoo.org', 80),1918+ ('localhost', 80, 'localhost', 80),1919+))1920+def test_run_from_config(monkeypatch, host, port, expect_host, expect_port):1921+ def run_simple_mock(hostname, port, *args, **kwargs):1922+ assert hostname == expect_host1923+ assert port == expect_port1924+1925+ monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1926+ app = flask.Flask(__name__)1927+ app.config['SERVER_NAME'] = 'pocoo.org:8080'1928+ app.run(host, port)modified:tests/test_blueprints.py+88 added
89 unmodified lines90 91 assert c.get('/decorator').data == b'boom'92 assert c.get('/function').data == b'bam'93 94+def test_blueprint_app_error_handling():95+ errors = flask.Blueprint('errors', __name__)96+97+ @errors.app_errorhandler(403)98+ def forbidden_handler(e):99+ return 'you shall not pass', 403100+101+ app = flask.Flask(__name__)102+103+ @app.route('/forbidden')104+ def app_forbidden():105+ flask.abort(403)106+107+ forbidden_bp = flask.Blueprint('forbidden_bp', __name__)108+109+ @forbidden_bp.route('/nope')110+ def bp_forbidden():111+ flask.abort(403)112+113+ app.register_blueprint(errors)114+ app.register_blueprint(forbidden_bp)115+116+ c = app.test_client()117+118+ assert c.get('/forbidden').data == b'you shall not pass'119+ assert c.get('/nope').data == b'you shall not pass'120+121 def test_blueprint_url_definitions():122 bp = flask.Blueprint('test', __name__)123 124 @bp.route('/foo', defaults={'baz': 42})256 unmodified lines381 assert rv.status_code == 404382 rv = c.get('/py/bar/123')383 assert rv.status_code == 404384 385+386+def test_endpoint_decorator():387+ from werkzeug.routing import Rule388+ app = flask.Flask(__name__)389+ app.url_map.add(Rule('/foo', endpoint='bar'))390+391+ bp = flask.Blueprint('bp', __name__)392+393+ @bp.endpoint('bar')394+ def foobar():395+ return flask.request.endpoint396+397+ app.register_blueprint(bp, url_prefix='/bp_prefix')398+399+ c = app.test_client()400+ assert c.get('/foo').data == b'bar'401+ assert c.get('/bp_prefix/bar').status_code == 404402+403+404 def test_template_filter():405 bp = flask.Blueprint('bp', __name__)406 @bp.app_template_filter()407 def my_reverse(s):209 unmodified lines617 def index():618 return flask.render_template('template_test.html', value=False)619 rv = app.test_client().get('/')620 assert b'Success!' in rv.data621+622+def test_context_processing():623+ app = flask.Flask(__name__)624+ answer_bp = flask.Blueprint('answer_bp', __name__)625+626+ template_string = lambda: flask.render_template_string(627+ '{% if notanswer %}{{ notanswer }} is not the answer. {% endif %}'628+ '{% if answer %}{{ answer }} is the answer.{% endif %}'629+ )630+631+ # App global context processor632+ @answer_bp.app_context_processor633+ def not_answer_context_processor():634+ return {'notanswer': 43}635+636+ # Blueprint local context processor637+ @answer_bp.context_processor638+ def answer_context_processor():639+ return {'answer': 42}640+641+ # Setup endpoints for testing642+ @answer_bp.route('/bp')643+ def bp_page():644+ return template_string()645+646+ @app.route('/')647+ def app_page():648+ return template_string()649+650+ # Register the blueprint651+ app.register_blueprint(answer_bp)652+653+ c = app.test_client()654+655+ app_page_bytes = c.get('/').data656+ answer_page_bytes = c.get('/bp').data657+658+ assert b'43' in app_page_bytes659+ assert b'42' not in app_page_bytes660+661+ assert b'42' in answer_page_bytes662+ assert b'43' in answer_page_bytesmodified:tests/test_cli.py+117 added-19 removed
12 unmodified lines13 #14 from __future__ import absolute_import, print_function15 import os16 import sys17+from functools import partial18 19 import click20 import pytest21 from click.testing import CliRunner22 from flask import Flask, current_app23 23-from flask.cli import AppGroup, FlaskGroup, NoAppException, ScriptInfo, \24+from flask.cli import cli, AppGroup, FlaskGroup, NoAppException, ScriptInfo, \25 find_best_app, locate_app, with_appcontext, prepare_exec_for_file, \25- find_default_import_path26+ find_default_import_path, get_version27 28 29+@pytest.fixture30+def runner():31+ return CliRunner()32+33+34 def test_cli_name(test_apps):35 """Make sure the CLI object's name is the app's name and not the app itself"""36 from cliapp.app import testapp37 assert testapp.cli.name == testapp.name38 39 40 def test_find_best_app(test_apps):35- """Test of find_best_app."""36- class mod:41+ """Test if `find_best_app` behaves as expected with different combinations of input."""42+ class Module:43 app = Flask('appname')38- assert find_best_app(mod) == mod.app44+ assert find_best_app(Module) == Module.app45 40- class mod:46+ class Module:47 application = Flask('appname')42- assert find_best_app(mod) == mod.application48+ assert find_best_app(Module) == Module.application49 44- class mod:50+ class Module:51 myapp = Flask('appname')46- assert find_best_app(mod) == mod.myapp52+ assert find_best_app(Module) == Module.myapp53 48- class mod:49- myapp = Flask('appname')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 52- pytest.raises(NoAppException, find_best_app, mod)63 54-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, where17 unmodified lines85 """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."""7 unmodified lines104 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"7 unmodified lines134 assert app.name == "createapp"135 assert obj.load_app() == app136 137 111-def test_with_appcontext():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 120- runner = CliRunner()147 result = runner.invoke(testcmd, obj=obj)148 assert result.exit_code == 0149 assert result.output == 'testapp\n'150 151 126-def test_appgroup():152+def test_appgroup(runner):153 """Test of with_appcontext."""154 @click.group(cls=AppGroup)155 def cli():156 pass11 unmodified lines168 click.echo(current_app.name)169 170 obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))171 146- runner = CliRunner()172 result = runner.invoke(cli, ['test'], obj=obj)173 assert result.exit_code == 0174 assert result.output == 'testappgroup\n'175 1 unmodified line177 assert result.exit_code == 0178 assert result.output == 'testappgroup\n'179 180 156-def test_flaskgroup():181+def test_flaskgroup(runner):182 """Test FlaskGroup."""183 def create_app(info):184 return Flask("flaskgroup")185 4 unmodified lines190 @cli.command()191 def test():192 click.echo(current_app.name)193 169- runner = CliRunner()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 outputmodified:tests/test_config.py+20 added-2 removed
5 unmodified lines6 :copyright: (c) 2015 by the Flask Team, see AUTHORS for more details.7 :license: BSD, see LICENSE for more details.8 """9 10-import pytest10 12-import os11 from datetime import timedelta12+import os13+import textwrap14+15 import flask16+from flask._compat import PY217+import pytest18 19 20 # config keys used for the TestConfig21 TEST_KEY = 'foo'167 unmodified lines189 bar_options = app.config.get_namespace('BAR_', lowercase=False, trim_namespace=False)190 assert 2 == len(bar_options)191 assert 'bar stuff 1' == bar_options['BAR_STUFF_1']192 assert 'bar stuff 2' == bar_options['BAR_STUFF_2']193+194+195+@pytest.mark.parametrize('encoding', ['utf-8', 'iso-8859-15', 'latin-1'])196+def test_from_pyfile_weird_encoding(tmpdir, encoding):197+ f = tmpdir.join('my_config.py')198+ f.write_binary(textwrap.dedent(u'''199+ # -*- coding: {0} -*-200+ TEST_VALUE = "föö"201+ '''.format(encoding)).encode(encoding))202+ app = flask.Flask(__name__)203+ app.config.from_pyfile(str(f))204+ value = app.config['TEST_VALUE']205+ if PY2:206+ value = value.decode(encoding)207+ assert value == u'föö'modified:tests/test_ext.py+2 added-2 removed
177 unmodified lines178 179 def test_no_error_swallowing(flaskext_broken):180 with pytest.raises(ImportError) as excinfo:181 import flask.ext.broken182-183- assert excinfo.type is ImportError182+ # python3.6 raises a subclass of ImportError: 'ModuleNotFoundError'183+ assert issubclass(excinfo.type, ImportError)184 if PY2:185 message = 'No module named missing_module'186 else:187 message = 'No module named \'missing_module\''12 unmodified linesmodified:tests/test_helpers.py+203 added-38 removed
10 unmodified lines11 12 import pytest13 14 import os15+import uuid16 import datetime17+18 import flask19 from logging import StreamHandler20+from werkzeug.datastructures import Range21 from werkzeug.exceptions import BadRequest, NotFound22 from werkzeug.http import parse_cache_control_header, parse_options_header23 from werkzeug.http import http_date21-from flask._compat import StringIO, text_type, PY224+from flask._compat import StringIO, text_type25 26 27 def has_encoding(name):28 try:5 unmodified lines34 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'])59 unmodified lines109 with app.app_context():110 rv = flask.json.dumps(u'\N{SNOWMAN}')111 assert rv == u'"\u2603"'112 102- def test_jsonify_basic_types(self):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."""104- # Should be able to use pytest parametrize on this, but I couldn't105- # figure out the correct syntax106- # https://pytest.org/latest/parametrize.html#pytest-mark-parametrize-parametrizing-test-functions107- test_data = (0, 1, 23, 3.14, 's', "longer string", True, False,)127 app = flask.Flask(__name__)128 c = app.test_client()110- for i, d in enumerate(test_data):111- url = '/jsonify_basic_types{0}'.format(i)112- app.add_url_rule(url, str(i), lambda x=d: flask.jsonify(x))113- rv = c.get(url)114- assert rv.mimetype == 'application/json'115- assert flask.json.loads(rv.data) == d129 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,34 unmodified lines174 assert flask.json.loads(rv.data) == l175 176 def test_jsonify_date_types(self):177 """Test jsonify with datetime.date and datetime.datetime types."""159-178 test_dates = (179 datetime.datetime(1973, 3, 11, 6, 30, 45),180 datetime.date(1975, 1, 5)181 )164-182 app = flask.Flask(__name__)183 c = app.test_client()184 185 for i, d in enumerate(test_dates):2 unmodified lines188 rv = c.get(url)189 assert rv.mimetype == 'application/json'190 assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple())191 192+ def test_jsonify_uuid_types(self):193+ """Test jsonify with uuid.UUID types"""194+195+ test_uuid = uuid.UUID(bytes=b'\xDE\xAD\xBE\xEF' * 4)196+ app = flask.Flask(__name__)197+ url = '/uuid_test'198+ app.add_url_rule(url, url, lambda: flask.jsonify(x=test_uuid))199+200+ c = app.test_client()201+ rv = c.get(url)202+203+ rv_x = flask.json.loads(rv.data)['x']204+ assert rv_x == str(test_uuid)205+ rv_uuid = uuid.UUID(rv_x)206+ assert rv_uuid == test_uuid207+208 def test_json_attr(self):209 app = flask.Flask(__name__)210 @app.route('/add', methods=['POST'])211 def add():54 unmodified lines266 'x': {'_foo': 42}267 }), content_type='application/json')268 assert rv.data == b'"<42>"'269 270+ def test_blueprint_json_customization(self):271+ class X(object):272+ def __init__(self, val):273+ self.val = val274+275+ class MyEncoder(flask.json.JSONEncoder):276+ def default(self, o):277+ if isinstance(o, X):278+ return '<%d>' % o.val279+280+ return flask.json.JSONEncoder.default(self, o)281+282+ class MyDecoder(flask.json.JSONDecoder):283+ def __init__(self, *args, **kwargs):284+ kwargs.setdefault('object_hook', self.object_hook)285+ flask.json.JSONDecoder.__init__(self, *args, **kwargs)286+287+ def object_hook(self, obj):288+ if len(obj) == 1 and '_foo' in obj:289+ return X(obj['_foo'])290+291+ return obj292+293+ bp = flask.Blueprint('bp', __name__)294+ bp.json_encoder = MyEncoder295+ bp.json_decoder = MyDecoder296+297+ @bp.route('/bp', methods=['POST'])298+ def index():299+ return flask.json.dumps(flask.request.get_json()['x'])300+301+ app = flask.Flask(__name__)302+ app.testing = True303+ app.register_blueprint(bp)304+305+ c = app.test_client()306+ rv = c.post('/bp', data=flask.json.dumps({307+ 'x': {'_foo': 42}308+ }), content_type='application/json')309+ assert rv.data == b'"<42>"'310+311 def test_modified_url_encoding(self):312 class ModifiedRequest(flask.Request):313 url_charset = 'euc-kr'314 app = flask.Flask(__name__)14 unmodified lines329 330 def test_json_key_sorting(self):331 app = flask.Flask(__name__)332 app.testing = True333+ app.debug = True334+335 assert app.config['JSON_SORT_KEYS'] == True336 d = dict.fromkeys(range(20), 'foo')337 338 @app.route('/')91 unmodified lines430 last_modified = datetime.datetime(1999, 1, 1)431 432 @app.route('/')433 def index():358- return flask.send_file(StringIO("party like it's"), last_modified=last_modified)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:369- rv = flask.send_file(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'2 unmodified lines466 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:380- rv = flask.send_file(f)470+ rv = flask.send_file(f, mimetype='text/html')471 assert rv.mimetype == 'text/html'382- assert 'x-sendfile' in rv.headers383- assert rv.headers['x-sendfile'] == \384- os.path.join(app.root_path, 'static/index.html')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')390- rv = flask.send_file(f)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()4 unmodified lines487 def __getattr__(self, name):488 return getattr(self._io, name)489 f = PyStringIO('Test')490 f.name = 'test.txt'403- rv = flask.send_file(f)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()8 unmodified lines504 app.use_x_sendfile = True505 506 with app.test_request_context():507 f = StringIO('Test')420- rv = flask.send_file(f)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:428- rv = flask.send_file(f, as_attachment=True)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():435- assert options['filename'] == 'index.html'589 rv = flask.send_file('static/index.html', as_attachment=True)590 value, options = parse_options_header(rv.headers['Content-Disposition'])591 assert value == 'attachment'592 assert options['filename'] == 'index.html'8 unmodified lines601 assert value == 'attachment'602 assert options['filename'] == 'index.txt'603 rv.close()604 605+ def test_attachment_with_utf8_filename(self):606+ app = flask.Flask(__name__)607+608+ with app.test_request_context():609+ rv = flask.send_file('static/index.html', as_attachment=True, attachment_filename=u'Ñandú/pingüino.txt')610+ content_disposition = set(rv.headers['Content-Disposition'].split('; '))611+ assert content_disposition == set((612+ 'attachment',613+ 'filename="Nandu/pinguino.txt"',614+ "filename*=UTF-8''%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt"615+ ))616+ rv.close()617+618 def test_static_file(self):619 app = flask.Flask(__name__)620 # default cache timeout is 12 hours621 with app.test_request_context():280 unmodified lines902 assert called == [42]903 904 905 class TestSafeJoin(object):740-906 def test_safe_join(self):907 # Valid combinations of *args and expected joined paths.908 passing = (744- (('a/b/c', ), 'a/b/c'),745- (('/', 'a/', 'b/', 'c/', ), '/a/b/c'),746- (('a', 'b', 'c', ), 'a/b/c'),747- (('/a', 'b/c', ), '/a/b/c'),748- (('a/b', 'X/../c'), 'a/b/c', ),749- (('/a/b', 'c/X/..'), '/a/b/c', ),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 slash751- (('/a/b/c', '', ), '/a/b/c/', ),916+ (('/a/b/c', ''), '/a/b/c/'),917 # Preserve dot slash753- (('/a/b/c', './', ), '/a/b/c/.', ),754- (('a/b/c', 'X/..'), 'a/b/c/.', ),918+ (('/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 )5 unmodified lines929 # Should raise werkzeug.exceptions.NotFound on unsafe joins.930 failing = (931 # path.isabs and ``..'' checks932 ('/a', 'b', '/c'),768- ('/a', '../b/c', ),933+ ('/a', '../b/c'),934 ('/a', '..', 'b/c'),935 # Boundaries violations after path normalization771- ('/a', 'b/../b/../../c', ),936+ ('/a', 'b/../b/../../c'),937 ('/a', 'b', 'c/../..'),773- ('/a', 'b/../../c', ),938+ ('/a', 'b/../../c'),939 )940 941 for args in failing:942 with pytest.raises(NotFound):1 unmodified linemodified:tests/test_reqctx.py+25 added
10 unmodified lines11 12 import pytest13 14 import flask15+from flask.sessions import SessionInterface16 17 try:18 from greenlet import greenlet19 except ImportError:173 unmodified lines193 assert rv.data == b'Hello World!'194 195 result = greenlets[0].run()196 assert result == 42197+198+199+def test_session_error_pops_context():200+ class SessionError(Exception):201+ pass202+203+ class FailingSessionInterface(SessionInterface):204+ def open_session(self, app, request):205+ raise SessionError()206+207+ class CustomFlask(flask.Flask):208+ session_interface = FailingSessionInterface()209+210+ app = CustomFlask(__name__)211+212+ @app.route('/')213+ def index():214+ # shouldn't get here215+ assert False216+217+ response = app.test_client().get('/')218+ assert response.status_code == 500219+ assert not flask.request220+ assert not flask.current_appmodified:tests/test_testing.py+35 added
9 unmodified lines10 """11 import pytest12 13 import flask14+import werkzeug15 16 from flask._compat import text_type17 18 24 unmodified lines43 with app.test_client() as c:44 rv = c.get('/')45 assert rv.data == b'http://localhost/'46 47+def test_environ_base_default():48+ app = flask.Flask(__name__)49+ app.testing = True50+ @app.route('/')51+ def index():52+ flask.g.user_agent = flask.request.headers["User-Agent"]53+ return flask.request.remote_addr54+55+ with app.test_client() as c:56+ rv = c.get('/')57+ assert rv.data == b'127.0.0.1'58+ assert flask.g.user_agent == 'werkzeug/' + werkzeug.__version__59+60+def test_environ_base_modified():61+ app = flask.Flask(__name__)62+ app.testing = True63+ @app.route('/')64+ def index():65+ flask.g.user_agent = flask.request.headers["User-Agent"]66+ return flask.request.remote_addr67+68+ with app.test_client() as c:69+ c.environ_base['REMOTE_ADDR'] = '0.0.0.0'70+ c.environ_base['HTTP_USER_AGENT'] = 'Foo'71+ rv = c.get('/')72+ assert rv.data == b'0.0.0.0'73+ assert flask.g.user_agent == 'Foo'74+75+ c.environ_base['REMOTE_ADDR'] = '0.0.0.1'76+ c.environ_base['HTTP_USER_AGENT'] = 'Bar'77+ rv = c.get('/')78+ assert rv.data == b'0.0.0.1'79+ assert flask.g.user_agent == 'Bar'80+81 def test_redirect_keep_session():82 app = flask.Flask(__name__)83 app.secret_key = 'testing'84 187 unmodified linesmodified:tests/test_views.py+42 added
158 unmodified lines159 app.add_url_rule('/', view_func=Index.as_view('index'))160 161 # But these tests should still pass. We just log a warning.162 common_test(app)163+164+def test_multiple_inheritance():165+ app = flask.Flask(__name__)166+167+ class GetView(flask.views.MethodView):168+ def get(self):169+ return 'GET'170+171+ class DeleteView(flask.views.MethodView):172+ def delete(self):173+ return 'DELETE'174+175+ class GetDeleteView(GetView, DeleteView):176+ pass177+178+ app.add_url_rule('/', view_func=GetDeleteView.as_view('index'))179+180+ c = app.test_client()181+ assert c.get('/').data == b'GET'182+ assert c.delete('/').data == b'DELETE'183+ assert sorted(GetDeleteView.methods) == ['DELETE', 'GET']184+185+def test_remove_method_from_parent():186+ app = flask.Flask(__name__)187+188+ class GetView(flask.views.MethodView):189+ def get(self):190+ return 'GET'191+192+ class OtherView(flask.views.MethodView):193+ def post(self):194+ return 'POST'195+196+ class View(GetView, OtherView):197+ methods = ['GET']198+199+ app.add_url_rule('/', view_func=View.as_view('index'))200+201+ c = app.test_client()202+ assert c.get('/').data == b'GET'203+ assert c.post('/').status_code == 405204+ assert sorted(View.methods) == ['GET']added:.gitattributes+1 added
1+CHANGES merge=unionmodified:.gitignore+5 added-1 removed
9 unmodified lines10 _mailinglist11 .tox12 .cache/13 .idea/14-.coverage14+15+# Coverage reports16 htmlcov17+.coverage18+.coverage.*19+*,covermodified:.travis.yml+5 added-1 removed
6 unmodified lines7 - "pypy"8 - "3.3"9 - "3.4"10 - "3.5"11+ - "3.6"12 13 env:14 - REQUIREMENTS=lowest15 - REQUIREMENTS=lowest-simplejson16 unmodified lines32 - 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 36-41 install:42 - pip install tox43 44 script:15 unmodified linesmodified:AUTHORS+1 added
19 unmodified lines20 - Edmond Burnett21 - Florent Xicluna22 - Georg Brandl23 - Jeff Widman @jeffwidman24+- Joshua Bronson @jab25 - Justin Quick26 - Kenneth Reitz27 - Keyan Pishdadian28 - Marian Sigler10 unmodified linesmodified:CHANGES+92 added-3 removed
1 unmodified line2 ===============3 4 Here you can see the full list of changes between each Flask release.5 6+Version 0.137+------------8+9+Major release, unreleased10+11+- 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`.10-- Mimetype guessing for ``send_file`` has been removed, as per issue ``#104``.11- See pull request ``#1849``.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.298 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 is321- 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` to257 unmodified linesmodified:CONTRIBUTING.rst+37 added-4 removed
26 unmodified lines27 - Include tests if your patch is supposed to solve a bug, and explain28 clearly under which circumstances the bug happens. Make sure the test fails29 without your patch.30 31-- Try to follow `PEP8 <http://legacy.python.org/dev/peps/pep-0008/>`_, but you31+- Try to follow `PEP8 <https://www.python.org/dev/peps/pep-0008/>`_, but you32 may ignore the line-length-limit if following it would make the code uglier.33 34 Getting Started35 ===============36 37 You probably want to set up a `virtualenv38 <https://virtualenv.readthedocs.io/en/latest/index.html>`_.39 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 11 unmodified lines61 pip install pytest62 63 Then you can run the testsuite with::64 59- py.test65+ pytest tests/66 67 **Shortcut**: ``make test`` will ensure ``pytest`` is installed, and run it.68 69 With only pytest installed, a large part of the testsuite will get skipped20 unmodified lines90 pip install pytest-cov91 92 After this has been installed, you can output a report to the command line using this command::93 88- py.test --cov=flask tests/94+ pytest --cov=flask tests/95 96 Generate a HTML report can be done using this command::97 92- py.test --cov-report html --cov=flask tests/98+ pytest --cov-report html --cov=flask tests/99 100 Full docs on ``coverage.py`` are here: https://coverage.readthedocs.io101 102 **Shortcut**: ``make cov`` will ensure ``pytest-cov`` is installed, run it, display the results, *and* save the HTML report.103+104+105+Caution106+=======107+pushing108+-------109+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.110+111+112+cloning113+-------114+The zero-padded file modes files above can cause issues while cloning, too. If you have115+116+::117+118+ [fetch]119+ fsckobjects = true120+121+or122+123+::124+125+ [receive]126+ fsckObjects = true127+128+129+set in your git configuration file, cloning this repository will fail. The only solution is to set both of the above settings to false while cloning, and then setting them back to true after the cloning is finished.modified:Makefile+2 added-6 removed
1 unmodified line2 3 all: clean-pyc test4 5 test:6- pip install -r test-requirements.txt -q7- FLASK_DEBUG= py.test tests examples6+ pip install -r test-requirements.txt7+ tox -e py-release8 9-tox-test:10- pip install -r test-requirements.txt -q11- tox12-9 cov:10 pip install -r test-requirements.txt -q11 FLASK_DEBUG= py.test --cov-report term --cov-report html --cov=flask --cov=examples tests examples12 33 unmodified linesmodified:README+2 added-2 removed
31 unmodified lines32 ~ Where are the tests?33 34 Good that you're asking. The tests are in the35 tests/ folder. To run the tests use the36- `py.test` testing tool:36+ `pytest` testing tool:37 38- $ py.test38+ $ pytest39 40 Details on contributing can be found in CONTRIBUTING.rst41 42 ~ Where can I get help?7 unmodified linesmodified:setup.cfg+5 added-2 removed
1 [aliases]2 release = egg_info -RDb ''3 4-[wheel]4+[bdist_wheel]5 universal = 16 7-[pytest]7+[metadata]8+license_file = LICENSE9+10+[tool:pytest]11 norecursedirs = .* *.egg *.egg-info env* artwork docsmodified:setup.py+2 added-2 removed
39 unmodified lines40 41 * `website <http://flask.pocoo.org/>`_42 * `documentation <http://flask.pocoo.org/docs/>`_43 * `development version44- <http://github.com/pallets/flask/zipball/master#egg=Flask-dev>`_44+ <https://github.com/pallets/flask/zipball/master#egg=Flask-dev>`_45 46 """47 import re48 import ast9 unmodified lines58 59 setup(60 name='Flask',61 version=version,62- url='http://github.com/pallets/flask/',62+ url='https://github.com/pallets/flask/',63 license='BSD',64 author='Armin Ronacher',65 author_email='armin.ronacher@active-4.com',66 description='A microframework based on Werkzeug, Jinja2 '34 unmodified linesmodified:test-requirements.txt+1 added-1 removed
1 tox2 pytest3-pytest-cov3+pytest-covmodified:tox.ini+9 added-4 removed
1 [tox]2-envlist = {py26,py27,pypy}-{lowest,release,devel}{,-simplejson}, {py33,py34,py35}-{release,devel}{,-simplejson}2+envlist = {py26,py27,pypy}-{lowest,release,devel}{,-simplejson}, {py33,py34,py35,py36}-{release,devel}{,-simplejson}3 4 5 6 [testenv]7+passenv = LANG8+usedevelop=true9 commands =8- py.test []9-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 greenlet13- redbaron19 20 lowest: Werkzeug==0.721 lowest: Jinja2==2.422 lowest: itsdangerous==0.2111 unmodified lines