Skip to content
Myr

Merge branch '0.11-maintenance'

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 f19d3bd, 17d4cb3 · Browse files · 33 files+575 added−392 removed
This commit

State

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

Diff stats

33 files+575 added−392 removed

  • tests:+82 added−0 removed
  • other:+493 added−392 removed

33 files+575 added−392 removed

modified:docs/tutorial/css.rst+2 added-2 removed
1.. _tutorial-css:23Step 7: Adding Style3Step 9: Adding Style4====================56Now that everything else works, it's time to add some style to the7application. Just create a stylesheet called :file:`style.css` in the8:file:`static` folder we created before:8:file:`static` folder:910.. sourcecode:: css1112 body { font-family: sans-serif; background: #eee; }
19 unmodified lines
modified:docs/tutorial/dbcon.rst+13 added-15 removed
1.. _tutorial-dbcon:23Step 3: Database Connections3Step 4: Database Connections4----------------------------56We have created a function for establishing a database connection with7`connect_db`, but by itself, that's not particularly useful. Creating and8closing database connections all the time is very inefficient, so we want9to keep it around for longer. Because database connections encapsulate a10transaction, we also need to make sure that only one request at the time11uses the connection. How can we elegantly do that with Flask?6You now have a function for establishing a database connection with7`connect_db`, but by itself, it is not particularly useful. Creating and8closing database connections all the time is very inefficient, so you will9need to keep it around for longer. Because database connections10encapsulate a transaction, you will need to make sure that only one11request at a time uses the connection. An elegant way to do this is by12utilizing the *application context*.1313This is where the application context comes into play, so let's start14there.1516Flask provides us with two contexts: the application context and the17request context. For the time being, all you have to know is that there14Flask provides two contexts: the *application context* and the15*request context*. For the time being, all you have to know is that there16are special variables that use these. For instance, the17:data:`~flask.request` variable is the request object associated with18the current request, whereas :data:`~flask.g` is a general purpose21variable associated with the current application context. We will go into22the details of this a bit later.19variable associated with the current application context. The tutorial20will cover some more details of this later on.2122For the time being, all you have to know is that you can store information23safely on the :data:`~flask.g` object.24
9 unmodified lines
34 if not hasattr(g, 'sqlite_db'):35 g.sqlite_db = connect_db()36 return g.sqlite_db3740So now we know how to connect, but how do we properly disconnect? For38Now you know how to connect, but how can you properly disconnect? For39that, Flask provides us with the :meth:`~flask.Flask.teardown_appcontext`40decorator. It's executed every time the application context tears down::4142 @app.teardown_appcontext
33 unmodified lines
modified:docs/tutorial/dbinit.rst+15 added-14 removed
1.. _tutorial-dbinit:23Step 4: Creating The Database3Step 5: Creating The Database4=============================56As outlined earlier, Flaskr is a database powered application, and more7precisely, it is an application powered by a relational database system. Such
7 unmodified lines
15 sqlite3 /tmp/flaskr.db < schema.sql1617The downside of this is that it requires the ``sqlite3`` command to be18installed, which is not necessarily the case on every system. This also19requires that we provide the path to the database, which can introduce19requires that you provide the path to the database, which can introduce20errors. It's a good idea to add a function that initializes the database21for you to the application.21for you, to the application.2223To do this, we can create a function and hook it into the :command:`flask`24command that initializes the database. Let me show you the code first. Just25add this function below the `connect_db` function in :file:`flaskr.py`::23To do this, you can create a function and hook it into a :command:`flask`24command that initializes the database. For now just take a look at the25code segment below. A good place to add this function, and command, is26just below the `connect_db` function in :file:`flaskr.py`::2728 def init_db():29 db = get_db()30 with app.open_resource('schema.sql', mode='r') as f:
7 unmodified lines
38 print 'Initialized the database.'3940The ``app.cli.command()`` decorator registers a new command with the41:command:`flask` script. When the command executes, Flask will automatically41create an application context for us bound to the right application.42Within the function, we can then access :attr:`flask.g` and other things as43we would expect. When the script ends, the application context tears down42create an application context which is bound to the right application.43Within the function, you can then access :attr:`flask.g` and other things as44you might expect. When the script ends, the application context tears down45and the database connection is released.4646We want to keep an actual function around that initializes the database,47You will want to keep an actual function around that initializes the database,48though, so that we can easily create databases in unit tests later on. (For49more information see :ref:`testing`.)5051The :func:`~flask.Flask.open_resource` method of the application object52is a convenient helper function that will open a resource that the53application provides. This function opens a file from the resource53location (your ``flaskr`` folder) and allows you to read from it. We are54using this here to execute a script on the database connection.54location (the :file:`flaskr/flaskr` folder) and allows you to read from it.55It is used in this example to execute a script on the database connection.5656The connection object provided by SQLite can give us a cursor object.57On that cursor, there is a method to execute a complete script. Finally, we57The connection object provided by SQLite can give you a cursor object.58On that cursor, there is a method to execute a complete script. Finally, you59only have to commit the changes. SQLite3 and other transactional60databases will not commit unless you explicitly tell it to.6162Now, it is possible to create a database with the :command:`flask` script::
11 unmodified lines
modified:docs/tutorial/folders.rst+15 added-11 removed
1 unmodified line
23Step 0: Creating The Folders4============================56Before we get started, let's create the folders needed for this6Before getting started, you will need to create the folders needed for this7application::89 /flaskr10 /flaskr10 /static11 /templates11 /static12 /templates1313The ``flaskr`` folder is not a Python package, but just something where we14drop our files. Later on, we will put our database schema as well as main15module into this folder. It is done in the following way. The files inside16the :file:`static` folder are available to users of the application via HTTP.17This is the place where CSS and Javascript files go. Inside the18:file:`templates` folder, Flask will look for `Jinja2`_ templates. The19templates you create later on in the tutorial will go in this directory.14The application will be installed and run as Python package. This is the15recommended way to install and run Flask applications. You will see exactly16how to run ``flaskr`` later on in this tutorial. For now go ahead and create17the applications directory structure. In the next few steps you will be18creating the database schema as well as the main module.1921Continue with :ref:`tutorial-schema`.20As a quick side note, the files inside of the :file:`static` folder are21available to users of the application via HTTP. This is the place where CSS and22Javascript files go. Inside the :file:`templates` folder, Flask will look for23`Jinja2`_ templates. You will see examples of this later on.2425For now you should continue with :ref:`tutorial-schema`.2627.. _Jinja2: http://jinja.pocoo.org/
modified:docs/tutorial/index.rst+1 added
22 unmodified lines
23 introduction24 folders25 schema26 setup27 setuptools28 dbcon29 dbinit30 views31 templates
2 unmodified lines
modified:docs/tutorial/introduction.rst+5 added-4 removed
1 unmodified line
23Introducing Flaskr4==================56We will call our blogging application Flaskr, but feel free to choose your own7less Web-2.0-ish name ;) Essentially, we want it to do the following things:6This tutorial will demonstrate a blogging application named Flaskr, but feel7free to choose your own less Web-2.0-ish name ;) Essentially, it will do the8following things:9101. Let the user sign in and out with credentials specified in the11 configuration. Only one user is supported.122. When the user is logged in, they can add new entries to the page
1 unmodified line
14 is not sanitized because we trust the user here.153. The index page shows all entries so far in reverse chronological order16 (newest on top) and the user can add new ones from there if logged in.1717We will be using SQLite3 directly for this application because it's good18enough for an application of this size. For larger applications, however,18SQLite3 will be used directly for this application because it's good enough19for an application of this size. For larger applications, however,20it makes a lot of sense to use `SQLAlchemy`_, as it handles database21connections in a more intelligent way, allowing you to target different22relational databases at once and more. You might also want to consider23one of the popular NoSQL databases if your data is more suited for those.
11 unmodified lines
modified:docs/tutorial/schema.rst+5 added-5 removed
1 unmodified line
23Step 1: Database Schema4=======================56First, we want to create the database schema. Only a single table is needed7for this application and we only want to support SQLite, so creating the8database schema is quite easy. Just put the following contents into a file9named `schema.sql` in the just created `flaskr` folder:6In this step, you will create the database schema. Only a single table is7needed for this application and it will only support SQLite. All you need to do8is put the following contents into a file named :file:`schema.sql` in the9:file:`flaskr/flaskr` folder:1011.. sourcecode:: sql1213 drop table if exists entries;
2 unmodified lines
16 title text not null,17 'text' text not null18 );1920This schema consists of a single table called ``entries``. Each row in20This schema consists of a single table called ``entries``. Each row in21this table has an ``id``, a ``title``, and a ``text``. The ``id`` is an22automatically incrementing integer and a primary key, the other two are23strings that must not be null.24
1 unmodified line
modified:docs/tutorial/setup.rst+26 added-47 removed
1 unmodified line
23Step 2: Application Setup Code4==============================56Now that we have the schema in place, we can create the application module.7Let's call it ``flaskr.py``. We will place this file inside the ``flaskr``8folder. We will begin by adding the imports we need and by adding the config9section. For small applications, it is possible to drop the configuration10directly into the module, and this is what we will be doing here. However,11a cleaner solution would be to create a separate ``.ini`` or ``.py`` file,12load that, and import the values from there.6Now that the schema is in place, you can create the application module,7:file:`flaskr.py`. This file should be placed inside of the8:file:`flaskr/flaskr` folder. The first several lines of code in the9application module are the needed import statements. After that there will be a10few lines of configuration code. For small applications like ``flaskr``, it is11possible to drop the configuration directly into the module. However, a cleaner12solution is to create a separate ``.ini`` or ``.py`` file, load that, and13import the values from there.1414First, we add the imports in :file:`flaskr.py`::15Here are the import statements (in :file:`flaskr.py`)::1617 # all the imports18 import os19 import sqlite320 from flask import Flask, request, session, g, redirect, url_for, abort, \21 render_template, flash2222Next, we can create our actual application and initialize it with the23config from the same file in :file:`flaskr.py`::23The next couple lines will create the actual application instance and24initialize it with the config from the same file in :file:`flaskr.py`:2525 # create our little application :)26 app = Flask(__name__)27 app.config.from_object(__name__)26.. sourcecode:: python2728 app = Flask(__name__) # create the application instance :)29 app.config.from_object(__name__) # load config from this file , flaskr.py3031 # Load default config and override config from an environment variable32 app.config.update(dict(33 DATABASE=os.path.join(app.root_path, 'flaskr.db'),34 SECRET_KEY='development key',
1 unmodified line
36 PASSWORD='default'37 ))38 app.config.from_envvar('FLASKR_SETTINGS', silent=True)3938The :class:`~flask.Config` object works similarly to a dictionary so we39can update it with new values.40The :class:`~flask.Config` object works similarly to a dictionary, so it can be41updated with new values.4243.. admonition:: Database Path4445 Operating systems know the concept of a current working directory for
10 unmodified lines
56 :ref:`instance-folders` instead.5758Usually, it is a good idea to load a separate, environment-specific59configuration file. Flask allows you to import multiple configurations and it58will use the setting defined in the last import. This enables robust60will use the setting defined in the last import. This enables robust61configuration setups. :meth:`~flask.Config.from_envvar` can help achieve this.6261.. code-block:: python63.. sourcecode:: python6465 app.config.from_envvar('FLASKR_SETTINGS', silent=True)6667Simply define the environment variable :envvar:`FLASKR_SETTINGS` that points to
7 unmodified lines
7576The ``SECRET_KEY`` is needed to keep the client-side sessions secure.77Choose that key wisely and as hard to guess and complex as possible.7877We will also add a method that allows for easy connections to the78specified database. This can be used to open a connection on request and79Lastly, you will add a method that allows for easy connections to the80specified database. This can be used to open a connection on request and81also from the interactive Python shell or a script. This will come in80handy later. We create a simple database connection through SQLite and82handy later. You can create a simple database connection through SQLite and83then tell it to use the :class:`sqlite3.Row` object to represent rows.82This allows us to treat the rows as if they were dictionaries instead of84This allows the rows to be treated as if they were dictionaries instead of85tuples.8685::87.. sourcecode:: python8889 def connect_db():90 """Connects to the specific database."""91 rv = sqlite3.connect(app.config['DATABASE'])92 rv.row_factory = sqlite3.Row93 return rv9493With that out of the way, you should be able to start up the application94without problems. Do this with the following commands::95In the next section you will see how to run the application.9696 export FLASK_APP=flaskr97 export FLASK_DEBUG=198 flask run99100(In case you are on Windows you need to use `set` instead of `export`).101The :envvar:`FLASK_DEBUG` flag enables or disables the interactive debugger.102*Never leave debug mode activated in a production system*, because it will103allow users to execute code on the server!104105You will see a message telling you that server has started along with106the address at which you can access it.107108When you head over to the server in your browser, you will get a 404 error109because we don't have any views yet. We will focus on that a little later,110but first, we should get the database working.111112.. admonition:: Externally Visible Server113114 Want your server to be publicly available? Check out the115 :ref:`externally visible server <public-server>` section for more116 information.117118Continue with :ref:`tutorial-dbcon`.97Continue with :ref:`tutorial-setuptools`.
added:docs/tutorial/setuptools.rst+89 added
1.. _tutorial-setuptools:23Step 3: Installing flaskr with setuptools4=========================================56Flask is now shipped with built-in support for `Click`_. Click provides7Flask with enhanced and extensible command line utilities. Later in this8tutorial you will see exactly how to extend the ``flask`` command line9interface (CLI).1011A useful pattern to manage a Flask application is to install your app12using `setuptools`_. This involves creating a :file:`setup.py`13in the projects root directory. You also need to add an empty14:file:`__init__.py` file to make the :file:`flaskr/flaskr` directory15a package. The code structure at this point should be::1617 /flaskr18 /flaskr19 __init__.py20 /static21 /templates22 setup.py2324The content of the ``setup.py`` file for ``flaskr`` is:2526.. sourcecode:: python2728 from setuptools import setup2930 setup(31 name='flaskr',32 packages=['flaskr'],33 include_package_data=True,34 install_requires=[35 'flask',36 ],37 )3839When using setuptools, it is also necessary to specify any special files40that should be included in your package (in the :file:`MANIFEST.in`).41In this case, the static and templates directories need to be included,42as well as the schema. Create the :file:`MANIFEST.in` and add the43following lines::4445 graft flaskr/templates46 graft flaskr/static47 include flaskr/schema.sql4849At this point you should be able to install the application. As usual, it50is recommended to install your Flask application within a `virtualenv`_.51With that said, go ahead and install the application with::5253 pip install --editable .5455.. note:: The above installation command assumes that it is run within the56 projects root directory, `flaskr/`. Also, the `editable` flag allows57 editing source code without having to reinstall the Flask app each time58 you make changes.5960With that out of the way, you should be able to start up the application.61Do this with the following commands::6263 export FLASK_APP=flaskr.flaskr64 export FLASK_DEBUG=165 flask run6667(In case you are on Windows you need to use `set` instead of `export`).68The :envvar:`FLASK_DEBUG` flag enables or disables the interactive debugger.69*Never leave debug mode activated in a production system*, because it will70allow users to execute code on the server!7172You will see a message telling you that server has started along with73the address at which you can access it.7475When you head over to the server in your browser, you will get a 404 error76because we don't have any views yet. That will be addressed a little later,77but first, you should get the database working.7879.. admonition:: Externally Visible Server8081 Want your server to be publicly available? Check out the82 :ref:`externally visible server <public-server>` section for more83 information.8485Continue with :ref:`tutorial-dbcon`.8687.. _Click: http://click.pocoo.org88.. _setuptools: https://setuptools.readthedocs.io89.. _virtualenv: https://virtualenv.pypa.io
modified:docs/tutorial/templates.rst+8 added-7 removed
1.. _tutorial-templates:23Step 6: The Templates3Step 8: The Templates4=====================56Now we should start working on the templates. If we were to request the URLs7now, we would only get an exception that Flask cannot find the templates. The8templates are using `Jinja2`_ syntax and have autoescaping enabled by6Now it is time to start working on the templates. As you may have7noticed, if you make requests with the app running, you will get8an exception that Flask cannot find the templates. The templates9are using `Jinja2`_ syntax and have autoescaping enabled by10default. This means that unless you mark a value in the code with11:class:`~flask.Markup` or with the ``|safe`` filter in the template,12Jinja2 will ensure that special characters such as ``<`` or ``>`` are13escaped with their XML equivalents.
43 unmodified lines
57-----------------5859This template extends the :file:`layout.html` template from above to display the60messages. Note that the ``for`` loop iterates over the messages we passed60in with the :func:`~flask.render_template` function. We also tell the61form to submit to your `add_entry` function and use ``POST`` as HTTP62method:61in with the :func:`~flask.render_template` function. Notice that the form is62configured to to submit to the `add_entry` view function and use ``POST`` as63HTTP method:6465.. sourcecode:: html+jinja6667 {% extends "layout.html" %}
45 unmodified lines
modified:docs/tutorial/testing.rst+78 added
6 unmodified lines
7expected, it's probably not a bad idea to add automated tests to simplify8modifications in the future. The application above is used as a basic9example of how to perform unit testing in the :ref:`testing` section of the10documentation. Go there to see how easy it is to test Flask applications.1112Adding Tests to flaskr13======================1415Assuming you have seen the testing section above and have either written16your own tests for ``flaskr`` or have followed along with the examples17provided, you might be wondering about ways to organize the project.1819One possible and recommended project structure is::2021 flaskr/22 flaskr/23 __init__.py24 static/25 templates/26 tests/27 context.py28 test_flaskr.py29 setup.py30 MANIFEST.in3132For now go ahead a create the :file:`tests/` directory as well as the33:file:`context.py` and :file:`test_flaskr.py` files, if you haven't34already. The context file is used as an import helper. The contents35of that file are::3637 import sys, os3839 basedir = os.path.dirname(os.path.abspath(__file__))40 sys.path.insert(0, basedir + '/../')4142 from flaskr import flaskr4344Testing + Setuptools45====================4647One way to handle testing is to integrate it with ``setuptools``. All it48requires is adding a couple of lines to the :file:`setup.py` file and49creating a new file :file:`setup.cfg`. Go ahead and update the50:file:`setup.py` to contain::5152 from setuptools import setup5354 setup(55 name='flaskr',56 packages=['flaskr'],57 include_package_data=True,58 install_requires=[59 'flask',60 ],61 )62 setup_requires=[63 'pytest-runner',64 ],65 tests_require=[66 'pytest',67 ],68 )69Now create :file:`setup.cfg` in the project root (alongside70:file:`setup.py`)::7172 [aliases]73 test=pytest7475Now you can run::7677 python setup.py test7879This calls on the alias created in :file:`setup.cfg` which in turn runs80``pytest`` via ``pytest-runner``, as the :file:`setup.py` script has81been called. (Recall the `setup_requires` argument in :file:`setup.py`)82Following the standard rules of test-discovery your tests will be83found, run, and hopefully pass.8485This is one possible way to run and manage testing. Here ``pytest`` is86used, but there are other options such as ``nose``. Integrating testing87with ``setuptools`` is convenient because it is not necessary to actually88download ``pytest`` or any other testing framework one might use.
modified:docs/tutorial/views.rst+19 added-19 removed
1.. _tutorial-views:23Step 5: The View Functions3Step 7: The View Functions4==========================56Now that the database connections are working, we can start writing the7view functions. We will need four of them:6Now that the database connections are working, you can start writing the7view functions. You will need four of them:89Show Entries10------------11
17 unmodified lines
29-------------3031This view lets the user add new entries if they are logged in. This only32responds to ``POST`` requests; the actual form is shown on the33`show_entries` page. If everything worked out well, we will33`show_entries` page. If everything worked out well, it will34:func:`~flask.flash` an information message to the next request and35redirect back to the `show_entries` page::3637 @app.route('/add', methods=['POST'])
6 unmodified lines
44 db.commit()45 flash('New entry was successfully posted')46 return redirect(url_for('show_entries'))4748Note that we check that the user is logged in here (the `logged_in` key is49present in the session and ``True``).48Note that this view checks that the user is logged in (that is, if the49`logged_in` key is present in the session and ``True``).5051.. admonition:: Security Note5253 Be sure to use question marks when building SQL statements, as done in the
26 unmodified lines
80 return redirect(url_for('show_entries'))81 return render_template('login.html', error=error)8283The `logout` function, on the other hand, removes that key from the session84again. We use a neat trick here: if you use the :meth:`~dict.pop` method84again. There is a neat trick here: if you use the :meth:`~dict.pop` method85of the dict and pass a second parameter to it (the default), the method86will delete the key from the dictionary if present or do nothing when that87key is not in there. This is helpful because now we don't have to check88if the user was logged in.87key is not in there. This is helpful because now it is not necessary to88check if the user was logged in.8990::9192 @app.route('/logout')
3 unmodified lines
96 return redirect(url_for('show_entries'))9798.. admonition:: Security Note99100 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.105106 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.110111 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/>`_113114115Continue with :ref:`tutorial-templates`.116117.. _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/
added:examples/flaskr/flaskr/static/style.css+18 added
1body { font-family: sans-serif; background: #eee; }2a, h1, h2 { color: #377BA8; }3h1, h2 { font-family: 'Georgia', serif; margin: 0; }4h1 { border-bottom: 2px solid #eee; }5h2 { font-size: 1.2em; }67.page { margin: 2em auto; width: 35em; border: 5px solid #ccc;8 padding: 0.8em; background: white; }9.entries { list-style: none; margin: 0; padding: 0; }10.entries li { margin: 0.8em 1.2em; }11.entries li h2 { margin-left: -1em; }12.add-entry { font-size: 0.9em; border-bottom: 1px solid #ccc; }13.add-entry dl { font-weight: bold; }14.metanav { text-align: right; font-size: 0.8em; padding: 0.3em;15 margin-bottom: 1em; background: #fafafa; }16.flash { background: #CEE5F5; padding: 0.5em;17 border: 1px solid #AACBE2; }18.error { background: #F0D6D6; padding: 0.5em; }
added:examples/flaskr/flaskr/templates/layout.html+17 added
1<!doctype html>2<title>Flaskr</title>3<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">4<div class="page">5 <h1>Flaskr</h1>6 <div class="metanav">7 {% if not session.logged_in %}8 <a href="{{ url_for('login') }}">log in</a>9 {% else %}10 <a href="{{ url_for('logout') }}">log out</a>11 {% endif %}12 </div>13 {% for message in get_flashed_messages() %}14 <div class="flash">{{ message }}</div>15 {% endfor %}16 {% block body %}{% endblock %}17</div>
added:examples/flaskr/flaskr/templates/login.html+14 added
1{% extends "layout.html" %}2{% block body %}3 <h2>Login</h2>4 {% if error %}<p class="error"><strong>Error:</strong> {{ error }}{% endif %}5 <form action="{{ url_for('login') }}" method="post">6 <dl>7 <dt>Username:8 <dd><input type="text" name="username">9 <dt>Password:10 <dd><input type="password" name="password">11 <dd><input type="submit" value="Login">12 </dl>13 </form>14{% endblock %}
added:examples/flaskr/flaskr/templates/show_entries.html+21 added
1{% extends "layout.html" %}2{% block body %}3 {% if session.logged_in %}4 <form action="{{ url_for('add_entry') }}" method="post" class="add-entry">5 <dl>6 <dt>Title:7 <dd><input type="text" size="30" name="title">8 <dt>Text:9 <dd><textarea name="text" rows="5" cols="40"></textarea>10 <dd><input type="submit" value="Share">11 </dl>12 </form>13 {% endif %}14 <ul class="entries">15 {% for entry in entries %}16 <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}17 {% else %}18 <li><em>Unbelievable. No entries here so far</em>19 {% endfor %}20 </ul>21{% endblock %}
added:examples/flaskr/flaskr/__init__.py
added:examples/flaskr/flaskr/flaskr.py+110 added
1# -*- coding: utf-8 -*-2"""3 Flaskr4 ~~~~~~56 A microblog example application written as Flask tutorial with7 Flask and sqlite3.89 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213import os14from sqlite3 import dbapi2 as sqlite315from flask import Flask, request, session, g, redirect, url_for, abort, \16 render_template, flash171819# create our little application :)20app = Flask(__name__)2122# Load default config and override config from an environment variable23app.config.update(dict(24 DATABASE=os.path.join(app.root_path, 'flaskr.db'),25 DEBUG=True,26 SECRET_KEY='development key',27 USERNAME='admin',28 PASSWORD='default'29))30app.config.from_envvar('FLASKR_SETTINGS', silent=True)313233def connect_db():34 """Connects to the specific database."""35 rv = sqlite3.connect(app.config['DATABASE'])36 rv.row_factory = sqlite3.Row37 return rv383940def init_db():41 """Initializes the database."""42 db = get_db()43 with app.open_resource('schema.sql', mode='r') as f:44 db.cursor().executescript(f.read())45 db.commit()464748@app.cli.command('initdb')49def initdb_command():50 """Creates the database tables."""51 init_db()52 print('Initialized the database.')535455def get_db():56 """Opens a new database connection if there is none yet for the57 current application context.58 """59 if not hasattr(g, 'sqlite_db'):60 g.sqlite_db = connect_db()61 return g.sqlite_db626364@app.teardown_appcontext65def close_db(error):66 """Closes the database again at the end of the request."""67 if hasattr(g, 'sqlite_db'):68 g.sqlite_db.close()697071@app.route('/')72def show_entries():73 db = get_db()74 cur = db.execute('select title, text from entries order by id desc')75 entries = cur.fetchall()76 return render_template('show_entries.html', entries=entries)777879@app.route('/add', methods=['POST'])80def add_entry():81 if not session.get('logged_in'):82 abort(401)83 db = get_db()84 db.execute('insert into entries (title, text) values (?, ?)',85 [request.form['title'], request.form['text']])86 db.commit()87 flash('New entry was successfully posted')88 return redirect(url_for('show_entries'))899091@app.route('/login', methods=['GET', 'POST'])92def login():93 error = None94 if request.method == 'POST':95 if request.form['username'] != app.config['USERNAME']:96 error = 'Invalid username'97 elif request.form['password'] != app.config['PASSWORD']:98 error = 'Invalid password'99 else:100 session['logged_in'] = True101 flash('You were logged in')102 return redirect(url_for('show_entries'))103 return render_template('login.html', error=error)104105106@app.route('/logout')107def logout():108 session.pop('logged_in', None)109 flash('You were logged out')110 return redirect(url_for('show_entries'))
added:examples/flaskr/flaskr/schema.sql+6 added
1drop table if exists entries;2create table entries (3 id integer primary key autoincrement,4 title text not null,5 'text' text not null6);
deleted:examples/flaskr/static/style.css-18 removed
1body { font-family: sans-serif; background: #eee; }2a, h1, h2 { color: #377BA8; }3h1, h2 { font-family: 'Georgia', serif; margin: 0; }4h1 { border-bottom: 2px solid #eee; }5h2 { font-size: 1.2em; }67.page { margin: 2em auto; width: 35em; border: 5px solid #ccc;8 padding: 0.8em; background: white; }9.entries { list-style: none; margin: 0; padding: 0; }10.entries li { margin: 0.8em 1.2em; }11.entries li h2 { margin-left: -1em; }12.add-entry { font-size: 0.9em; border-bottom: 1px solid #ccc; }13.add-entry dl { font-weight: bold; }14.metanav { text-align: right; font-size: 0.8em; padding: 0.3em;15 margin-bottom: 1em; background: #fafafa; }16.flash { background: #CEE5F5; padding: 0.5em;17 border: 1px solid #AACBE2; }18.error { background: #F0D6D6; padding: 0.5em; }
deleted:examples/flaskr/templates/layout.html-17 removed
1<!doctype html>2<title>Flaskr</title>3<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">4<div class="page">5 <h1>Flaskr</h1>6 <div class="metanav">7 {% if not session.logged_in %}8 <a href="{{ url_for('login') }}">log in</a>9 {% else %}10 <a href="{{ url_for('logout') }}">log out</a>11 {% endif %}12 </div>13 {% for message in get_flashed_messages() %}14 <div class="flash">{{ message }}</div>15 {% endfor %}16 {% block body %}{% endblock %}17</div>
deleted:examples/flaskr/templates/login.html-14 removed
1{% extends "layout.html" %}2{% block body %}3 <h2>Login</h2>4 {% if error %}<p class="error"><strong>Error:</strong> {{ error }}{% endif %}5 <form action="{{ url_for('login') }}" method="post">6 <dl>7 <dt>Username:8 <dd><input type="text" name="username">9 <dt>Password:10 <dd><input type="password" name="password">11 <dd><input type="submit" value="Login">12 </dl>13 </form>14{% endblock %}
deleted:examples/flaskr/templates/show_entries.html-21 removed
1{% extends "layout.html" %}2{% block body %}3 {% if session.logged_in %}4 <form action="{{ url_for('add_entry') }}" method="post" class="add-entry">5 <dl>6 <dt>Title:7 <dd><input type="text" size="30" name="title">8 <dt>Text:9 <dd><textarea name="text" rows="5" cols="40"></textarea>10 <dd><input type="submit" value="Share">11 </dl>12 </form>13 {% endif %}14 <ul class="entries">15 {% for entry in entries %}16 <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}17 {% else %}18 <li><em>Unbelievable. No entries here so far</em>19 {% endfor %}20 </ul>21{% endblock %}
added:examples/flaskr/tests/context.py+6 added
1import sys, os23basedir = os.path.dirname(os.path.abspath(__file__))4sys.path.insert(0, basedir + '/../')56from flaskr import flaskr
added:examples/flaskr/tests/test_flaskr.py+76 added
1# -*- coding: utf-8 -*-2"""3 Flaskr Tests4 ~~~~~~~~~~~~56 Tests the Flaskr application.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest13import os14import tempfile1516from context import flaskr1718@pytest.fixture19def client(request):20 db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()21 flaskr.app.config['TESTING'] = True22 client = flaskr.app.test_client()23 with flaskr.app.app_context():24 flaskr.init_db()2526 def teardown():27 os.close(db_fd)28 os.unlink(flaskr.app.config['DATABASE'])29 request.addfinalizer(teardown)3031 return client323334def login(client, username, password):35 return client.post('/login', data=dict(36 username=username,37 password=password38 ), follow_redirects=True)394041def logout(client):42 return client.get('/logout', follow_redirects=True)434445def test_empty_db(client):46 """Start with a blank database."""47 rv = client.get('/')48 assert b'No entries here so far' in rv.data495051def test_login_logout(client):52 """Make sure login and logout works"""53 rv = login(client, flaskr.app.config['USERNAME'],54 flaskr.app.config['PASSWORD'])55 assert b'You were logged in' in rv.data56 rv = logout(client)57 assert b'You were logged out' in rv.data58 rv = login(client, flaskr.app.config['USERNAME'] + 'x',59 flaskr.app.config['PASSWORD'])60 assert b'Invalid username' in rv.data61 rv = login(client, flaskr.app.config['USERNAME'],62 flaskr.app.config['PASSWORD'] + 'x')63 assert b'Invalid password' in rv.data646566def test_messages(client):67 """Test that messages work"""68 login(client, flaskr.app.config['USERNAME'],69 flaskr.app.config['PASSWORD'])70 rv = client.post('/add', data=dict(71 title='<Hello>',72 text='<strong>HTML</strong> allowed here'73 ), follow_redirects=True)74 assert b'No entries here so far' not in rv.data75 assert b'&lt;Hello&gt;' in rv.data76 assert b'<strong>HTML</strong> allowed here' in rv.data
modified:examples/flaskr/.gitignore+1 added
1flaskr.db2.eggs/
deleted:examples/flaskr/flaskr.py-110 removed
1# -*- coding: utf-8 -*-2"""3 Flaskr4 ~~~~~~56 A microblog example application written as Flask tutorial with7 Flask and sqlite3.89 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213import os14from sqlite3 import dbapi2 as sqlite315from flask import Flask, request, session, g, redirect, url_for, abort, \16 render_template, flash171819# create our little application :)20app = Flask(__name__)2122# Load default config and override config from an environment variable23app.config.update(dict(24 DATABASE=os.path.join(app.root_path, 'flaskr.db'),25 DEBUG=True,26 SECRET_KEY='development key',27 USERNAME='admin',28 PASSWORD='default'29))30app.config.from_envvar('FLASKR_SETTINGS', silent=True)313233def connect_db():34 """Connects to the specific database."""35 rv = sqlite3.connect(app.config['DATABASE'])36 rv.row_factory = sqlite3.Row37 return rv383940def init_db():41 """Initializes the database."""42 db = get_db()43 with app.open_resource('schema.sql', mode='r') as f:44 db.cursor().executescript(f.read())45 db.commit()464748@app.cli.command('initdb')49def initdb_command():50 """Creates the database tables."""51 init_db()52 print('Initialized the database.')535455def get_db():56 """Opens a new database connection if there is none yet for the57 current application context.58 """59 if not hasattr(g, 'sqlite_db'):60 g.sqlite_db = connect_db()61 return g.sqlite_db626364@app.teardown_appcontext65def close_db(error):66 """Closes the database again at the end of the request."""67 if hasattr(g, 'sqlite_db'):68 g.sqlite_db.close()697071@app.route('/')72def show_entries():73 db = get_db()74 cur = db.execute('select title, text from entries order by id desc')75 entries = cur.fetchall()76 return render_template('show_entries.html', entries=entries)777879@app.route('/add', methods=['POST'])80def add_entry():81 if not session.get('logged_in'):82 abort(401)83 db = get_db()84 db.execute('insert into entries (title, text) values (?, ?)',85 [request.form['title'], request.form['text']])86 db.commit()87 flash('New entry was successfully posted')88 return redirect(url_for('show_entries'))899091@app.route('/login', methods=['GET', 'POST'])92def login():93 error = None94 if request.method == 'POST':95 if request.form['username'] != app.config['USERNAME']:96 error = 'Invalid username'97 elif request.form['password'] != app.config['PASSWORD']:98 error = 'Invalid password'99 else:100 session['logged_in'] = True101 flash('You were logged in')102 return redirect(url_for('show_entries'))103 return render_template('login.html', error=error)104105106@app.route('/logout')107def logout():108 session.pop('logged_in', None)109 flash('You were logged out')110 return redirect(url_for('show_entries'))
added:examples/flaskr/MANIFEST.in+3 added
1graft flaskr/templates2graft flaskr/static3include flaskr/schema.sql
modified:examples/flaskr/README+9 added-5 removed
11 unmodified lines
12 1. edit the configuration in the flaskr.py file or13 export an FLASKR_SETTINGS environment variable14 pointing to a configuration file.1516 2. Instruct flask to use the right application16 2. install the app from the root of the project directory1718 export FLASK_APP=flaskr18 pip install --editable .1920 3. initialize the database with this command:20 3. Instruct flask to use the right application2122 export FLASK_APP=flaskr.flaskr2324 4. initialize the database with this command:2526 flask initdb2724 4. now you can run flaskr:28 5. now you can run flaskr:2930 flask run3132 the application will greet you on33 http://localhost:5000/3435 ~ Is it tested?3633 You betcha. Run the `test_flaskr.py` file to see37 You betcha. Run `python setup.py test` to see38 the tests pass.
deleted:examples/flaskr/schema.sql-6 removed
1drop table if exists entries;2create table entries (3 id integer primary key autoincrement,4 title text not null,5 'text' text not null6);
added:examples/flaskr/setup.cfg+2 added
1[aliases]2test=pytest
added:examples/flaskr/setup.py+16 added
1from setuptools import setup23setup(4 name='flaskr',5 packages=['flaskr'],6 include_package_data=True,7 install_requires=[8 'flask',9 ],10 setup_requires=[11 'pytest-runner',12 ],13 tests_require=[14 'pytest',15 ],16)
deleted:examples/flaskr/test_flaskr.py-77 removed
1# -*- coding: utf-8 -*-2"""3 Flaskr Tests4 ~~~~~~~~~~~~56 Tests the Flaskr application.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1314import os15import flaskr16import tempfile171819@pytest.fixture20def client(request):21 db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()22 flaskr.app.config['TESTING'] = True23 client = flaskr.app.test_client()24 with flaskr.app.app_context():25 flaskr.init_db()2627 def teardown():28 os.close(db_fd)29 os.unlink(flaskr.app.config['DATABASE'])30 request.addfinalizer(teardown)3132 return client333435def login(client, username, password):36 return client.post('/login', data=dict(37 username=username,38 password=password39 ), follow_redirects=True)404142def logout(client):43 return client.get('/logout', follow_redirects=True)444546def test_empty_db(client):47 """Start with a blank database."""48 rv = client.get('/')49 assert b'No entries here so far' in rv.data505152def test_login_logout(client):53 """Make sure login and logout works"""54 rv = login(client, flaskr.app.config['USERNAME'],55 flaskr.app.config['PASSWORD'])56 assert b'You were logged in' in rv.data57 rv = logout(client)58 assert b'You were logged out' in rv.data59 rv = login(client, flaskr.app.config['USERNAME'] + 'x',60 flaskr.app.config['PASSWORD'])61 assert b'Invalid username' in rv.data62 rv = login(client, flaskr.app.config['USERNAME'],63 flaskr.app.config['PASSWORD'] + 'x')64 assert b'Invalid password' in rv.data656667def test_messages(client):68 """Test that messages work"""69 login(client, flaskr.app.config['USERNAME'],70 flaskr.app.config['PASSWORD'])71 rv = client.post('/add', data=dict(72 title='<Hello>',73 text='<strong>HTML</strong> allowed here'74 ), follow_redirects=True)75 assert b'No entries here so far' not in rv.data76 assert b'&lt;Hello&gt;' in rv.data77 assert b'<strong>HTML</strong> allowed here' in rv.data