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
Provenance
- Commit
633b13e- Tree
0bc28e9- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
f19d3bd- Parent 2
17d4cb3
33 files changed+575 added−392 removed
modified:docs/tutorial/css.rst+2 added-2 removed
1 .. _tutorial-css:2 3-Step 7: Adding Style3+Step 9: 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 now 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+15 added-14 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:7 unmodified lines38 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+ setuptools28 dbcon29 dbinit30 views31 templates2 unmodified linesmodified:docs/tutorial/introduction.rst+5 added-4 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.11 unmodified linesmodified: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-setuptools`.added:docs/tutorial/setuptools.rst+89 added
1+.. _tutorial-setuptools:2+3+Step 3: Installing flaskr with setuptools4+=========================================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+using `setuptools`_. This involves creating a :file:`setup.py`13+in the projects root directory. You also need to add an empty14+:file:`__init__.py` file to make the :file:`flaskr/flaskr` directory15+a package. The code structure at this point should be::16+17+ /flaskr18+ /flaskr19+ __init__.py20+ /static21+ /templates22+ setup.py23+24+The content of the ``setup.py`` file for ``flaskr`` is:25+26+.. sourcecode:: python27+28+ from setuptools import setup29+30+ setup(31+ name='flaskr',32+ packages=['flaskr'],33+ include_package_data=True,34+ install_requires=[35+ 'flask',36+ ],37+ )38+39+When using setuptools, it is also necessary to specify any special files40+that should be included in your package (in the :file:`MANIFEST.in`).41+In this case, the static and templates directories need to be included,42+as well as the schema. Create the :file:`MANIFEST.in` and add the43+following lines::44+45+ graft flaskr/templates46+ graft flaskr/static47+ include flaskr/schema.sql48+49+At this point you should be able to install the application. As usual, it50+is recommended to install your Flask application within a `virtualenv`_.51+With that said, go ahead and install the application with::52+53+ pip install --editable .54+55+.. 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.59+60+With that out of the way, you should be able to start up the application.61+Do this with the following commands::62+63+ export FLASK_APP=flaskr.flaskr64+ export FLASK_DEBUG=165+ flask run66+67+(In case you are on Windows you need to use `set` instead of `export`).68+The :envvar:`FLASK_DEBUG` flag enables or disables the interactive debugger.69+*Never leave debug mode activated in a production system*, because it will70+allow users to execute code on the server!71+72+You will see a message telling you that server has started along with73+the address at which you can access it.74+75+When you head over to the server in your browser, you will get a 404 error76+because we don't have any views yet. That will be addressed a little later,77+but first, you should get the database working.78+79+.. admonition:: Externally Visible Server80+81+ Want your server to be publicly available? Check out the82+ :ref:`externally visible server <public-server>` section for more83+ information.84+85+Continue with :ref:`tutorial-dbcon`.86+87+.. _Click: http://click.pocoo.org88+.. _setuptools: https://setuptools.readthedocs.io89+.. _virtualenv: https://virtualenv.pypa.iomodified:docs/tutorial/templates.rst+8 added-7 removed
1 .. _tutorial-templates:2 3-Step 6: The Templates3+Step 8: 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 to submit to the `add_entry` view function and use ``POST`` as63+HTTP method:64 65 .. sourcecode:: html+jinja66 67 {% extends "layout.html" %}45 unmodified linesmodified:docs/tutorial/testing.rst+78 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 testing section above 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+ context.py28+ test_flaskr.py29+ setup.py30+ MANIFEST.in31+32+For 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't34+already. The context file is used as an import helper. The contents35+of that file are::36+37+ import sys, os38+39+ basedir = os.path.dirname(os.path.abspath(__file__))40+ sys.path.insert(0, basedir + '/../')41+42+ from flaskr import flaskr43+44+Testing + Setuptools45+====================46+47+One way to handle testing is to integrate it with ``setuptools``. All it48+requires is adding a couple of lines to the :file:`setup.py` file and49+creating a new file :file:`setup.cfg`. Go ahead and update the50+:file:`setup.py` to contain::51+52+ from setuptools import setup53+54+ 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+ )69+Now create :file:`setup.cfg` in the project root (alongside70+:file:`setup.py`)::71+72+ [aliases]73+ test=pytest74+75+Now you can run::76+77+ python setup.py test78+79+This calls on the alias created in :file:`setup.cfg` which in turn runs80+``pytest`` via ``pytest-runner``, as the :file:`setup.py` script has81+been called. (Recall the `setup_requires` argument in :file:`setup.py`)82+Following the standard rules of test-discovery your tests will be83+found, run, and hopefully pass.84+85+This is one possible way to run and manage testing. Here ``pytest`` is86+used, but there are other options such as ``nose``. Integrating testing87+with ``setuptools`` is convenient because it is not necessary to actually88+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 7: 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/added: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 }}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+ ~~~~~~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/context.py+6 added
1+import sys, os2+3+basedir = os.path.dirname(os.path.abspath(__file__))4+sys.path.insert(0, basedir + '/../')5+6+from flaskr import flaskradded: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 pytest13+import os14+import tempfile15+16+from context import flaskr17+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+9 added-5 removed
11 unmodified lines12 1. edit the configuration in the flaskr.py file or13 export an FLASKR_SETTINGS environment variable14 pointing to a configuration file.15 16- 2. Instruct flask to use the right application16+ 2. install the app from the root of the project directory17 18- export FLASK_APP=flaskr18+ pip install --editable .19 20- 3. initialize the database with this command:20+ 3. Instruct flask to use the right application21 22+ export FLASK_APP=flaskr.flaskr23+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+[aliases]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.data