Merge branch 'master' into figome-multiple-inheritance
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parents 516ce59, 9569e8c · Browse files · 130 files·+2429 added−1716 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
130 files+2429 added−1716 removed
- tests:+666 added−46 removed
- other:+1763 added−1670 removed
Provenance
- Commit
0d9d3d8- Tree
376228e- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
516ce59- Parent 2
9569e8c
130 files changed+2429 added−1716 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+1 added-1 removed
34 unmodified lines35 36 from celery import Celery37 38 def make_celery(app):39- celery = Celery(app.import_name, backend=app.config['CELERY_BACKEND'],39+ celery = Celery(app.import_name, backend=app.config['CELERY_RESULT_BACKEND'],40 broker=app.config['CELERY_BROKER_URL'])41 celery.conf.update(app.config)42 TaskBase = celery.Task43 class ContextTask(TaskBase):50 unmodified linesmodified:docs/patterns/distribute.rst+1 added-1 removed
172 unmodified lines173 the code without having to run ``install`` again after each change.174 175 176 .. _pip: https://pypi.python.org/pypi/pip177-.. _Setuptools: https://pythonhosted.org/setuptools177+.. _Setuptools: https://pypi.python.org/pypi/setuptoolsmodified: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+6 added-6 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):5 unmodified lines71 <!doctype html>72 <title>Upload new File</title>73 <h1>Upload new File</h1>74 <form method=post enctype=multipart/form-data>75- <p><input type=file name=file>76- <input type=submit value=Upload>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?99 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/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+7 added-7 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 the ``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)22 unmodified lines101 M102 103 Additionally, it is a good idea to provide a query function that combines104 getting the cursor, executing and fetching the results::105- 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 112-This handy little function, in combination with a row factory, makes 113-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 Injections134-<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+1 added-1 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 100 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/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/cli.rst+15 added-5 removed
54 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 101 unmodified linesmodified:docs/conf.py+7 added-4 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-from datetime import datetime14 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.25 sys.path.append(os.path.join(os.path.dirname(__file__), '_themes'))25 unmodified lines51 master_doc = 'index'52 53 # General information about the project.54 project = u'Flask'52-copyright = u'2010 - {0}, Armin Ronacher'.format(datetime.utcnow().year)55+copyright = u'2010 - {0}, Armin Ronacher'.format(BUILD_DATE.year)56 57 # The version info for the project you're documenting, acts as replacement for58 # |version| and |release|, also used in various other places throughout the59 # built documents.173 unmodified lines233 234 # The scheme of the identifier. Typical schemes are ISBN or URL.235 #epub_scheme = ''236 234-# The unique identifier of the text. This can be a ISBN number237+# The unique identifier of the text. This can be an ISBN number238 # or the project homepage.239 #epub_identifier = ''240 241 # A unique identification for the text.17 unmodified lines259 'python': ('https://docs.python.org/3/', None),260 'werkzeug': ('http://werkzeug.pocoo.org/docs/', None),261 'click': ('http://click.pocoo.org/', None),262 'jinja': ('http://jinja.pocoo.org/docs/', None),260- 'sqlalchemy': ('http://docs.sqlalchemy.org/en/latest/', None),263+ 'sqlalchemy': ('https://docs.sqlalchemy.org/en/latest/', None),264 'wtforms': ('https://wtforms.readthedocs.io/en/latest/', None),265 'blinker': ('https://pythonhosted.org/blinker/', None)266 }267 35 unmodified linesmodified:docs/config.rst+22 added-8 removed
42 unmodified lines43 DEBUG=True,44 SECRET_KEY='...'45 )46 47+.. admonition:: Debug Mode with the ``flask`` Script48+49+ If you use the :command:`flask` script to start a local development50+ server, to enable the debug mode, you need to export the ``FLASK_DEBUG``51+ environment variable before running the server::52+53+ $ export FLASK_DEBUG=154+ $ flask run55+56+ (On Windows you need to use ``set`` instead of ``export``).57+ 58+ ``app.debug`` and ``app.config['DEBUG']`` are not compatible with 59+ the :command:`flask` script. They only worked when using ``Flask.run()``60+ method.61+ 62 Builtin Configuration Values63 ----------------------------64 65 The following configuration values are used internally by Flask:66 67 .. tabularcolumns:: |p{6.5cm}|p{8.5cm}|68 69 ================================= =========================================55-``DEBUG`` enable/disable debug mode70+``DEBUG`` enable/disable debug mode when using 71+ ``Flask.run()`` method to start server72 ``TESTING`` enable/disable testing mode73 ``PROPAGATE_EXCEPTIONS`` explicitly enable or disable the74 propagation of exceptions. If not set or75 explicitly set to ``None`` this is116 unmodified lines192 caches. You can override the default193 behavior by changing this variable.194 This is not recommended but might give195 you a performance improvement on the180- cost of cachability.181-``JSONIFY_PRETTYPRINT_REGULAR`` If this is set to ``True`` (the default)182- jsonify responses will be pretty printed183- if they are not requested by an184- XMLHttpRequest object (controlled by185- the ``X-Requested-With`` header)196+ cost of cacheability.197+``JSONIFY_PRETTYPRINT_REGULAR`` If this is set to ``True`` or the Flask app198+ is running in debug mode, jsonify responses199+ will be pretty printed.200 ``JSONIFY_MIMETYPE`` MIME type used for jsonify responses.201 ``TEMPLATES_AUTO_RELOAD`` Whether to check for modifications of202 the template source and reload it203 automatically. By default the value 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+20 added-31 removed
38 unmodified lines39 installations of Python, one for each project. It doesn't actually install40 separate copies of Python, but it does provide a clever way to keep different41 project environments isolated. Let's see how virtualenv works.42 43-If you are on Mac OS X or Linux, chances are that one of the following two44-commands will work for you::43+If you are on Mac OS X or Linux, chances are that the following44+command will work for you::45 46- $ sudo easy_install virtualenv47-48-or even better::49-46 $ sudo pip install virtualenv47 52-One of these will probably install virtualenv on your system. Maybe it's even48+It will probably install virtualenv on your system. Maybe it's even49 in your package manager. If you use Ubuntu, try::50 51 $ sudo apt-get install python-virtualenv52 57-If you are on Windows and don't have the :command:`easy_install` command, you must53+If you are on Windows and don't have the ``easy_install`` command, you must54 install it first. Check the :ref:`windows-easy-install` section for more55 information about how to do that. Once you have it installed, run the same60-commands as above, but without the :command:`sudo` prefix.56+commands as above, but without the ``sudo`` prefix.57 58 Once you have virtualenv installed, just fire up a shell and create59 your own environment. I usually create a project folder and a :file:`venv`60 folder within::10 unmodified lines71 $ . venv/bin/activate72 73 If you are a Windows user, the following command is for you::74 79- $ venv\scripts\activate75+ $ venv\Scripts\activate76 77 Either way, you should now be using your virtualenv (notice how the prompt of78 your shell has changed to show the active environment).79 14 unmodified lines94 System-Wide Installation95 ------------------------96 97 This is possible as well, though I do not recommend it. Just run102-:command:`pip` with root privileges::98+``pip`` with root privileges::99 100 $ sudo pip install Flask101 102 (On Windows systems, run it in a command-prompt window with administrator107-privileges, and leave out :command:`sudo`.)103+privileges, and leave out ``sudo``.)104 105 106 Living on the Edge107 ------------------108 109 If you want to work with the latest version of Flask, there are two ways: you114-can either let :command:`pip` pull in the development version, or you can tell110+can either let ``pip`` pull in the development version, or you can tell111 it to operate on a git checkout. Either way, virtualenv is recommended.112 113 Get the git checkout in a new virtualenv and run in development mode::114 119- $ git clone http://github.com/pallets/flask.git115+ $ git clone https://github.com/pallets/flask.git116 Initialized empty Git repository in ~/dev/flask/.git/117 $ cd flask118 $ virtualenv venv119 New python executable in venv/bin/python6 unmodified lines126 This will pull in the dependencies and activate the git head as the current127 version inside the virtualenv. Then all you have to do is run ``git pull128 origin`` to update to the latest version.129 134-130 .. _windows-easy-install:131 132 `pip` and `setuptools` on Windows133 ---------------------------------134 140-Sometimes getting the standard "Python packaging tools" like *pip*, *setuptools*141-and *virtualenv* can be a little trickier, but nothing very hard. The two crucial142-packages you will need are setuptools and pip - these will let you install143-anything else (like virtualenv). Fortunately there are two "bootstrap scripts"144-you can run to install either.135+Sometimes getting the standard "Python packaging tools" like ``pip``, ``setuptools``136+and ``virtualenv`` can be a little trickier, but nothing very hard. The crucial137+package you will need is pip - this will let you install138+anything else (like virtualenv). Fortunately there is a "bootstrap script"139+you can run to install.140 146-If you don't currently have either, then :file:`get-pip.py` will install both for you147-(you won't need to run :file:`ez_setup.py`).141+If you don't currently have ``pip``, then `get-pip.py` will install it for you.142 143 `get-pip.py`_144 151-To install the latest setuptools, you can use its bootstrap file:152-153-`ez_setup.py`_154-155-Either should be double-clickable once you download them. If you already have pip,145+It should be double-clickable once you download it. If you already have ``pip``,146 you can upgrade them by running::147 148 > pip install --upgrade pip setuptools149 160-Most often, once you pull up a command prompt you want to be able to type :command:`pip`161-and :command:`python` which will run those things, but this might not automatically happen150+Most often, once you pull up a command prompt you want to be able to type ``pip``151+and ``python`` which will run those things, but this might not automatically happen152 on Windows, because it doesn't know where those executables are (give either a try!).153 154 To fix this, you should be able to navigate to your Python install directory155 (e.g :file:`C:\Python27`), then go to :file:`Tools`, then :file:`Scripts`, then find the156 :file:`win_add2path.py` file and run that. Open a **new** Command Prompt and167-check that you can now just type :command:`python` to bring up the interpreter.157+check that you can now just type ``python`` to bring up the interpreter.158 159 Finally, to install `virtualenv`_, you can simply run::160 161 > pip install virtualenv162 163 Then you can be off on your way following the installation instructions above.164 165 .. _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+19 added-16 removed
100 unmodified lines101 102 Invalid Import Name103 ```````````````````104 105-The ``-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 150 unmodified lines263 >>> @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')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=/30 unmodified lines305 306 @app.route('/login', methods=['GET', 'POST'])307 def login():308 if request.method == 'POST':309- do_the_login()309+ return do_the_login()310 else:311- show_the_login_form()311+ return show_the_login_form()312 313 If ``GET`` is present, ``HEAD`` will be added automatically for you. You314 don't have to deal with that. It will also make sure that ``HEAD`` requests315 are handled as the `HTTP RFC`_ (the document describing the HTTP50 unmodified lines366 HTTP has become quite popular lately and browsers are no longer the only367 clients that are using HTTP. For instance, many revision control systems368 use it.369 370-.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt370+.. _HTTP RFC: https://www.ietf.org/rfc/rfc2068.txt371 372 Static Files373 ------------374 162 unmodified lines537 The Request Object538 ``````````````````539 540 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 of541+it here in detail (see :class:`~flask.Request`). Here is a broad overview of542 some of the most common operations. First of all you have to import it from543 the ``flask`` module::544 545 from flask import request546 547 The current request method is available by using the548-:attr:`~flask.request.method` attribute. To access form data (data548+:attr:`~flask.Request.method` attribute. To access form data (data549 transmitted in a ``POST`` or ``PUT`` request) you can use the550-:attr:`~flask.request.form` attribute. Here is a full example of the two550+:attr:`~flask.Request.form` attribute. Here is a full example of the two551 attributes mentioned above::552 553 @app.route('/login', methods=['POST', 'GET'])554 def login():14 unmodified lines569 error page is shown instead. So for many situations you don't have to570 deal with that problem.571 572 To access parameters submitted in the URL (``?key=value``) you can use the573-:attr:`~flask.request.args` attribute::573+:attr:`~flask.Request.args` attribute::574 575 searchword = request.args.get('key', '')576 577 We recommend accessing URL parameters with `get` or by catching the578 :exc:`KeyError` because users might change the URL and presenting them a 400579 bad request page in that case is not user friendly.580 581 For a full list of methods and attributes of the request object, head over582-to the :class:`~flask.request` documentation.582+to the :class:`~flask.Request` documentation.583 584 585 File Uploads586 ````````````229 unmodified lines816 values do not persist across requests, cookies are indeed enabled, and you are817 not getting a clear error message, check the size of the cookie in your page818 responses compared to the size supported by web browsers.819 820+Besides the default client-side based sessions, if you want to handle821+sessions on the server-side instead, there are several822+Flask extensions that support this.823 824 Message Flashing825 ----------------826 67 unmodified linesmodified:docs/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+12 added-10 removed
39 unmodified lines40 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+41 added-3 removed
17 unmodified lines18 providing the ``--upgrade`` parameter::19 20 $ 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 supposed76 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 46 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.267 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/app.py+86 added-47 removed
12 unmodified lines13 from threading import Lock14 from datetime import timedelta15 from itertools import chain16 from functools import update_wrapper17-from collections import deque17 18 from werkzeug.datastructures import ImmutableDict19 from werkzeug.routing import Map, Rule, RequestRedirect, BuildError20 from werkzeug.exceptions import HTTPException, InternalServerError, \101 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 a118 unmodified lines528 #: class ListConverter(BaseConverter):529 #: def to_python(self, value):530 #: return value.split(',')531 #: def to_url(self, values):522- #: return ','.join(BaseConverter.to_url(value)532+ #: return ','.join(super(ListConverter, self).to_url(value)533 #: for value in values)534 #:535 #: app = Flask(__name__)536 #: app.url_map.converters['list'] = ListConverter537 self.url_map = Map()538 539+ self.url_map.host_matching = host_matching540+541 # tracks internally if the application already handled at least one542 # request.543 self._got_first_request = False544 self._before_request_lock = Lock()545 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.546+ # Add a static route using the provided static_url_path, static_host,547+ # and static_folder if there is a configured static_folder.548+ # Note we do this without checking if static_folder exists.549+ # For one, it might be created while the server is running (e.g. during550+ # development). Also, Google App Engine stores static files somewhere551 if self.has_static_folder:552+ assert bool(static_host) == host_matching, 'Invalid static_host/host_matching combination'553 self.add_url_rule(self.static_url_path + '/<path:filename>',541- endpoint='static',554+ endpoint='static', host=static_host,555 view_func=self.send_static_file)556 557 #: The click command line context for this application. Commands558 #: registered here show up in the :command:`flask` command once the267 unmodified lines826 The default port is now picked from the ``SERVER_NAME`` variable.827 828 :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to829 have the server available externally as well. Defaults to817- ``'127.0.0.1'``.830+ ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config831+ variable if present.832 :param port: the port of the webserver. Defaults to ``5000`` or the833 port defined in the ``SERVER_NAME`` config variable if834 present.835 :param debug: if given, enable or disable debug mode.2 unmodified lines838 Werkzeug server. See839 :func:`werkzeug.serving.run_simple` for more840 information.841 """842+ # Change this into a no-op if the server is invoked from the843+ # command line. Have a look at cli.py for more information.844+ if os.environ.get('FLASK_RUN_FROM_CLI_SERVER') == '1':845+ from .debughelpers import explain_ignored_app_run846+ explain_ignored_app_run()847+ return848+849 from werkzeug.serving import run_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 = 5000850+ _host = '127.0.0.1'851+ _port = 5000852+ server_name = self.config.get("SERVER_NAME")853+ sn_host, sn_port = None, None854+ if server_name:855+ sn_host, _, sn_port = server_name.partition(':')856+ host = host or sn_host or _host857+ port = int(port or sn_port or _port)858 if debug is not None:859 self.debug = bool(debug)860 options.setdefault('use_reloader', self.debug)861 options.setdefault('use_debugger', self.debug)841- options.setdefault('passthrough_errors', True)862 try:863 run_simple(host, port, self, **options)864 finally:865 # reset the first request information if the development server846- # resetted normally. This makes it possible to restart the server866+ # reset normally. This makes it possible to restart the server867 # without reloader and that stuff from an interactive shell.868 self._got_first_request = False869 870 def test_client(self, use_cookies=True, **kwargs):25 unmodified lines896 897 from flask.testing import FlaskClient898 899 class CustomClient(FlaskClient):880- def __init__(self, authentication=None, *args, **kwargs):881- FlaskClient.__init__(*args, **kwargs)882- self._authentication = authentication900+ def __init__(self, *args, **kwargs):901+ self._authentication = kwargs.pop("authentication")902+ super(CustomClient,self).__init__( *args, **kwargs)903 904 app.test_client_class = CustomClient905 client = app.test_client(authentication='Basic ....')906 72 unmodified lines979 """980 return iter(self._blueprint_order)981 982 @setupmethod963- def add_url_rule(self, rule, endpoint=None, view_func=None, **options):983+ def add_url_rule(self, rule, endpoint=None, view_func=None, provide_automatic_options=None, **options):984 """Connects a URL rule. Works exactly like the :meth:`route`985 decorator. If a view_func is provided it will be registered with the986 endpoint.987 31 unmodified lines1019 itself assumes the name of the view function as1020 endpoint1021 :param view_func: the function to call when serving a request to the1022 provided endpoint1023+ :param provide_automatic_options: controls whether the ``OPTIONS``1024+ method should be added automatically. This can also be controlled1025+ by setting the ``view_func.provide_automatic_options = False``1026+ before adding the rule.1027 :param options: the options to be forwarded to the underlying1028 :class:`~werkzeug.routing.Rule` object. A change1029 to Werkzeug is handling of method options. methods1030 is a list of methods this rule should be limited21 unmodified lines1052 required_methods = set(getattr(view_func, 'required_methods', ()))1053 1054 # starting with Flask 0.8 the view_func object can disable and1055 # force-enable the automatic options handling.1056+ if provide_automatic_options is None:1032- provide_automatic_options = getattr(view_func,1033- 'provide_automatic_options', None)1057+ provide_automatic_options = getattr(view_func,1058+ 'provide_automatic_options', None)1059 1060 if provide_automatic_options is None:1061 if 'OPTIONS' not in methods:1062 provide_automatic_options = True77 unmodified lines1140 return exc_class, None1141 1142 @setupmethod1143 def errorhandler(self, code_or_exception):1119- """A decorator that is used to register a function give a given1144+ """A decorator that is used to register a function given an1145 error code. Example::1146 1147 @app.errorhandler(404)1148 def page_not_found(error):29 unmodified lines1178 One can now additionally also register custom exception types1179 that do not necessarily have to be a subclass of the1180 :class:`~werkzeug.exceptions.HTTPException` class.1181 1157- :param code: the code as integer for the handler1182+ :param code_or_exception: the code as integer for the handler, or1183+ an arbitrary exception1184 """1185 def decorator(f):1186 self._register_error_handler(None, code_or_exception, f)1187 return f185 unmodified lines1373 that they will fail. If they do execute code that might fail they1374 will have to surround the execution of these code by try/except1375 statements and log occurring errors.1376 1351- 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 80 unmodified lines1462 1463 def find_handler(handler_map):1464 if not handler_map:1465 return1440- queue = deque(exc_class.__mro__)1441- # Protect from geniuses who might create circular references in1442- # __mro__1443- done = set()1444-1445- while queue:1446- cls = queue.popleft()1447- if cls in done:1448- continue1449- done.add(cls)1466+ for cls in exc_class.__mro__:1467 handler = handler_map.get(cls)1468 if handler is not None:1469 # cache for next time exc_class is raised1470 handler_map[exc_class] = handler1471 return handler1472 1456- queue.extend(cls.__mro__)1457-1473 # try blueprint handlers1474 handler = find_handler(self.error_handler_spec1475 .get(request.blueprint, {})1476 .get(code))93 unmodified lines1570 1571 self.log_exception((exc_type, exc_value, tb))1572 if handler is None:1573 return InternalServerError()1559- return handler(e)1574+ return self.finalize_request(handler(e), from_error_handler=True)1575 1576 def log_exception(self, exc_info):1577 """Logs an exception. This is called by :meth:`handle_exception`1578 if debugging is disabled and right before the handler is called.59 unmodified lines1638 if rv is None:1639 rv = self.dispatch_request()1640 except Exception as e:1641 rv = self.handle_user_exception(e)1642+ return self.finalize_request(rv)1643+1644+ def finalize_request(self, rv, from_error_handler=False):1645+ """Given the return value from a view function this finalizes1646+ the request by converting it into a response and invoking the1647+ postprocessing functions. This is invoked for both normal1648+ request dispatching as well as error handlers.1649+1650+ Because this means that it might be called as a result of a1651+ failure a special safe mode is available which can be enabled1652+ with the `from_error_handler` flag. If enabled, failures in1653+ response processing will be logged and otherwise ignored.1654+1655+ :internal:1656+ """1657 response = self.make_response(rv)1658+ try:1628- response = self.process_response(response)1629- request_finished.send(self, response=response)1659+ response = self.process_response(response)1660+ request_finished.send(self, response=response)1661+ except Exception:1662+ if not from_error_handler:1663+ raise1664+ self.logger.exception('Request finalizing failed with an '1665+ 'error while handling an error')1666 return response1667 1668 def try_trigger_before_first_request_functions(self):1669 """Called before each request and will ensure that it triggers338 unmodified lines2008 try:2009 response = self.full_dispatch_request()2010 except Exception as e:2011 error = e1976- response = self.make_response(self.handle_exception(e))2012+ response = self.handle_exception(e)2013+ except:2014+ error = sys.exc_info()[1]2015+ raise2016 return response(environ, start_response)2017 finally:2018 if self.should_ignore_error(error):2019 error = None11 unmodified linesmodified:flask/cli.py+30 added-7 removed
9 unmodified lines10 """11 12 import os13 import sys14+import traceback15 from threading import Lock, Thread16 from functools import update_wrapper17 18 import click67 unmodified lines86 else:87 module = app_id88 app_obj = None89 90+ try:89- __import__(module)91+ __import__(module)92+ except ImportError:93+ # Reraise the ImportError if it occurred within the imported module.94+ # Determine this by checking whether the trace has a depth > 1.95+ if sys.exc_info()[-1].tb_next:96+ stack_trace = traceback.format_exc()97+ raise NoAppException('There was an error trying to import'98+ ' the app (%s):\n%s' % (module, stack_trace))99+ else:100+ raise NoAppException('The file/path provided (%s) does not appear'101+ ' to exist. Please verify the path is '102+ 'correct. If app is not on PYTHONPATH, '103+ 'ensure the extension is .py' % module)104+105 mod = sys.modules[module]106 if app_obj is None:107 app = find_best_app(mod)108 else:30 unmodified lines139 callback=get_version,140 is_flag=True, is_eager=True)141 142 class DispatchingApp(object):128- """Special application that dispatches to a flask application which143+ """Special application that dispatches to a Flask application which144 is imported by name in a background thread. If an error happens130- it is is recorded and shows as part of the WSGI handling which in case145+ it is recorded and shown as part of the WSGI handling which in case146 of the Werkzeug debugger means that it shows up in the browser.147 """148 149 def __init__(self, loader, use_eager_loading=False):220 unmodified lines370 # Here we intentionally swallow all exceptions as we don't371 # want the help page to break if the app does not exist.372 # If someone attempts to use the command we try to create373 # the app again and this will give us the error.359- pass374+ # However, we will not do so silently because that would confuse375+ # users.376+ traceback.print_exc()377 return sorted(rv)378 379 def main(self, *args, **kwargs):380 obj = kwargs.get('obj')35 unmodified lines416 Flask is enabled and disabled otherwise.417 """418 from werkzeug.serving import run_simple419 420+ # Set a global flag that indicates that we were invoked from the421+ # command line interface provided server command. This is detected422+ # by Flask.run to make the call into a no-op. This is necessary to423+ # avoid ugly errors when the script that is loaded here also attempts424+ # to start a server.425+ os.environ['FLASK_RUN_FROM_CLI_SERVER'] = '1'426+427 debug = get_debug_flag()428 if reload is None:429 reload = bool(debug)430 if debugger is None:15 unmodified lines446 if debug is not None:447 print(' * Forcing debug mode %s' % (debug and 'on' or 'off'))448 449 run_simple(host, port, app, use_reloader=reload,426- use_debugger=debugger, threaded=with_threads,427- passthrough_errors=True)450+ use_debugger=debugger, threaded=with_threads)451 452 453 @click.command('shell', short_help='Runs a shell in the app context.')454 @with_appcontext31 unmodified lines486 487 cli = FlaskGroup(help="""\488 This shell command acts as general utility script for Flask applications.489 467-It loads the application configured (either through the FLASK_APP environment490+It loads the application configured (through the FLASK_APP environment491 variable) and then provides commands either provided by the application or492 Flask itself.493 494 The most useful commands are the "run" and "shell" command.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+86 added-32 removed
15 unmodified lines16 import mimetypes17 from time import time18 from zlib import adler3219 from threading import RLock20+import unicodedata21 from werkzeug.routing import BuildError22 from functools import update_wrapper23 24 try:25 from werkzeug.urls import url_quote26 except ImportError:27 from urlparse import quote as url_quote28 28-from werkzeug.datastructures import Headers29-from werkzeug.exceptions import BadRequest, NotFound29+from werkzeug.datastructures import Headers, Range30+from werkzeug.exceptions import BadRequest, NotFound, \31+ RequestedRangeNotSatisfiable32 33 # this was moved in 0.734 try:35 from werkzeug.wsgi import wrap_file4 unmodified lines40 41 from .signals import message_flashed42 from .globals import session, _request_ctx_stack, _app_ctx_stack, \43 current_app, request42-from ._compat import string_types, text_type, PY244+from ._compat import string_types, text_type45 46 47 # sentinel48 _missing = object()9 unmodified lines58 def get_debug_flag(default=None):59 val = os.environ.get('FLASK_DEBUG')60 if not val:61 return default60- return val not in ('0', 'false', 'no')62+ return val.lower() not in ('0', 'false', 'no')63 64 65 def _endpoint_from_view_func(view_func):66 """Internal helper that returns the default endpoint for a given263 unmodified lines330 # deal with that sort of stuff.331 values['_external'] = external332 values['_anchor'] = anchor333 values['_method'] = method334+ values['_scheme'] = scheme335 return appctx.app.handle_url_build_error(error, endpoint, values)336 337 if anchor is not None:338 rv += '#' + url_quote(anchor)100 unmodified lines439 you can set the application's :attr:`~Flask.use_x_sendfile` attribute440 to ``True`` to directly emit an ``X-Sendfile`` header. This however441 requires support of the underlying webserver for ``X-Sendfile``.442 440- You must explicitly provide the mimetype for the filename or file object.443+ By default it will try to guess the mimetype for you, but you can444+ also explicitly provide one. For extra security you probably want445+ to send certain files as attachment (HTML for instance). The mimetype446+ guessing requires a `filename` or an `attachment_filename` to be447+ provided.448 449+ ETags will also be attached automatically if a `filename` is provided. You450+ can turn this off by setting `add_etags=False`.451+452+ If `conditional=True` and `filename` is provided, this method will try to453+ upgrade the response stream to support range requests. This will allow454+ the request to be answered with partial content response.455+456 Please never pass filenames to this function from user sources;457 you should use :func:`send_from_directory` instead.458 459 .. versionadded:: 0.211 unmodified lines471 .. versionchanged:: 0.9472 cache_timeout pulls its default from application config, when None.473 474 .. 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.475+ The filename is no longer automatically inferred from file objects. If476+ you want to use automatic mimetype and etag support, pass a filepath via477+ `filename_or_fp` or `attachment_filename`.478 479+ .. versionchanged:: 0.12480+ The `attachment_filename` is preferred over `filename` for MIME-type481+ detection.482+ 483+ .. versionchanged:: 0.13484+ UTF-8 filenames, as specified in `RFC 2231`_, are supported.485+ 486+ .. _RFC 2231: https://tools.ietf.org/html/rfc2231#section-4487+465- :param filename_or_fp: the filename of the file to send in `latin-1`.488+ :param filename_or_fp: the filename of the file to send.489 This is relative to the :attr:`~Flask.root_path`490 if a relative path is specified.491 Alternatively a file object might be provided in492 which case ``X-Sendfile`` might not work and fall493 back to the traditional method. Make sure that the494 file pointer is positioned at the start of data to495 send before calling :func:`send_file`.473- :param mimetype: the mimetype of the file if provided, otherwise474- auto detection happens.496+ :param mimetype: the mimetype of the file if provided. If a file path is497+ given, auto detection happens as fallback, otherwise an498+ error will be raised.499 :param as_attachment: set to ``True`` if you want to send this file with500 a ``Content-Disposition: attachment`` header.501 :param attachment_filename: the filename for the attachment if it502 differs from the file's filename.8 unmodified lines511 a :class:`~datetime.datetime` or timestamp.512 If a file was passed, this overrides its mtime.513 """514 mtime = None515+ fsize = None516 if isinstance(filename_or_fp, string_types):517 filename = filename_or_fp518+ if not os.path.isabs(filename):519+ filename = os.path.join(current_app.root_path, filename)520 file = None521+ if attachment_filename is None:522+ attachment_filename = os.path.basename(filename)523 else:524 file = filename_or_fp496- filename = getattr(file, 'name', None)525+ filename = None526 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]527 if mimetype is None:528+ if attachment_filename is not None:529+ mimetype = mimetypes.guess_type(attachment_filename)[0] \504- mimetype = 'application/octet-stream'530+ or 'application/octet-stream'531 532+ if mimetype is None:533+ raise ValueError(534+ 'Unable to infer MIME-type because no filename is available. '535+ 'Please set either `attachment_filename`, pass a filepath to '536+ '`filename_or_fp` or set your own MIME-type via `mimetype`.'537+ )538+539 headers = Headers()540 if as_attachment:541 if attachment_filename is None:509- if filename is None:510- raise TypeError('filename unavailable, required for '511- 'sending as attachment')542+ raise TypeError('filename unavailable, required for '543+ 'sending as attachment')512- attachment_filename = os.path.basename(filename)513- headers.add('Content-Disposition', 'attachment',514- filename=attachment_filename)544 545+ try:546+ attachment_filename = attachment_filename.encode('latin-1')547+ except UnicodeEncodeError:548+ filenames = {549+ 'filename': unicodedata.normalize(550+ 'NFKD', attachment_filename).encode('latin-1', 'ignore'),551+ 'filename*': "UTF-8''%s" % url_quote(attachment_filename),552+ }553+ else:554+ filenames = {'filename': attachment_filename}555+556+ headers.add('Content-Disposition', 'attachment', **filenames)557+558 if current_app.use_x_sendfile and filename:559 if file is not None:560 file.close()561 headers['X-Sendfile'] = filename520- headers['Content-Length'] = os.path.getsize(filename)562+ fsize = os.path.getsize(filename)563+ headers['Content-Length'] = fsize564 data = None565 else:566 if file is None:567 file = open(filename, 'rb')568 mtime = os.path.getmtime(filename)526- headers['Content-Length'] = os.path.getsize(filename)569+ fsize = os.path.getsize(filename)570+ headers['Content-Length'] = fsize571 data = wrap_file(request.environ, file)572 573 rv = current_app.response_class(data, mimetype=mimetype, headers=headers,574 direct_passthrough=True)9 unmodified lines584 if cache_timeout is not None:585 rv.cache_control.max_age = cache_timeout586 rv.expires = int(time() + cache_timeout)587 544- if add_etags and filename is not None and file is None:588+ if add_etags and filename is not None:589 from warnings import warn590 591 try:592 rv.set_etag('%s-%s-%s' % (7 unmodified lines600 except OSError:601 warn('Access %s failed, maybe it does not exist, so ignore etags in '602 'headers' % filename, stacklevel=2)603 560- if conditional:604+ if conditional:605+ if callable(getattr(Range, 'to_content_range_header', None)):606+ # Werkzeug supports Range Requests607+ # Remove this test when support for Werkzeug <0.12 is dropped608+ try:609+ rv = rv.make_conditional(request, accept_ranges=True,610+ complete_length=fsize)611+ except RequestedRangeNotSatisfiable:612+ file.close()613+ raise614+ else:615 rv = rv.make_conditional(request)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)616+ # make sure we don't send x-sendfile for servers that617+ # ignore the 304 status code for x-sendfile.618+ if rv.status_code == 304:619+ rv.headers.pop('x-sendfile', None)620 return rv621 622 623 def safe_join(directory, *pathnames):355 unmodified linesmodified:flask/json.py+7 added-8 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.226 unmodified lines235 .. versionchanged:: 0.11236 Added support for serializing top-level arrays. This introduces a237 security risk in ancient browsers. See :ref:`json-security` for details.238 239- This function's response will be pretty printed if it was not requested240- with ``X-Requested-With: XMLHttpRequest`` to simplify debugging unless241- the ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to false.242- Compressed (not pretty) formatting currently means no indents and no243- spaces after separators.239+ This function's response will be pretty printed if the240+ ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to True or the241+ Flask app is running in debug mode. Compressed (not pretty) formatting242+ currently means no indents and no spaces after separators.243 244 .. versionadded:: 0.2245 """246 247 indent = None248 separators = (',', ':')249 251- if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and not request.is_xhr:250+ if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug:251 indent = 2252 separators = (', ', ': ')253 254 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+15 added-11 removed
82 unmodified lines83 84 def dumps(self, value):85 return json.dumps(_tag(value), separators=(',', ':'))86 87+ LOADS_MAP = {88+ ' t': tuple,89+ ' u': uuid.UUID,90+ ' b': b64decode,91+ ' m': Markup,92+ ' d': parse_date,93+ }94+95 def loads(self, value):96 def object_hook(obj):97 if len(obj) != 1:98 return obj99 the_key, the_value = next(iteritems(obj))92- if the_key == ' t':93- return tuple(the_value)94- elif the_key == ' u':95- return uuid.UUID(the_value)96- elif the_key == ' b':97- return b64decode(the_value)98- elif the_key == ' m':99- return Markup(the_value)100- elif the_key == ' d':101- return parse_date(the_value)100+ # Check the key for a corresponding function101+ return_function = self.LOADS_MAP.get(the_key)102+ if return_function:103+ # Pass the value to the function104+ return return_function(the_value)105+ # Didn't find a function for this object106 return obj107 return json.loads(value, object_hook=object_hook)108 109 61 unmodified lines171 #: this type.172 null_session_class = NullSession173 174 #: A flag that indicates if the session interface is pickle based.171- #: This can be used by flask extensions to make a decision in regards175+ #: This can be used by Flask extensions to make a decision in regards176 #: to how to deal with the session object.177 #:178 #: .. versionadded:: 0.10179 pickle_based = False187 unmodified linesmodified:flask/signals.py+1 added-1 removed
35 unmodified lines36 connect = disconnect = has_receivers_for = receivers_for = \37 temporarily_connected_to = connected_to = _fail38 del _fail39 40-# The namespace for code signals. If you are not flask code, do40+# The namespace for code signals. If you are not Flask code, do41 # not put signals in here. Create your own namespace instead.42 _signals = Namespace()43 44 12 unmodified linesmodified:flask/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+1 added-1 removed
125 unmodified lines126 127 class MethodView(with_metaclass(MethodViewType, View)):128 """Like a regular class-based view but that dispatches requests to129 particular methods. For instance if you implement a method called130- :meth:`get` it means you will response to ``'GET'`` requests and130+ :meth:`get` it means it will respond to ``'GET'`` requests and131 the :meth:`dispatch_request` implementation will automatically132 forward your request to that. Also :attr:`options` is set for you133 automatically::134 19 unmodified linesmodified: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+144 added-5 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('/')255 unmodified lines380 381 client = app.test_client()382 rv = client.get('/')383 assert 'set-cookie' in rv.headers336- match = re.search(r'\bexpires=([^;]+)(?i)', rv.headers['set-cookie'])384+ match = re.search(r'(?i)\bexpires=([^;]+)', rv.headers['set-cookie'])385 expires = parse_date(match.group())386 expected = datetime.utcnow() + app.permanent_session_lifetime387 assert expires.year == expected.year388 assert expires.month == expected.month426 unmodified lines815 assert rv.status_code == 403816 assert b'forbidden' == rv.data817 818 819+def test_error_handling_processing():820+ app = flask.Flask(__name__)821+ app.config['LOGGER_HANDLER_POLICY'] = 'never'822+823+ @app.errorhandler(500)824+ def internal_server_error(e):825+ return 'internal server error', 500826+827+ @app.route('/')828+ def broken_func():829+ 1 // 0830+831+ @app.after_request832+ def after_request(resp):833+ resp.mimetype = 'text/x-special'834+ return resp835+836+ with app.test_client() as c:837+ resp = c.get('/')838+ assert resp.mimetype == 'text/x-special'839+ assert resp.data == b'internal server error'840+841+842+def test_baseexception_error_handling():843+ app = flask.Flask(__name__)844+ app.config['LOGGER_HANDLER_POLICY'] = 'never'845+846+ @app.route('/')847+ def broken_func():848+ raise KeyboardInterrupt()849+850+ with app.test_client() as c:851+ with pytest.raises(KeyboardInterrupt):852+ c.get('/')853+854+ ctx = flask._request_ctx_stack.top855+ assert ctx.preserved856+ assert type(ctx._preserved_exc) is KeyboardInterrupt857+858+859 def test_before_request_and_routing_errors():860 app = flask.Flask(__name__)861 862 @app.before_request196 unmodified lines1059 with app.test_request_context():1060 rv = flask.make_response(1061 flask.jsonify({'msg': 'W00t'}), 400)1062 assert rv.status_code == 400975- assert rv.data == b'{\n "msg": "W00t"\n}\n'1063+ assert rv.data == b'{"msg":"W00t"}\n'1064 assert rv.mimetype == 'application/json'1065 1066 rv = flask.make_response(1067 flask.Response(''), 400)110 unmodified lines1178 with app.test_request_context():1179 pytest.raises(BuildError, flask.url_for, 'not.existing')1180 1181 1182+def test_url_for_passes_special_values_to_build_error_handler():1183+ app = flask.Flask(__name__)1184+1185+ @app.url_build_error_handlers.append1186+ def handler(error, endpoint, values):1187+ assert values == {1188+ '_external': False,1189+ '_anchor': None,1190+ '_method': None,1191+ '_scheme': None,1192+ }1193+ return 'handled'1194+1195+ with app.test_request_context():1196+ flask.url_for('/')1197+1198+1199 def test_custom_converters():1200 from werkzeug.routing import BaseConverter1201 1202 class ListConverter(BaseConverter):49 unmodified lines1252 with app.test_request_context():1253 assert flask.url_for('static', filename='index.html') == '/foo/index.html'1254 1255 1256+def test_static_route_with_host_matching():1257+ app = flask.Flask(__name__, host_matching=True, static_host='example.com')1258+ c = app.test_client()1259+ rv = c.get('http://example.com/static/index.html')1260+ assert rv.status_code == 2001261+ rv.close()1262+ with app.test_request_context():1263+ rv = flask.url_for('static', filename='index.html', _external=True)1264+ assert rv == 'http://example.com/static/index.html'1265+ # Providing static_host without host_matching=True should error.1266+ with pytest.raises(Exception):1267+ flask.Flask(__name__, static_host='example.com')1268+ # Providing host_matching=True with static_folder but without static_host should error.1269+ with pytest.raises(Exception):1270+ flask.Flask(__name__, host_matching=True)1271+ # Providing host_matching=True without static_host but with static_folder=None should not error.1272+ flask.Flask(__name__, host_matching=True, static_folder=None)1273+1274+1275 def test_none_response():1276 app = flask.Flask(__name__)1277 app.testing = True1278 112 unmodified lines1391 app = flask.Flask(__name__)1392 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1393 app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1394 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)1271- # make sure werkzeug always passes errors through1272- assert rv['passthrough_errors']1395 1396 1397 def test_max_content_length():1398 app = flask.Flask(__name__)382 unmodified lines1781 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1782 hostname, port = 'localhost', 80001783 app.run(hostname, port, debug=True)1784 assert rv['result'] == 'running on %s:%s ...' % (hostname, port)1785+1786+1787+@pytest.mark.parametrize('host,port,expect_host,expect_port', (1788+ (None, None, 'pocoo.org', 8080),1789+ ('localhost', None, 'localhost', 8080),1790+ (None, 80, 'pocoo.org', 80),1791+ ('localhost', 80, 'localhost', 80),1792+))1793+def test_run_from_config(monkeypatch, host, port, expect_host, expect_port):1794+ def run_simple_mock(hostname, port, *args, **kwargs):1795+ assert hostname == expect_host1796+ assert port == expect_port1797+1798+ monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1799+ app = flask.Flask(__name__)1800+ app.config['SERVER_NAME'] = 'pocoo.org:8080'1801+ app.run(host, port)modified:tests/test_blueprints.py+19 added
353 unmodified lines354 assert rv.status_code == 404355 rv = c.get('/py/bar/123')356 assert rv.status_code == 404357 358+359+def test_endpoint_decorator():360+ from werkzeug.routing import Rule361+ app = flask.Flask(__name__)362+ app.url_map.add(Rule('/foo', endpoint='bar'))363+364+ bp = flask.Blueprint('bp', __name__)365+366+ @bp.endpoint('bar')367+ def foobar():368+ return flask.request.endpoint369+370+ app.register_blueprint(bp, url_prefix='/bp_prefix')371+372+ c = app.test_client()373+ assert c.get('/foo').data == b'bar'374+ assert c.get('/bp_prefix/bar').status_code == 404375+376+377 def test_template_filter():378 bp = flask.Blueprint('bp', __name__)379 @bp.app_template_filter()380 def my_reverse(s):213 unmodified linesmodified:tests/test_cli.py+50 added-12 removed
20 unmodified lines21 from flask import Flask, current_app22 23 from flask.cli import AppGroup, FlaskGroup, NoAppException, ScriptInfo, \24 find_best_app, locate_app, with_appcontext, prepare_exec_for_file, \25- find_default_import_path25+ find_default_import_path, get_version26 27 28 def test_cli_name(test_apps):29 """Make sure the CLI object's name is the app's name and not the app itself"""1 unmodified line31 assert testapp.cli.name == testapp.name32 33 34 def test_find_best_app(test_apps):35- """Test of find_best_app."""36- class mod:35+ """Test if `find_best_app` behaves as expected with different combinations of input."""36+ class Module:37 app = Flask('appname')38- assert find_best_app(mod) == mod.app38+ assert find_best_app(Module) == Module.app39 40- class mod:40+ class Module:41 application = Flask('appname')42- assert find_best_app(mod) == mod.application42+ assert find_best_app(Module) == Module.application43 44- class mod:44+ class Module:45 myapp = Flask('appname')46- assert find_best_app(mod) == mod.myapp46+ assert find_best_app(Module) == Module.myapp47 48- class mod:49- myapp = Flask('appname')48+ class Module:49+ pass50+ pytest.raises(NoAppException, find_best_app, Module)51+52+ class Module:53+ myapp1 = Flask('appname1')54 myapp2 = Flask('appname2')55+ pytest.raises(NoAppException, find_best_app, Module)56 52- pytest.raises(NoAppException, find_best_app, mod)57 54-58 def test_prepare_exec_for_file(test_apps):59 """Expect the correct path to be set and the correct module name to be returned.60 61 :func:`prepare_exec_for_file` has a side effect, where17 unmodified lines79 """Test of locate_app."""80 assert locate_app("cliapp.app").name == "testapp"81 assert locate_app("cliapp.app:testapp").name == "testapp"82 assert locate_app("cliapp.multiapp:app1").name == "app1"83+ pytest.raises(NoAppException, locate_app, "notanpp.py")84+ pytest.raises(NoAppException, locate_app, "cliapp/app")85 pytest.raises(RuntimeError, locate_app, "cliapp.app:notanapp")86+ pytest.raises(NoAppException, locate_app, "cliapp.importerrorapp")87 88 89 def test_find_default_import_path(test_apps, monkeypatch, tmpdir):90 """Test of find_default_import_path."""7 unmodified lines98 expect_rv = prepare_exec_for_file(str(tmpfile))99 assert find_default_import_path() == expect_rv100 101 102+def test_get_version(test_apps, capsys):103+ """Test of get_version."""104+ from flask import __version__ as flask_ver105+ from sys import version as py_ver106+ class MockCtx(object):107+ resilient_parsing = False108+ color = None109+ def exit(self): return110+ ctx = MockCtx()111+ get_version(ctx, None, "test")112+ out, err = capsys.readouterr()113+ assert flask_ver in out114+ assert py_ver in out115+116+117 def test_scriptinfo(test_apps):118 """Test of ScriptInfo."""119 obj = ScriptInfo(app_import_path="cliapp.app:testapp")120 assert obj.load_app().name == "testapp"69 unmodified lines190 runner = CliRunner()191 result = runner.invoke(cli, ['test'])192 assert result.exit_code == 0193 assert result.output == 'flaskgroup\n'194+195+196+def test_print_exceptions():197+ """Print the stacktrace if the CLI."""198+ def create_app(info):199+ raise Exception("oh no")200+ return Flask("flaskgroup")201+202+ @click.group(cls=FlaskGroup, create_app=create_app)203+ def cli(**params):204+ pass205+206+ runner = CliRunner()207+ result = runner.invoke(cli, ['--help'])208+ assert result.exit_code == 0209+ assert 'Exception: oh no' in result.output210+ assert 'Traceback' in result.outputmodified:tests/test_config.py+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+150 added-25 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():76 unmodified lines288 289 def test_json_key_sorting(self):290 app = flask.Flask(__name__)291 app.testing = True292+ app.debug = True293+294 assert app.config['JSON_SORT_KEYS'] == True295 d = dict.fromkeys(range(20), 'foo')296 297 @app.route('/')91 unmodified lines389 last_modified = datetime.datetime(1999, 1, 1)390 391 @app.route('/')392 def index():358- return flask.send_file(StringIO("party like it's"), last_modified=last_modified)393+ return flask.send_file(StringIO("party like it's"),394+ last_modified=last_modified,395+ mimetype='text/plain')396 397 c = app.test_client()398 rv = c.get('/')399 assert rv.last_modified == last_modified400 401+ def test_send_file_object_without_mimetype(self):402+ app = flask.Flask(__name__)403+404+ with app.test_request_context():405+ with pytest.raises(ValueError) as excinfo:406+ flask.send_file(StringIO("LOL"))407+ assert 'Unable to infer MIME-type' in str(excinfo)408+ assert 'no filename is available' in str(excinfo)409+410+ with app.test_request_context():411+ flask.send_file(StringIO("LOL"), attachment_filename='filename')412+413 def test_send_file_object(self):414 app = flask.Flask(__name__)415 416 with app.test_request_context():417 with open(os.path.join(app.root_path, 'static/index.html'), mode='rb') as f:369- rv = flask.send_file(f)418+ rv = flask.send_file(f, mimetype='text/html')419 rv.direct_passthrough = False420 with app.open_resource('static/index.html') as f:421 assert rv.data == f.read()422 assert rv.mimetype == 'text/html'2 unmodified lines425 app.use_x_sendfile = True426 427 with app.test_request_context():428 with open(os.path.join(app.root_path, 'static/index.html')) as f:380- rv = flask.send_file(f)429+ rv = flask.send_file(f, mimetype='text/html')430 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')431+ assert 'x-sendfile' not in rv.headers432 rv.close()433 434 app.use_x_sendfile = False435 with app.test_request_context():436 f = StringIO('Test')390- rv = flask.send_file(f)437+ rv = flask.send_file(f, mimetype='application/octet-stream')438 rv.direct_passthrough = False439 assert rv.data == b'Test'440 assert rv.mimetype == 'application/octet-stream'441 rv.close()4 unmodified lines446 def __getattr__(self, name):447 return getattr(self._io, name)448 f = PyStringIO('Test')449 f.name = 'test.txt'403- rv = flask.send_file(f)450+ rv = flask.send_file(f, attachment_filename=f.name)451 rv.direct_passthrough = False452 assert rv.data == b'Test'453 assert rv.mimetype == 'text/plain'454 rv.close()8 unmodified lines463 app.use_x_sendfile = True464 465 with app.test_request_context():466 f = StringIO('Test')420- rv = flask.send_file(f)467+ rv = flask.send_file(f, mimetype='text/html')468 assert 'x-sendfile' not in rv.headers469 rv.close()470 471+ @pytest.mark.skipif(472+ not callable(getattr(Range, 'to_content_range_header', None)),473+ reason="not implement within werkzeug"474+ )475+ def test_send_file_range_request(self):476+ app = flask.Flask(__name__)477+478+ @app.route('/')479+ def index():480+ return flask.send_file('static/index.html', conditional=True)481+482+ c = app.test_client()483+484+ rv = c.get('/', headers={'Range': 'bytes=4-15'})485+ assert rv.status_code == 206486+ with app.open_resource('static/index.html') as f:487+ assert rv.data == f.read()[4:16]488+ rv.close()489+490+ rv = c.get('/', headers={'Range': 'bytes=4-'})491+ assert rv.status_code == 206492+ with app.open_resource('static/index.html') as f:493+ assert rv.data == f.read()[4:]494+ rv.close()495+496+ rv = c.get('/', headers={'Range': 'bytes=4-1000'})497+ assert rv.status_code == 206498+ with app.open_resource('static/index.html') as f:499+ assert rv.data == f.read()[4:]500+ rv.close()501+502+ rv = c.get('/', headers={'Range': 'bytes=-10'})503+ assert rv.status_code == 206504+ with app.open_resource('static/index.html') as f:505+ assert rv.data == f.read()[-10:]506+ rv.close()507+508+ rv = c.get('/', headers={'Range': 'bytes=1000-'})509+ assert rv.status_code == 416510+ rv.close()511+512+ rv = c.get('/', headers={'Range': 'bytes=-'})513+ assert rv.status_code == 416514+ rv.close()515+516+ rv = c.get('/', headers={'Range': 'somethingsomething'})517+ assert rv.status_code == 416518+ rv.close()519+520+ last_modified = datetime.datetime.utcfromtimestamp(os.path.getmtime(521+ os.path.join(app.root_path, 'static/index.html'))).replace(522+ microsecond=0)523+524+ rv = c.get('/', headers={'Range': 'bytes=4-15',525+ 'If-Range': http_date(last_modified)})526+ assert rv.status_code == 206527+ rv.close()528+529+ rv = c.get('/', headers={'Range': 'bytes=4-15', 'If-Range': http_date(530+ datetime.datetime(1999, 1, 1))})531+ assert rv.status_code == 200532+ rv.close()533+534 def test_attachment(self):535 app = flask.Flask(__name__)536 with app.test_request_context():537 with open(os.path.join(app.root_path, 'static/index.html')) as f:428- rv = flask.send_file(f, as_attachment=True)538+ rv = flask.send_file(f, as_attachment=True,539+ attachment_filename='index.html')540 value, options = \541 parse_options_header(rv.headers['Content-Disposition'])542 assert value == 'attachment'543+ assert options['filename'] == 'index.html'544+ assert 'filename*' not in rv.headers['Content-Disposition']545 rv.close()546 547 with app.test_request_context():435- assert options['filename'] == 'index.html'548 rv = flask.send_file('static/index.html', as_attachment=True)549 value, options = parse_options_header(rv.headers['Content-Disposition'])550 assert value == 'attachment'551 assert options['filename'] == 'index.html'8 unmodified lines560 assert value == 'attachment'561 assert options['filename'] == 'index.txt'562 rv.close()563 564+ def test_attachment_with_utf8_filename(self):565+ app = flask.Flask(__name__)566+567+ with app.test_request_context():568+ rv = flask.send_file('static/index.html', as_attachment=True, attachment_filename=u'Ñandú/pingüino.txt')569+ content_disposition = set(rv.headers['Content-Disposition'].split('; '))570+ assert content_disposition == set((571+ 'attachment',572+ 'filename="Nandu/pinguino.txt"',573+ "filename*=UTF-8''%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt"574+ ))575+ rv.close()576+577 def test_static_file(self):578 app = flask.Flask(__name__)579 # default cache timeout is 12 hours580 with app.test_request_context():323 unmodified linesmodified: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 linesadded:.gitattributes+1 added
1+CHANGES merge=unionmodified:.gitignore+6 added
9 unmodified lines10 _mailinglist11 .tox12 .cache/13 .idea/14+15+# Coverage reports16+htmlcov17+.coverage18+.coverage.*19+*,covermodified:.travis.yml+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+56 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+28+.. _#1489: https://github.com/pallets/flask/pull/148929+.. _#2017: https://github.com/pallets/flask/pull/201730+.. _#2223: https://github.com/pallets/flask/pull/222331+32+Version 0.12.133+--------------34+35+Bugfix release, released on March 31st 201736+37+- Prevent `flask run` from showing a NoAppException when an ImportError occurs38+ within the imported application module.39+- Fix encoding behavior of ``app.config.from_pyfile`` for Python 3. Fix40+ ``#2118``.41+- Use the ``SERVER_NAME`` config if it is present as default values for42+ ``app.run``. ``#2109``, ``#2152``43+- Call `ctx.auto_pop` with the exception object instead of `None`, in the44+ event that a `BaseException` such as `KeyboardInterrupt` is raised in a45+ request handler.46+47 Version 0.1248 ------------49 50+Released on December 21st 2016, codename Punsch.51+52 - 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``.53+- Mimetype guessing and ETag generation for file-like objects in ``send_file``54+ has been removed, as per issue ``#104``. See pull request ``#1849``.55+- Mimetype guessing in ``send_file`` now fails loudly and doesn't fall back to56+ ``application/octet-stream``. See pull request ``#1988``.57 - Make ``flask.safe_join`` able to join multiple paths like ``os.path.join``58 (pull request ``#1730``).59+- Revert a behavior change that made the dev server crash instead of returning60+ a Internal Server Error (pull request ``#2006``).61+- Correctly invoke response handlers for both regular request dispatching as62+ well as error handlers.63+- Disable logger propagation by default for the app logger.64+- Add support for range requests in ``send_file``.65+- ``app.test_client`` includes preset default environment, which can now be66+ directly set, instead of per ``client.get``.67 68 Version 0.11.269 --------------70 306 unmodified lines377 error if not handled. This is a backwards incompatible change.378 - Applications now not only have a root path where the resources and modules379 are located but also an instance path which is the designated place to380 drop files that are modified at runtime (uploads etc.). Also this is328- conceptionally only instance depending and outside version control so it's381+ conceptually only instance depending and outside version control so it's382 the perfect place to put configuration files etc. For more information383 see :ref:`instance-folders`.384 - Added the ``APPLICATION_ROOT`` configuration variable.385 - Implemented :meth:`~flask.testing.TestClient.session_transaction` to257 unmodified linesmodified:CONTRIBUTING.rst+31 added-6 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 35 Running the testsuite1 unmodified line37 38 You probably want to set up a `virtualenv39 <https://virtualenv.readthedocs.io/en/latest/index.html>`_.40 41-The minimal requirement for running the testsuite is ``py.test``. You can41+The minimal requirement for running the testsuite is ``pytest``. You can42 install it with::43 44 pip install pytest45 7 unmodified lines53 pip install --editable .54 55 Then you can run the testsuite with::56 57- py.test57+ pytest58 59-With only py.test installed, a large part of the testsuite will get skipped59+With only pytest installed, a large part of the testsuite will get skipped60 though. Whether this is relevant depends on which part of Flask you're working61 on. Travis is set up to run the full testsuite when you submit your pull62 request anyways.63 14 unmodified lines78 pip install pytest-cov79 80 After this has been installed, you can output a report to the command line using this command::81 82- py.test --cov=flask tests/82+ pytest --cov=flask tests/83 84 Generate a HTML report can be done using this command::85 86- py.test --cov-report html --cov=flask tests/86+ pytest --cov-report html --cov=flask tests/87 88 Full docs on ``coverage.py`` are here: https://coverage.readthedocs.io89 90+Caution91+=======92+pushing93+-------94+This repository contains several zero-padded file modes that may cause issues when pushing this repository to git hosts other than github. Fixing this is destructive to the commit history, so we suggest ignoring these warnings. If it fails to push and you're using a self-hosted git service like Gitlab, you can turn off repository checks in the admin panel.95+96+97+cloning98+-------99+The zero-padded file modes files above can cause issues while cloning, too. If you have100+101+::102+103+ [fetch]104+ fsckobjects = true105+106+or107+108+::109+110+ [receive]111+ fsckObjects = true112+113+114+set in your git configuration file, cloning this repository will fail. The only solution is to set both of the above settings to false while cloning, and then setting them back to true after the cloning is finished.modified:Makefile+2 added-5 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- tox11-9 audit:10 python setup.py audit11 12 release:29 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-pytest1+toxmodified: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