rewrite tutorial docs and example
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 · parent 16d83d6 · Browse files · 104 files·+3311 added−2208 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
104 files+3311 added−2208 removed
- tests:+270 added−254 removed
- other:+3041 added−1954 removed
Provenance
- Commit
c3dd7b8- Tree
6ea1c29- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
16d83d6
104 files changed+3311 added−2208 removed
deleted:docs/_static/flaskr.pngbinary
A binary file, deleted.
modified:docs/patterns/jquery.rst+2 added-4 removed
160 unmodified lines161 data arrived, it will call the given function with the return value as162 argument. Note that we can use the `$SCRIPT_ROOT` variable here that163 we set earlier.164 165-If you don't get the whole picture, download the `sourcecode166-for this example167-<https://github.com/pallets/flask/tree/master/examples/jqueryexample>`_168-from GitHub.165+If you don't get the whole picture, download the :gh:`sourcecode166+for this example <examples/jqueryexample>`.modified:docs/patterns/packages.rst+7 added-9 removed
15 unmodified lines16 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`_.20+The :ref:`tutorial <tutorial>` is structured this way, see the21+:gh:`example code <examples/tutorial>`.22 23 Simple Packages24 ---------------25 31 unmodified lines57 'flask',58 ],59 )60 62-In order to run the application you need to export an environment variable 63-that tells Flask where to find the application instance:: 61+In order to run the application you need to export an environment variable62+that tells Flask where to find the application instance::63 64 export FLASK_APP=yourapplication65 67-If you are outside of the project directory make sure to provide the exact 66+If you are outside of the project directory make sure to provide the exact67 path to your application directory. Similarly you can turn on the68 development features like this::69 70 export FLASK_ENV=development71 73-In order to install and run the application you need to issue the following 72+In order to install and run the application you need to issue the following73 commands::74 76- pip install -e . 75+ pip install -e .76 flask run77 78 What did we gain from this? Now we can restructure the application a bit79 into multiple modules. The only thing you have to remember is the52 unmodified lines132 :ref:`becomingbig` section for some inspiration how to deal with that.133 134 135 .. _working-with-modules:137-.. _the full src for this example here: https://github.com/pallets/flask/tree/master/examples/patterns/largerapp136 137 Working with Blueprints138 -----------------------139 4 unmodified linesadded:docs/tutorial/blog.rst+336 added
1+.. currentmodule:: flask2+3+Blog Blueprint4+==============5+6+You'll use the same techniques you learned about when writing the7+authentication blueprint to write the blog blueprint. The blog should8+list all posts, allow logged in users to create posts, and allow the9+author of a post to edit or delete it.10+11+As you implement each view, keep the development server running. As you12+save your changes, try going to the URL in your browser and testing them13+out.14+15+The Blueprint16+-------------17+18+Define the blueprint and register it in the application factory.19+20+.. code-block:: python21+ :caption: ``flaskr/blog.py``22+23+ from flask import (24+ Blueprint, flash, g, redirect, render_template, request, url_for25+ )26+ from werkzeug.exceptions import abort27+28+ from flaskr.auth import login_required29+ from flaskr.db import get_db30+31+ bp = Blueprint('blog', __name__)32+33+Import and register the blueprint from the factory using34+:meth:`app.register_blueprint() <Flask.register_blueprint>`. Place the35+new code at the end of the factory function before returning the app.36+37+.. code-block:: python38+ :caption: ``flaskr/__init__.py``39+40+ def create_app():41+ app = ...42+ # existing code omitted43+44+ from . import blog45+ app.register_blueprint(blog.bp)46+ app.add_url_rule('/', endpoint='index')47+48+ return app49+50+51+Unlike the auth blueprint, the blog blueprint does not have a52+``url_prefix``. So the ``index`` view will be at ``/``, the ``create``53+view at ``/create``, and so on. The blog is the main feature of Flaskr,54+so it makes sense that the blog index will be the main index.55+56+However, the endpoint for the ``index`` view defined below will be57+``blog.index``. Some of the authentication views referred to a plain58+``index`` endpoint. :meth:`app.add_url_rule() <Flask.add_url_rule>`59+associates the endpoint name ``'index'`` with the ``/`` url so that60+``url_for('index')`` or ``url_for('blog.index')`` will both work,61+generating the same ``/`` URL either way.62+63+In another application you might give the blog blueprint a64+``url_prefix`` and define a separate ``index`` view in the application65+factory, similar to the ``hello`` view. Then the ``index`` and66+``blog.index`` endpoints and URLs would be different.67+68+69+Index70+-----71+72+The index will show all of the posts, most recent first. A ``JOIN`` is73+used so that the author information from the ``user`` table is74+available in the result.75+76+.. code-block:: python77+ :caption: ``flaskr/blog.py``78+79+ @bp.route('/')80+ def index():81+ db = get_db()82+ posts = db.execute(83+ 'SELECT p.id, title, body, created, author_id, username'84+ ' FROM post p JOIN user u ON p.author_id = u.id'85+ ' ORDER BY created DESC'86+ ).fetchall()87+ return render_template('blog/index.html', posts=posts)88+89+.. code-block:: html+jinja90+ :caption: ``flaskr/templates/blog/index.html``91+92+ {% extends 'base.html' %}93+94+ {% block header %}95+ <h1>{% block title %}Posts{% endblock %}</h1>96+ {% if g.user %}97+ <a class="action" href="{{ url_for('blog.create') }}">New</a>98+ {% endif %}99+ {% endblock %}100+101+ {% block content %}102+ {% for post in posts %}103+ <article class="post">104+ <header>105+ <div>106+ <h1>{{ post['title'] }}</h1>107+ <div class="about">by {{ post['username'] }} on {{ post['created'].strftime('%Y-%m-%d') }}</div>108+ </div>109+ {% if g.user['id'] == post['author_id'] %}110+ <a class="action" href="{{ url_for('blog.update', id=post['id']) }}">Edit</a>111+ {% endif %}112+ </header>113+ <p class="body">{{ post['body'] }}</p>114+ </article>115+ {% if not loop.last %}116+ <hr>117+ {% endif %}118+ {% endfor %}119+ {% endblock %}120+121+When a user is logged in, the ``header`` block adds a link to the122+``create`` view. When the user is the author of a post, they'll see an123+"Edit" link to the ``update`` view for that post. ``loop.last`` is a124+special variable available inside `Jinja for loops`_. It's used to125+display a line after each post except the last one, to visually separate126+them.127+128+.. _Jinja for loops: http://jinja.pocoo.org/docs/templates/#for129+130+131+Create132+------133+134+The ``create`` view works the same as the auth ``register`` view. Either135+the form is displayed, or the posted data is validated and the post is136+added to the database or an error is shown.137+138+The ``login_required`` decorator you wrote earlier is used on the blog139+views. A user must be logged in to visit these views, otherwise they140+will be redirected to the login page.141+142+.. code-block:: python143+ :caption: ``flaskr/blog.py``144+145+ @bp.route('/create', methods=('GET', 'POST'))146+ @login_required147+ def create():148+ if request.method == 'POST':149+ title = request.form['title']150+ body = request.form['body']151+ error = None152+153+ if not title:154+ error = 'Title is required.'155+156+ if error is not None:157+ flash(error)158+ else:159+ db = get_db()160+ db.execute(161+ 'INSERT INTO post (title, body, author_id)'162+ ' VALUES (?, ?, ?)',163+ (title, body, g.user['id'])164+ )165+ db.commit()166+ return redirect(url_for('blog.index'))167+168+ return render_template('blog/create.html')169+170+.. code-block:: html+jinja171+ :caption: ``flaskr/templates/blog/create.html``172+173+ {% extends 'base.html' %}174+175+ {% block header %}176+ <h1>{% block title %}New Post{% endblock %}</h1>177+ {% endblock %}178+179+ {% block content %}180+ <form method="post">181+ <label for="title">Title</label>182+ <input name="title" id="title" value="{{ request.form['title'] }}" required>183+ <label for="body">Body</label>184+ <textarea name="body" id="body">{{ request.form['body'] }}</textarea>185+ <input type="submit" value="Save">186+ </form>187+ {% endblock %}188+189+190+Update191+------192+193+Both the ``update`` and ``delete`` views will need to fetch a ``post``194+by ``id`` and check if the author matches the logged in user. To avoid195+duplicating code, you can write a function to get the ``post`` and call196+it from each view.197+198+.. code-block:: python199+ :caption: ``flaskr/blog.py``200+201+ def get_post(id, check_author=True):202+ post = get_db().execute(203+ 'SELECT p.id, title, body, created, author_id, username'204+ ' FROM post p JOIN user u ON p.author_id = u.id'205+ ' WHERE p.id = ?',206+ (id,)207+ ).fetchone()208+209+ if post is None:210+ abort(404, "Post id {0} doesn't exist.".format(id))211+212+ if check_author and post['author_id'] != g.user['id']:213+ abort(403)214+215+ return post216+217+:func:`abort` will raise a special exception that returns an HTTP status218+code. It takes an optional message to show with the error, otherwise a219+default message is used. ``404`` means "Not Found", and ``403`` means220+"Forbidden". (``401`` means "Unauthorized", but you redirect to the221+login page instead of returning that status.)222+223+The ``check_author`` argument is defined so that the function can be224+used to get a ``post`` without checking the author. This would be useful225+if you wrote a view to show an individual post on a page, where the user226+doesn't matter because they're not modifying the post.227+228+.. code-block:: python229+ :caption: ``flaskr/blog.py``230+231+ @bp.route('/<int:id>/update', methods=('GET', 'POST'))232+ @login_required233+ def update(id):234+ post = get_post(id)235+236+ if request.method == 'POST':237+ title = request.form['title']238+ body = request.form['body']239+ error = None240+241+ if not title:242+ error = 'Title is required.'243+244+ if error is not None:245+ flash(error)246+ else:247+ db = get_db()248+ db.execute(249+ 'UPDATE post SET title = ?, body = ?'250+ ' WHERE id = ?',251+ (title, body, id)252+ )253+ db.commit()254+ return redirect(url_for('blog.index'))255+256+ return render_template('blog/update.html', post=post)257+258+Unlike the views you've written so far, the ``update`` function takes259+an argument, ``id``. That corresponds to the ``<int:id>`` in the route.260+A real URL will look like ``/1/update``. Flask will capture the ``1``,261+ensure it's an :class:`int`, and pass it as the ``id`` argument. If you262+don't specify ``int:`` and instead do ``<id>``, it will be a string.263+To generate a URL to the update page, :func:`url_for` needs to be passed264+the ``id`` so it knows what to fill in:265+``url_for('blog.update', id=post['id'])``. This is also in the266+``index.html`` file above.267+268+The ``create`` and ``update`` views look very similar. The main269+difference is that the ``update`` view uses a ``post`` object and an270+``UPDATE`` query instead of an ``INSERT``. With some clever refactoring,271+you could use one view and template for both actions, but for the272+tutorial it's clearer to keep them separate.273+274+.. code-block:: html+jinja275+ :caption: ``flaskr/templates/blog/update.html``276+277+ {% extends 'base.html' %}278+279+ {% block header %}280+ <h1>{% block title %}Edit "{{ post['title'] }}"{% endblock %}</h1>281+ {% endblock %}282+283+ {% block content %}284+ <form method="post">285+ <label for="title">Title</label>286+ <input name="title" id="title"287+ value="{{ request.form['title'] or post['title'] }}" required>288+ <label for="body">Body</label>289+ <textarea name="body" id="body">{{ request.form['body'] or post['body'] }}</textarea>290+ <input type="submit" value="Save">291+ </form>292+ <hr>293+ <form action="{{ url_for('blog.delete', id=post['id']) }}" method="post">294+ <input class="danger" type="submit" value="Delete" onclick="return confirm('Are you sure?');">295+ </form>296+ {% endblock %}297+298+This template has two forms. The first posts the edited data to the299+current page (``/<id>/update``). The other form contains only a button300+and specifies an ``action`` attribute that posts to the delete view301+instead. The button uses some JavaScript to show a confirmation dialog302+before submitting.303+304+The pattern ``{{ request.form['title'] or post['title'] }}`` is used to305+choose what data appears in the form. When the form hasn't been306+submitted, the original ``post`` data appears, but if invalid form data307+was posted you want to display that so the user can fix the error, so308+``request.form`` is used instead. :data:`request` is another variable309+that's automatically available in templates.310+311+312+Delete313+------314+315+The delete view doesn't have its own template, the delete button is part316+of ``update.html`` and posts to the ``/<id>/delete`` URL. Since there317+is no template, it will only handle the ``POST`` method then redirect318+to the ``index`` view.319+320+.. code-block:: python321+ :caption: ``flaskr/blog.py``322+323+ @bp.route('/<int:id>/delete', methods=('POST',))324+ @login_required325+ def delete(id):326+ get_post(id)327+ db = get_db()328+ db.execute('DELETE FROM post WHERE id = ?', (id,))329+ db.commit()330+ return redirect(url_for('blog.index'))331+332+Congratulations, you've now finished writing your application! Take some333+time to try out everything in the browser. However, there's still more334+to do before the project is complete.335+336+Continue to :doc:`install`.deleted:docs/tutorial/css.rst-31 removed
1-.. _tutorial-css:2-3-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:9-10-.. sourcecode:: css11-12- body { font-family: sans-serif; background: #eee; }13- a, h1, h2 { color: #377ba8; }14- h1, h2 { font-family: 'Georgia', serif; margin: 0; }15- h1 { border-bottom: 2px solid #eee; }16- h2 { font-size: 1.2em; }17-18- .page { margin: 2em auto; width: 35em; border: 5px solid #ccc;19- padding: 0.8em; background: white; }20- .entries { list-style: none; margin: 0; padding: 0; }21- .entries li { margin: 0.8em 1.2em; }22- .entries li h2 { margin-left: -1em; }23- .add-entry { font-size: 0.9em; border-bottom: 1px solid #ccc; }24- .add-entry dl { font-weight: bold; }25- .metanav { text-align: right; font-size: 0.8em; padding: 0.3em;26- margin-bottom: 1em; background: #fafafa; }27- .flash { background: #cee5F5; padding: 0.5em;28- border: 1px solid #aacbe2; }29- .error { background: #f0d6d6; padding: 0.5em; }30-31-Continue with :ref:`tutorial-testing`.added:docs/tutorial/database.rst+213 added
1+.. currentmodule:: flask2+3+Define and Access the Database4+==============================5+6+The application will use a `SQLite`_ database to store users and posts.7+Python comes with built-in support for SQLite in the :mod:`sqlite3`8+module.9+10+SQLite is convenient because it doesn't require setting up a separate11+database server and is built-in to Python. However, if concurrent12+requests try to write to the database at the same time, they will slow13+down as each write happens sequentially. Small applications won't notice14+this. Once you become big, you may want to switch to a different15+database.16+17+The tutorial doesn't go into detail about SQL. If you are not familiar18+with it, the SQLite docs describe the `language`_.19+20+.. _SQLite: https://sqlite.org/about.html21+.. _language: https://sqlite.org/lang.html22+23+24+Connect to the Database25+-----------------------26+27+The first thing to do when working with a SQLite database (and most28+other Python database libraries) is to create a connection to it. Any29+queries and operations are performed using the connection, which is30+closed after the work is finished.31+32+In web applications this connection is typically tied to the request. It33+is created at some point when handling a request, and closed before the34+response is sent.35+36+.. code-block:: python37+ :caption: ``flaskr/db.py``38+39+ import sqlite340+41+ import click42+ from flask import current_app, g43+ from flask.cli import with_appcontext44+45+46+ def get_db():47+ if 'db' not in g:48+ g.db = sqlite3.connect(49+ current_app.config['DATABASE'],50+ detect_types=sqlite3.PARSE_DECLTYPES51+ )52+ g.db.row_factory = sqlite3.Row53+54+ return g.db55+56+57+ def close_db(e=None):58+ db = g.pop('db', None)59+60+ if db is not None:61+ db.close()62+63+:data:`g` is a special object that is unique for each request. It is64+used to store data that might be accessed by multiple functions during65+the request. The connection is stored and reused instead of creating a66+new connection if ``get_db`` is called a second time in the same67+request.68+69+:data:`current_app` is another special object that points to the Flask70+application handling the request. Since you used an application factory,71+there is no application object when writing the rest of your code.72+``get_db`` will be called when the application has been created and is73+handling a request, so :data:`current_app` can be used.74+75+:func:`sqlite3.connect` establishes a connection to the file pointed at76+by the ``DATABASE`` configuration key. This file doesn't have to exist77+yet, and won't until you initialize the database later.78+79+:class:`sqlite3.Row` tells the connection to return rows that behave80+like dicts. This allows accessing the columns by name.81+82+``close_db`` checks if a connection was created by checking if ``g.db``83+was set. If the connection exists, it is closed. Further down you will84+tell your application about the ``close_db`` function in the application85+factory so that it is called after each request.86+87+88+Create the Tables89+-----------------90+91+In SQLite, data is stored in *tables* and *columns*. These need to be92+created before you can store and retrieve data. Flaskr will store users93+in the ``user`` table, and posts in the ``post`` table. Create a file94+with the SQL commands needed to create empty tables:95+96+.. code-block:: sql97+ :caption: ``flaskr/schema.sql``98+99+ DROP TABLE IF EXISTS user;100+ DROP TABLE IF EXISTS post;101+102+ CREATE TABLE user (103+ id INTEGER PRIMARY KEY AUTOINCREMENT,104+ username TEXT UNIQUE NOT NULL,105+ password TEXT NOT NULL106+ );107+108+ CREATE TABLE post (109+ id INTEGER PRIMARY KEY AUTOINCREMENT,110+ author_id INTEGER NOT NULL,111+ created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,112+ title TEXT NOT NULL,113+ body TEXT NOT NULL,114+ FOREIGN KEY (author_id) REFERENCES user (id)115+ );116+117+Add the Python functions that will run these SQL commands to the118+``db.py`` file:119+120+.. code-block:: python121+ :caption: ``flaskr/db.py``122+123+ def init_db():124+ db = get_db()125+126+ with current_app.open_resource('schema.sql') as f:127+ db.executescript(f.read().decode('utf8'))128+129+130+ @click.command('init-db')131+ @with_appcontext132+ def init_db_command():133+ """Clear the existing data and create new tables."""134+ init_db()135+ click.echo('Initialized the database.')136+137+:meth:`open_resource() <Flask.open_resource>` opens a file relative to138+the ``flaskr`` package, which is useful since you won't necessarily know139+where that location is when deploying the application later. ``get_db``140+returns a database connection, which is used to execute the commands141+read from the file.142+143+:func:`click.command` defines a command line command called ``init-db``144+that calls the ``init_db`` function and shows a success message to the145+user. You can read :ref:`cli` to learn more about writing commands.146+147+148+Register with the Application149+-----------------------------150+151+The ``close_db`` and ``init_db_command`` functions need to be registered152+with the application instance, otherwise they won't be used by the153+application. However, since you're using a factory function, that154+instance isn't available when writing the functions. Instead, write a155+function that takes an application and does the registration.156+157+.. code-block:: python158+ :caption: ``flaskr/db.py``159+160+ def init_app(app):161+ app.teardown_appcontext(close_db)162+ app.cli.add_command(init_db_command)163+164+:meth:`app.teardown_appcontext() <Flask.teardown_appcontext>` tells165+Flask to call that function when cleaning up after returning the166+response.167+168+:meth:`app.cli.add_command() <click.Group.add_command>` adds a new169+command that can be called with the ``flask`` command.170+171+Import and call this function from the factory. Place the new code at172+the end of the factory function before returning the app.173+174+.. code-block:: python175+ :caption: ``flaskr/__init__.py``176+177+ def create_app():178+ app = ...179+ # existing code omitted180+181+ from . import db182+ db.init_app(app)183+184+ return app185+186+187+Initialize the Database File188+----------------------------189+190+Now that ``init-db`` has been registered with the app, it can be called191+using the ``flask`` command, similar to the ``run`` command from the192+previous page.193+194+.. note::195+196+ If you're still running the server from the previous page, you can197+ either stop the server, or run this command in a new terminal. If198+ you use a new terminal, remember to change to your project directory199+ and activate the env as described in :ref:`install-activate-env`.200+ You'll also need to set ``FLASK_APP`` and ``FLASK_ENV`` as shown on201+ the previous page.202+203+Run the ``init-db`` command:204+205+.. code-block:: none206+207+ flask init-db208+ Initialized the database.209+210+There will now be a ``flaskr.sqlite`` file in the ``instance`` folder in211+your project.212+213+Continue to :doc:`views`.deleted:docs/tutorial/dbcon.rst-78 removed
1-.. _tutorial-dbcon:2-3-Step 4: Database Connections4-----------------------------5-6-Let's continue building our code in the ``flaskr.py`` file.7-(Scroll to the end of the page for more about project layout.)8-9-You currently have a function for establishing a database connection with10-`connect_db`, but by itself, it is not particularly useful. Creating and11-closing database connections all the time is very inefficient, so you will12-need to keep it around for longer. Because database connections13-encapsulate a transaction, you will need to make sure that only one14-request at a time uses the connection. An elegant way to do this is by15-utilizing the *application context*.16-17-Flask provides two contexts: the *application context* and the18-*request context*. For the time being, all you have to know is that there19-are special variables that use these. For instance, the20-:data:`~flask.request` variable is the request object associated with21-the current request, whereas :data:`~flask.g` is a general purpose22-variable associated with the current application context. The tutorial23-will cover some more details of this later on.24-25-For the time being, all you have to know is that you can store information26-safely on the :data:`~flask.g` object.27-28-So when do you put it on there? To do that you can make a helper29-function. The first time the function is called, it will create a database30-connection for the current context, and successive calls will return the31-already established connection::32-33- def get_db():34- """Opens a new database connection if there is none yet for the35- current application context.36- """37- if not hasattr(g, 'sqlite_db'):38- g.sqlite_db = connect_db()39- return g.sqlite_db40-41-Now you know how to connect, but how can you properly disconnect? For42-that, Flask provides us with the :meth:`~flask.Flask.teardown_appcontext`43-decorator. It's executed every time the application context tears down::44-45- @app.teardown_appcontext46- def close_db(error):47- """Closes the database again at the end of the request."""48- if hasattr(g, 'sqlite_db'):49- g.sqlite_db.close()50-51-Functions marked with :meth:`~flask.Flask.teardown_appcontext` are called52-every time the app context tears down. What does this mean?53-Essentially, the app context is created before the request comes in and is54-destroyed (torn down) whenever the request finishes. A teardown can55-happen because of two reasons: either everything went well (the error56-parameter will be ``None``) or an exception happened, in which case the error57-is passed to the teardown function.58-59-Curious about what these contexts mean? Have a look at the60-:ref:`app-context` documentation to learn more.61-62-Continue to :ref:`tutorial-dbinit`.63-64-.. hint:: Where do I put this code?65-66- If you've been following along in this tutorial, you might be wondering67- where to put the code from this step and the next. A logical place is to68- group these module-level functions together, and put your new69- ``get_db`` and ``close_db`` functions below your existing70- ``connect_db`` function (following the tutorial line-by-line).71-72- If you need a moment to find your bearings, take a look at how the `example73- source`_ is organized. In Flask, you can put all of your application code74- into a single Python module. You don't have to, and if your app :ref:`grows75- larger <larger-applications>`, it's a good idea not to.76-77-.. _example source:78- https://github.com/pallets/flask/tree/master/examples/flaskr/deleted:docs/tutorial/dbinit.rst-80 removed
1-.. _tutorial-dbinit:2-3-Step 5: Creating The Database4-=============================5-6-As outlined earlier, Flaskr is a database powered application, and more7-precisely, it is an application powered by a relational database system. Such8-systems need a schema that tells them how to store that information.9-Before starting the server for the first time, it's important to create10-that schema.11-12-Such a schema could be created by piping the ``schema.sql`` file into the13-``sqlite3`` command as follows::14-15- sqlite3 /tmp/flaskr.db < schema.sql16-17-However, the downside of this is that it requires the ``sqlite3`` command18-to be installed, which is not necessarily the case on every system. This19-also requires that you provide the path to the database, which can introduce20-errors.21-22-Instead of the ``sqlite3`` command above, it's a good idea to add a function23-to our application that initializes the database for you. To do this, you24-can create a function and hook it into a :command:`flask` command that25-initializes the database.26-27-Take a look at the code segment below. A good place to add this function,28-and command, is just below the ``connect_db`` function in :file:`flaskr.py`::29-30- def init_db():31- db = get_db()32-33- with app.open_resource('schema.sql', mode='r') as f:34- db.cursor().executescript(f.read())35-36- db.commit()37-38-39- @app.cli.command('initdb')40- def initdb_command():41- """Initializes the database."""42-43- init_db()44- print('Initialized the database.')45-46-The ``app.cli.command()`` decorator registers a new command with the47-:command:`flask` script. When the command executes, Flask will automatically48-create an application context which is bound to the right application.49-Within the function, you can then access :attr:`flask.g` and other things as50-you might expect. When the script ends, the application context tears down51-and the database connection is released.52-53-You will want to keep an actual function around that initializes the database,54-though, so that we can easily create databases in unit tests later on. (For55-more information see :ref:`testing`.)56-57-The :func:`~flask.Flask.open_resource` method of the application object58-is a convenient helper function that will open a resource that the59-application provides. This function opens a file from the resource60-location (the :file:`flaskr/flaskr` folder) and allows you to read from it.61-It is used in this example to execute a script on the database connection.62-63-The connection object provided by SQLite can give you a cursor object.64-On that cursor, there is a method to execute a complete script. Finally, you65-only have to commit the changes. SQLite3 and other transactional66-databases will not commit unless you explicitly tell it to.67-68-Now, in a terminal, from the application root directory :file:`flaskr/` it is69-possible to create a database with the :command:`flask` script::70-71- flask initdb72- Initialized the database.73-74-.. admonition:: Troubleshooting75-76- If you get an exception later on stating that a table cannot be found, check77- that you did execute the ``initdb`` command and that your table names are78- correct (singular vs. plural, for example).79-80-Continue with :ref:`tutorial-views`added:docs/tutorial/deploy.rst+121 added
1+Deploy to Production2+====================3+4+This part of the tutorial assumes you have a server that you want to5+deploy your application to. It gives an overview of how to create the6+distribution file and install it, but won't go into specifics about7+what server or software to use. You can set up a new environment on your8+development computer to try out the instructions below, but probably9+shouldn't use it for hosting a real public application. See10+:doc:`/deploying/index` for a list of many different ways to host your11+application.12+13+14+Build and Install15+-----------------16+17+When you want to deploy your application elsewhere, you build a18+distribution file. The current standard for Python distribution is the19+*wheel* format, with the ``.whl`` extension. Make sure the wheel library20+is installed first:21+22+.. code-block:: none23+24+ pip install wheel25+26+Running ``setup.py`` with Python gives you a command line tool to issue27+build-related commands. The ``bdist_wheel`` command will build a wheel28+distribution file.29+30+.. code-block:: none31+32+ python setup.py bdist_wheel33+34+You can find the file in ``dist/flaskr-1.0.0-py3-none-any.whl``. The35+file name is the name of the project, the version, and some tags about36+the file can install.37+38+Copy this file to another machine,39+:ref:`set up a new virtualenv <install-create-env>`, then install the40+file with ``pip``.41+42+.. code-block:: none43+44+ pip install flaskr-1.0.0-py3-none-any.whl45+46+Pip will install your project along with its dependencies.47+48+Since this is a different machine, you need to run ``init-db`` again to49+create the database in the instance folder.50+51+.. code-block:: none52+53+ export FLASK_APP=flaskr54+ flask init-db55+56+When Flask detects that it's installed (not in editable mode), it uses57+a different directory for the instance folder. You can find it at58+``venv/var/flaskr-instance`` instead.59+60+61+Configure the Secret Key62+------------------------63+64+In the beginning of the tutorial that you gave a default value for65+:data:`SECRET_KEY`. This should be changed to some random bytes in66+production. Otherwise, attackers could use the public ``'dev'`` key to67+modify the session cookie, or anything else that uses the secret key.68+69+You can use the following command to output a random secret key:70+71+.. code-block:: none72+73+ python -c 'import os; print(os.urandom(16))'74+75+ b'_5#y2L"F4Q8z\n\xec]/'76+77+Create the ``config.py`` file in the instance folder, which the factory78+will read from if it exists. Copy the generated value into it.79+80+.. code-block:: python81+ :caption: ``venv/var/flaskr-instance/config.py``82+83+ SECRET_KEY = b'_5#y2L"F4Q8z\n\xec]/'84+85+You can also set any other necessary configuration here, although86+``SECRET_KEY`` is the only one needed for Flaskr.87+88+89+Run with a Production Server90+----------------------------91+92+When running publicly rather than in development, you should not use the93+built-in development server (``flask run``). The development server is94+provided by Werkzeug for convenience, but is not designed to be95+particularly efficient, stable, or secure.96+97+Instead, use a production WSGI server. For example, to use `Waitress`_,98+first install it in the virtual environment:99+100+.. code-block:: none101+102+ pip install waitress103+104+You need to tell Waitress about your application, but it doesn't use105+``FLASK_APP`` like ``flask run`` does. You need to tell it to import and106+call the application factory to get an application object.107+108+.. code-block:: none109+110+ waitress-serve --call 'flaskr:create_app'111+112+ Serving on http://0.0.0.0:8080113+114+See :doc:`/deploying/index` for a list of many different ways to host115+your application. Waitress is just an example, chosen for the tutorial116+because it supports both Windows and Linux. There are many more WSGI117+servers and deployment options that you may choose for your project.118+119+.. _Waitress: https://docs.pylonsproject.org/projects/waitress/120+121+Continue to :doc:`next`.added:docs/tutorial/factory.rst+177 added
1+.. currentmodule:: flask2+3+Application Setup4+=================5+6+A Flask application is an instance of the :class:`Flask` class.7+Everything about the application, such as configuration and URLs, will8+be registered with this class.9+10+The most straightforward way to create a Flask application is to create11+a global :class:`Flask` instance directly at the top of your code, like12+how the "Hello, World!" example did on the previous page. While this is13+simple and useful in some cases, it can cause some tricky issues as the14+project grows.15+16+Instead of creating a :class:`Flask` instance globally, you will create17+it inside a function. This function is known as the *application18+factory*. Any configuration, registration, and other setup the19+application needs will happen inside the function, then the application20+will be returned.21+22+23+The Application Factory24+-----------------------25+26+It's time to start coding! Create the ``flaskr`` directory and add the27+``__init__.py`` file. The ``__init__.py`` serves double duty: it will28+contain the application factory, and it tells Python that the ``flaskr``29+directory should be treated as a package.30+31+.. code-block:: none32+33+ mkdir flaskr34+35+.. code-block:: python36+ :caption: ``flaskr/__init__.py``37+38+ import os39+40+ from flask import Flask41+42+43+ def create_app(test_config=None):44+ # create and configure the app45+ app = Flask(__name__, instance_relative_config=True)46+ app.config.from_mapping(47+ SECRET_KEY='dev',48+ DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),49+ )50+51+ if test_config is None:52+ # load the instance config, if it exists, when not testing53+ app.config.from_pyfile('config.py', silent=True)54+ else:55+ # load the test config if passed in56+ app.config.from_mapping(test_config)57+58+ # ensure the instance folder exists59+ try:60+ os.makedirs(app.instance_path)61+ except OSError:62+ pass63+64+ # a simple page that says hello65+ @app.route('/hello')66+ def hello():67+ return 'Hello, World!'68+69+ return app70+71+``create_app`` is the application factory function. You'll add to it72+later in the tutorial, but it already does a lot.73+74+#. ``app = Flask(__name__, instance_relative_config=True)`` creates the75+ :class:`Flask` instance.76+77+ * ``__name__`` is the name of the current Python module. The app78+ needs to know where it's located to set up some paths, and79+ ``__name__`` is a convenient way to tell it that.80+81+ * ``instance_relative_config=True`` tells the app that82+ configuration files are relative to the83+ :ref:`instance folder <instance-folders>`. The instance folder84+ is located outside the ``flaskr`` package and can hold local85+ data that shouldn't be committed to version control, such as86+ configuration secrets and the database file.87+88+#. :meth:`app.config.from_mapping() <Config.from_mapping>` sets89+ some default configuration that the app will use:90+91+ * :data:`SECRET_KEY` is used by Flask and extensions to keep data92+ safe. It's set to ``'dev'`` to provide a convenient value93+ during development, but it should be overridden with a random94+ value when deploying.95+96+ * ``DATABASE`` is the path where the SQLite database file will be97+ saved. It's under98+ :attr:`app.instance_path <Flask.instance_path>`, which is the99+ path that Flask has chosen for the instance folder. You'll learn100+ more about the database in the next section.101+102+#. :meth:`app.config.from_pyfile() <Config.from_pyfile>` overrides103+ the default configuration with values taken from the ``config.py``104+ file in the instance folder if it exists. For example, when105+ deploying, this can be used to set a real ``SECRET_KEY``.106+107+ * ``test_config`` can also be passed to the factory, and will be108+ used instead of the instance configuration. This is so the tests109+ you'll write later in the tutorial can be configured110+ independently of any development values you have configured.111+112+#. :func:`os.makedirs` ensures that113+ :attr:`app.instance_path <Flask.instance_path>` exists. Flask114+ doesn't create the instance folder automatically, but it needs to be115+ created because your project will create the SQLite database file116+ there.117+118+#. :meth:`@app.route() <Flask.route>` creates a simple route so you can119+ see the application working before getting into the rest of the120+ tutorial. It creates a connection between the URL ``/hello`` and a121+ function that returns a response, the string ``'Hello, World!'`` in122+ this case.123+124+125+Run The Application126+-------------------127+128+Now you can run your application using the ``flask`` command. From the129+terminal, tell Flask where to find your application, then run it in130+development mode.131+132+Development mode shows an interactive debugger whenever a page raises an133+exception, and restarts the server whenever you make changes to the134+code. You can leave it running and just reload the browser page as you135+follow the tutorial.136+137+For Linux and Mac:138+139+.. code-block:: none140+141+ export FLASK_APP=flaskr142+ export FLASK_ENV=development143+ flask run144+145+For Windows cmd, use ``set`` instead of ``export``:146+147+.. code-block:: none148+149+ set FLASK_APP=flaskr150+ set FLASK_ENV=development151+ flask run152+153+For Windows PowerShell, use ``$env:`` instead of ``export``:154+155+.. code-block:: none156+157+ $env:FLASK_APP = "flaskr"158+ $env:FLASK_ENV = "development"159+ flask run160+161+You'll see output similar to this:162+163+.. code-block:: none164+165+ * Serving Flask app "flaskr"166+ * Environment: development167+ * Debug mode: on168+ * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)169+ * Restarting with stat170+ * Debugger is active!171+ * Debugger PIN: 855-212-761172+173+Visit http://127.0.0.1:5000/hello in a browser and you should see the174+"Hello, World!" message. Congratulations, you're now running your Flask175+web application!176+177+Continue to :doc:`database`.added:docs/tutorial/flaskr_edit.pngbinary
A binary file, added.
added:docs/tutorial/flaskr_index.pngbinary
A binary file, added.
added:docs/tutorial/flaskr_login.pngbinary
A binary file, added.
deleted:docs/tutorial/folders.rst-31 removed
1-.. _tutorial-folders:2-3-Step 0: Creating The Folders4-============================5-6-It is recommended to install your Flask application within a virtualenv. Please7-read the :ref:`installation` section to set up your environment.8-9-Now that you have installed Flask, you will need to create the folders required10-for this tutorial. Your directory structure will look like this::11-12- /flaskr13- /flaskr14- /static15- /templates16-17-The application will be installed and run as Python package. This is the18-recommended way to install and run Flask applications. You will see exactly19-how to run ``flaskr`` later on in this tutorial.20-21-For now go ahead and create the applications directory structure. In the next22-few steps you will be creating the database schema as well as the main module.23-24-As a quick side note, the files inside of the :file:`static` folder are25-available to users of the application via HTTP. This is the place where CSS and26-JavaScript files go. Inside the :file:`templates` folder, Flask will look for27-`Jinja2`_ templates. You will see examples of this later on.28-29-For now you should continue with :ref:`tutorial-schema`.30-31-.. _Jinja2: http://jinja.pocoo.org/modified:docs/tutorial/index.rst+55 added-22 removed
1 unmodified line2 3 Tutorial4 ========5 6-Learn by example to develop an application with Python and Flask.6+.. toctree::7+ :caption: Contents:8+ :maxdepth: 19 8-In this tutorial, we will create a simple blogging application. It only9-supports one user, only allows text entries, and has no feeds or comments.10+ layout11+ factory12+ database13+ views14+ templates15+ static16+ blog17+ install18+ tests19+ deploy20+ next21 11-While very simple, this example still features everything you need to get12-started. In addition to Flask, we will use SQLite for the database, which is13-built-in to Python, so there is nothing else you need.22+This tutorial will walk you through creating a basic blog application23+called Flaskr. Users will be able to register, log in, create posts,24+and edit or delete their own posts. You will be able to package and25+install the application on other computers.26 15-If you want the full source code in advance or for comparison, check out16-the `example source`_.27+.. image:: flaskr_index.png28+ :align: center29+ :class: screenshot30+ :alt: screenshot of index page31 18-.. _example source: https://github.com/pallets/flask/tree/master/examples/flaskr/32+It's assumed that you're already familiar with Python. The `official33+tutorial`_ in the Python docs is a great way to learn or review first.34 20-.. toctree::21- :maxdepth: 235+.. _official tutorial: https://docs.python.org/3/tutorial/36 23- introduction24- folders25- schema26- setup27- packaging28- dbcon29- dbinit30- views31- templates32- css33- testing37+While it's designed to give a good starting point, the tutorial doesn't38+cover all of Flask's features. Check out the :ref:`quickstart` for an39+overview of what Flask can do, then dive into the docs to find out more.40+The tutorial only uses what's provided by Flask and Python. In another41+project, you might decide to use :ref:`extensions` or other libraries to42+make some tasks simpler.43+44+.. image:: flaskr_login.png45+ :align: center46+ :class: screenshot47+ :alt: screenshot of login page48+49+Flask is flexible. It doesn't require you to use any particular project50+or code layout. However, when first starting, it's helpful to use a more51+structured approach. This means that the tutorial will require a bit of52+boilerplate up front, but it's done to avoid many common pitfalls that53+new developers encounter, and it creates a project that's easy to expand54+on. Once you become more comfortable with Flask, you can step out of55+this structure and take full advantage of Flask's flexibility.56+57+.. image:: flaskr_edit.png58+ :align: center59+ :class: screenshot60+ :alt: screenshot of login page61+62+:gh:`The tutorial project is available as an example in the Flask63+repository <examples/tutorial>`, if you want to compare your project64+with the final product as you follow the tutorial.65+66+Continue to :doc:`layout`.added:docs/tutorial/install.rst+113 added
1+Make the Project Installable2+============================3+4+Making your project installable means that you can build a5+*distribution* file and install that in another environment, just like6+you installed Flask in your project's environment. This makes deploying7+your project the same as installing any other library, so you're using8+all the standard Python tools to manage everything.9+10+Installing also comes with other benefits that might not be obvious from11+the tutorial or as a new Python user, including:12+13+* Currently, Python and Flask understand how to use the ``flaskr``14+ package only because you're running from your project's directory.15+ Installing means you can import it no matter where you run from.16+17+* You can manage your project's dependencies just like other packages18+ do, so ``pip install yourproject.whl`` installs them.19+20+* Test tools can isolate your test environment from your development21+ environment.22+23+.. note::24+ This is being introduced late in the tutorial, but in your future25+ projects you should always start with this.26+27+28+Describe the Project29+--------------------30+31+The ``setup.py`` file describes your project and the files that belong32+to it.33+34+.. code-block:: python35+ :caption: ``setup.py``36+37+ from setuptools import find_packages, setup38+39+ setup(40+ name='flaskr',41+ version='1.0.0',42+ packages=find_packages(),43+ include_package_data=True,44+ zip_safe=False,45+ install_requires=[46+ 'flask',47+ ],48+ )49+50+51+``packages`` tells Python what package directories (and the Python files52+they contain) to include. ``find_packages()`` finds these directories53+automatically so you don't have to type them out. To include other54+files, such as the static and templates directories,55+``include_package_data`` is set. Python needs another file named56+``MANIFEST.in`` to tell what this other data is.57+58+.. code-block:: none59+ :caption: ``MANIFEST.in``60+61+ include flaskr/schema.sql62+ graft flaskr/static63+ graft flaskr/templates64+ global-exclude *.pyc65+66+This tells Python to copy everything in the ``static`` and ``templates``67+directories, and the ``schema.sql`` file, but to exclude all bytecode68+files.69+70+See the `official packaging guide`_ for another explanation of the files71+and options used.72+73+.. _official packaging guide: https://packaging.python.org/tutorials/distributing-packages/74+75+76+Install the Project77+-------------------78+79+Use ``pip`` to install your project in the virtual environment.80+81+.. code-block:: none82+83+ pip install -e .84+85+This tells pip to find ``setup.py`` in the current directory and install86+it in *editable* or *development* mode. Editable mode means that as you87+make changes to your local code, you'll only need to re-install if you88+change the metadata about the project, such as its dependencies.89+90+You can observe that the project is now installed with ``pip list``.91+92+.. code-block:: none93+94+ pip list95+96+ Package Version Location97+ -------------- --------- ----------------------------------98+ click 6.799+ Flask 1.0100+ flaskr 1.0.0 /home/user/Projects/flask-tutorial101+ itsdangerous 0.24102+ Jinja2 2.10103+ MarkupSafe 1.0104+ pip 9.0.3105+ setuptools 39.0.1106+ Werkzeug 0.14.1107+ wheel 0.30.0108+109+Nothing changes from how you've been running your project so far.110+``FLASK_APP`` is still set to ``flaskr`` and ``flask run`` still runs111+the application.112+113+Continue to :doc:`tests`.deleted:docs/tutorial/introduction.rst-39 removed
1-.. _tutorial-introduction:2-3-Introducing Flaskr4-==================5-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 page13- consisting of a text-only title and some HTML for the text. This HTML14- 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-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.24-25-.. warning::26- If you're following the tutorial from a specific version of the docs, be27- sure to check out the same tag in the repository, otherwise the tutorial28- may be different than the example.29-30-Here is a screenshot of the final application:31-32-.. image:: ../_static/flaskr.png33- :align: center34- :class: screenshot35- :alt: screenshot of the final application36-37-Continue with :ref:`tutorial-folders`.38-39-.. _SQLAlchemy: https://www.sqlalchemy.org/added:docs/tutorial/layout.rst+110 added
1+Project Layout2+==============3+4+Create a project directory and enter it:5+6+.. code-block:: none7+8+ mkdir flask-tutorial9+ cd flask-tutorial10+11+Then follow the :doc:`installation instructions </installation>` to set12+up a Python virtual environment and install Flask for your project.13+14+The tutorial will assume you're working from the ``flask-tutorial``15+directory from now on. The file names at the top of each code block are16+relative to this directory.17+18+----19+20+A Flask application can be as simple as a single file.21+22+.. code-block:: python23+ :caption: ``hello.py``24+25+ from flask import Flask26+27+ app = Flask(__name__)28+29+30+ @app.route('/')31+ def hello():32+ return 'Hello, World!'33+34+However, as a project get bigger, it becomes overwhelming to keep all35+the code in one file. Python projects use *packages* to organize code36+into multiple modules that can be imported where needed, and the37+tutorial will do this as well.38+39+The project directory will contain:40+41+* ``flaskr/``, a Python package containing your application code and42+ files.43+* ``tests/``, a directory containing test modules.44+* ``venv/``, a Python virtual environment where Flask and other45+ dependencies are installed.46+* Installation files telling Python how to install your project.47+* Version control config, such as `git`_. You should make a habit of48+ using some type of version control for all your projects, no matter49+ the size.50+* Any other project files you might add in the future.51+52+.. _git: https://git-scm.com/53+54+By the end, your project layout will look like this:55+56+.. code-block:: none57+58+ /home/user/Projects/flask-tutorial59+ ├── flaskr/60+ │ ├── __init__.py61+ │ ├── db.py62+ │ ├── schema.sql63+ │ ├── auth.py64+ │ ├── blog.py65+ │ ├── templates/66+ │ │ ├── base.html67+ │ │ ├── auth/68+ │ │ │ ├── login.html69+ │ │ │ └── register.html70+ │ │ └── blog/71+ │ │ ├── create.html72+ │ │ ├── index.html73+ │ │ └── update.html74+ │ └── static/75+ │ └── style.css76+ ├── tests/77+ │ ├── conftest.py78+ │ ├── data.sql79+ │ ├── test_factory.py80+ │ ├── test_db.py81+ │ ├── test_auth.py82+ │ └── test_blog.py83+ ├── venv/84+ ├── setup.py85+ └── MANIFEST.in86+87+If you're using version control, the following files that are generated88+while running your project should be ignored. There may be other files89+based on the editor you use. In general, ignore files that you didn't90+write. For example, with git:91+92+.. code-block:: none93+ :caption: ``.gitignore``94+95+ venv/96+97+ *.pyc98+ __pycache__/99+100+ instance/101+102+ .pytest_cache/103+ .coverage104+ htmlcov/105+106+ dist/107+ build/108+ *.egg-info/109+110+Continue to :doc:`factory`.added:docs/tutorial/next.rst+38 added
1+Keep Developing!2+================3+4+You've learned about quite a few Flask and Python concepts throughout5+the tutorial. Go back and review the tutorial and compare your code with6+the steps you took to get there. Compare your project to the7+:gh:`example project <examples/tutorial>`, which might look a bit8+different due to the step-by-step nature of the tutorial.9+10+There's a lot more to Flask than what you've seen so far. Even so,11+you're now equipped to start developing your own web applications. Check12+out the :ref:`quickstart` for an overview of what Flask can do, then13+dive into the docs to keep learning. Flask uses `Jinja`_, `Click`_,14+`Werkzeug`_, and `ItsDangerous`_ behind the scenes, and they all have15+their own documentation too. You'll also be interested in16+:ref:`extensions` which make tasks like working with the database or17+validating form data easier and more powerful.18+19+If you want to keep developing your Flaskr project, here are some ideas20+for what to try next:21+22+* A detail view to show a single post. Click a post's title to go to23+ its page.24+* Like / unlike a post.25+* Comments.26+* Tags. Clicking a tag shows all the posts with that tag.27+* A search box that filters the index page by name.28+* Paged display. Only show 5 posts per page.29+* Upload an image to go along with a post.30+* Format posts using Markdown.31+* An RSS feed of new posts.32+33+Have fun and make awesome applications!34+35+.. _Jinja: https://palletsprojects.com/p/jinja/36+.. _Click: https://palletsprojects.com/p/click/37+.. _Werkzeug: https://palletsprojects.com/p/werkzeug/38+.. _ItsDangerous: https://palletsprojects.com/p/itsdangerous/deleted:docs/tutorial/packaging.rst-108 removed
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 involves13-creating two new files; :file:`setup.py` and :file:`MANIFEST.in` in the14-projects root directory. You also need to add an :file:`__init__.py`15-file to make the :file:`flaskr/flaskr` directory a package. After these16-changes, your code structure should be::17-18- /flaskr19- /flaskr20- __init__.py21- /static22- /templates23- flaskr.py24- schema.sql25- setup.py26- MANIFEST.in27-28-Create the ``setup.py`` file for ``flaskr`` with the following content::29-30- from setuptools import setup31-32- setup(33- name='flaskr',34- packages=['flaskr'],35- include_package_data=True,36- install_requires=[37- 'flask',38- ],39- )40-41-When using setuptools, it is also necessary to specify any special files42-that should be included in your package (in the :file:`MANIFEST.in`).43-In this case, the static and templates directories need to be included,44-as well as the schema.45-46-Create the :file:`MANIFEST.in` and add the following lines::47-48- graft flaskr/templates49- graft flaskr/static50- include flaskr/schema.sql51-52-Next, to simplify locating the application, create the file,53-:file:`flaskr/__init__.py` containing only the following import statement::54-55- from .flaskr import app56-57-This import statement brings the application instance into the top-level58-of the application package. When it is time to run the application, the59-Flask development server needs the location of the app instance. This60-import statement simplifies the location process. Without the above61-import statement, the export statement a few steps below would need to be62-``export FLASK_APP=flaskr.flaskr``.63-64-At this point you should be able to install the application. As usual, it65-is recommended to install your Flask application within a `virtualenv`_.66-With that said, from the ``flaskr/`` directory, go ahead and install the67-application with::68-69- pip install --editable .70-71-The above installation command assumes that it is run within the projects72-root directory, ``flaskr/``. The ``editable`` flag allows editing73-source code without having to reinstall the Flask app each time you make74-changes. The flaskr app is now installed in your virtualenv (see output75-of ``pip freeze``).76-77-With that out of the way, you should be able to start up the application.78-Do this on Mac or Linux with the following commands in ``flaskr/``::79-80- export FLASK_APP=flaskr81- export FLASK_ENV=development82- flask run83-84-(In case you are on Windows you need to use ``set`` instead of ``export``).85-Exporting ``FLASK_ENV=development`` turns on all development features86-such as enabling the interactive debugger.87-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 in a browser.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.iodeleted:docs/tutorial/schema.rst-25 removed
1-.. _tutorial-schema:2-3-Step 1: Database Schema4-=======================5-6-In this step, you will create the database schema. Only a single table is7-needed for this application and it will only support SQLite. All you need to do8-is put the following contents into a file named :file:`schema.sql` in the9-:file:`flaskr/flaskr` folder:10-11-.. sourcecode:: sql12-13- drop table if exists entries;14- create table entries (15- id integer primary key autoincrement,16- title text not null,17- 'text' text not null18- );19-20-This schema consists of a single table called ``entries``. Each row in21-this table has an ``id``, a ``title``, and a ``text``. The ``id`` is an22-automatically incrementing integer and a primary key, the other two are23-strings that must not be null.24-25-Continue with :ref:`tutorial-setup`.deleted:docs/tutorial/setup.rst-101 removed
1-.. _tutorial-setup:2-3-Step 2: Application Setup Code4-==============================5-6-Next, we will create the application module, :file:`flaskr.py`. Just like the7-:file:`schema.sql` file you created in the previous step, this file should be8-placed inside of the :file:`flaskr/flaskr` folder.9-10-For this tutorial, all the Python code we use will be put into this file11-(except for one line in ``__init__.py``, and any testing or optional files you12-decide to create).13-14-The first several lines of code in the application module are the needed import15-statements. After that there will be a few lines of configuration code.16-17-For small applications like ``flaskr``, it is possible to drop the configuration18-directly into the module. However, a cleaner solution is to create a separate19-``.py`` file, load that, and import the values from there.20-21-Here are the import statements (in :file:`flaskr.py`)::22-23- import os24- import sqlite325-26- from flask import (Flask, request, session, g, redirect, url_for, abort,27- render_template, flash)28-29-The next couple lines will create the actual application instance and30-initialize it with the config from the same file in :file:`flaskr.py`::31-32- app = Flask(__name__) # create the application instance :)33- app.config.from_object(__name__) # load config from this file , flaskr.py34-35- # Load default config and override config from an environment variable36- app.config.update(37- DATABASE=os.path.join(app.root_path, 'flaskr.db'),38- SECRET_KEY=b'_5#y2L"F4Q8z\n\xec]/',39- USERNAME='admin',40- PASSWORD='default'41- )42- app.config.from_envvar('FLASKR_SETTINGS', silent=True)43-44-In the above code, the :class:`~flask.Config` object works similarly to a45-dictionary, so it can be updated with new values.46-47-.. admonition:: Database Path48-49- Operating systems know the concept of a current working directory for50- each process. Unfortunately, you cannot depend on this in web51- applications because you might have more than one application in the52- same process.53-54- For this reason the ``app.root_path`` attribute can be used to55- get the path to the application. Together with the ``os.path`` module,56- files can then easily be found. In this example, we place the57- database right next to it.58-59- For a real-world application, it's recommended to use60- :ref:`instance-folders` instead.61-62-Usually, it is a good idea to load a separate, environment-specific63-configuration file. Flask allows you to import multiple configurations and it64-will use the setting defined in the last import. This enables robust65-configuration setups. :meth:`~flask.Config.from_envvar` can help achieve66-this. ::67-68- app.config.from_envvar('FLASKR_SETTINGS', silent=True)69-70-If you want to do this (not required for this tutorial) simply define the71-environment variable :envvar:`FLASKR_SETTINGS` that points to a config file72-to be loaded. The silent switch just tells Flask to not complain if no such73-environment key is set.74-75-In addition to that, you can use the :meth:`~flask.Config.from_object`76-method on the config object and provide it with an import name of a77-module. Flask will then initialize the variable from that module. Note78-that in all cases, only variable names that are uppercase are considered.79-80-The :data:`SECRET_KEY` is needed to keep the client-side sessions secure.81-Choose that key wisely and as hard to guess and complex as possible.82-83-Lastly, add a method that allows for easy connections to the specified84-database. ::85-86- def connect_db():87- """Connects to the specific database."""88-89- rv = sqlite3.connect(app.config['DATABASE'])90- rv.row_factory = sqlite3.Row91- return rv92-93-This can be used to open a connection on request and also from the94-interactive Python shell or a script. This will come in handy later.95-You can create a simple database connection through SQLite and then tell96-it to use the :class:`sqlite3.Row` object to represent rows. This allows97-the rows to be treated as if they were dictionaries instead of tuples.98-99-In the next section you will see how to run the application.100-101-Continue with :ref:`tutorial-packaging`.added:docs/tutorial/static.rst+72 added
1+Static Files2+============3+4+The authentication views and templates work, but they look very plain5+right now. Some `CSS`_ can be added to add style to the HTML layout you6+constructed. The style won't change, so it's a *static* file rather than7+a template.8+9+Flask automatically adds a ``static`` view that takes a path relative10+to the ``flaskr/static`` directory and serves it. The ``base.html``11+template already has a link to the ``style.css`` file:12+13+.. code-block:: html+jinja14+15+ {{ url_for('static', filename='style.css') }}16+17+Besides CSS, other types of static files might be files with JavaScript18+functions, or a logo image. They are all placed under the19+``flaskr/static`` directory and referenced with20+``url_for('static', filename='...')``.21+22+This tutorial isn't focused on how to write CSS, so you can just copy23+the following into the ``flaskr/static/style.css`` file:24+25+.. code-block:: css26+ :caption: ``flaskr/static/style.css``27+28+ html { font-family: sans-serif; background: #eee; padding: 1rem; }29+ body { max-width: 960px; margin: 0 auto; background: white; }30+ h1 { font-family: serif; color: #377ba8; margin: 1rem 0; }31+ a { color: #377ba8; }32+ hr { border: none; border-top: 1px solid lightgray; }33+ nav { background: lightgray; display: flex; align-items: center; padding: 0 0.5rem; }34+ nav h1 { flex: auto; margin: 0; }35+ nav h1 a { text-decoration: none; padding: 0.25rem 0.5rem; }36+ nav ul { display: flex; list-style: none; margin: 0; padding: 0; }37+ nav ul li a, nav ul li span, header .action { display: block; padding: 0.5rem; }38+ .content { padding: 0 1rem 1rem; }39+ .content > header { border-bottom: 1px solid lightgray; display: flex; align-items: flex-end; }40+ .content > header h1 { flex: auto; margin: 1rem 0 0.25rem 0; }41+ .flash { margin: 1em 0; padding: 1em; background: #cae6f6; border: 1px solid #377ba8; }42+ .post > header { display: flex; align-items: flex-end; font-size: 0.85em; }43+ .post > header > div:first-of-type { flex: auto; }44+ .post > header h1 { font-size: 1.5em; margin-bottom: 0; }45+ .post .about { color: slategray; font-style: italic; }46+ .post .body { white-space: pre-line; }47+ .content:last-child { margin-bottom: 0; }48+ .content form { margin: 1em 0; display: flex; flex-direction: column; }49+ .content label { font-weight: bold; margin-bottom: 0.5em; }50+ .content input, .content textarea { margin-bottom: 1em; }51+ .content textarea { min-height: 12em; resize: vertical; }52+ input.danger { color: #cc2f2e; }53+ input[type=submit] { align-self: start; min-width: 10em; }54+55+You can find a less compact version of ``style.css`` in the56+:gh:`example code <examples/tutorial/flaskr/static/style.css>`.57+58+Go to http://127.0.0.1/auth/login and the page should look like the59+screenshot below.60+61+.. image:: flaskr_login.png62+ :align: center63+ :class: screenshot64+ :alt: screenshot of login page65+66+You can read more about CSS from `Mozilla's documentation <CSS_>`_. If67+you change a static file, refresh the browser page. If the change68+doesn't show up, try clearing your browser's cache.69+70+.. _CSS: https://developer.mozilla.org/docs/Web/CSS71+72+Continue to :doc:`blog`.modified:docs/tutorial/templates.rst+161 added-87 removed
1-.. _tutorial-templates:1+.. currentmodule:: flask2 3-Step 7: The Templates4-=====================3+Templates4+=========5 6-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.6+You've written the authentication views for your application, but if7+you're running the server and try to go to any of the URLs, you'll see a8+``TemplateNotFound`` error. That's because the views are calling9+:func:`render_template`, but you haven't written the templates yet.10+The template files will be stored in the ``templates`` directory inside11+the ``flaskr`` package.12 15-We are also using template inheritance which makes it possible to reuse16-the layout of the website in all pages.13+Templates are files that contain static data as well as placeholders14+for dynamic data. A template is rendered with specific data to produce a15+final document. Flask uses the `Jinja`_ template library to render16+templates.17 18-Create the follwing three HTML files and place them in the19-:file:`templates` folder:18+In your application, you will use templates to render `HTML`_ which19+will display in the user's browser. In Flask, Jinja is configured to20+*autoescape* any data that is rendered in HTML templates. This means21+that it's safe to render user input; any characters they've entered that22+could mess with the HTML, such as ``<`` and ``>`` will be *escaped* with23+*safe* values that look the same in the browser but don't cause unwanted24+effects.25 21-.. _Jinja2: http://jinja.pocoo.org/docs/templates26+Jinja looks and behaves mostly like Python. Special delimiters are used27+to distinguish Jinja syntax from the static data in the template.28+Anything between ``{{`` and ``}}`` is an expression that will be output29+to the final document. ``{%`` and ``%}`` denotes a control flow30+statement like ``if`` and ``for``. Unlike Python, blocks are denoted31+by start and end tags rather than indentation since static text within32+a block could change indentation.33 23-layout.html24------------34+.. _Jinja: http://jinja.pocoo.org/docs/templates/35+.. _HTML: https://developer.mozilla.org/docs/Web/HTML36 26-This template contains the HTML skeleton, the header and a link to log in27-(or log out if the user was already logged in). It also displays the28-flashed messages if there are any. The ``{% block body %}`` block can be29-replaced by a block of the same name (``body``) in a child template.37 31-The :class:`~flask.session` dict is available in the template as well and32-you can use that to check if the user is logged in or not. Note that in33-Jinja you can access missing attributes and items of objects / dicts which34-makes the following code work, even if there is no ``'logged_in'`` key in35-the session:38+The Base Layout39+---------------40 37-.. sourcecode:: html+jinja41+Each page in the application will have the same basic layout around a42+different body. Instead of writing the entire HTML structure in each43+template, each template will *extend* a base template and override44+specific sections.45 46+.. code-block:: html+jinja47+ :caption: ``flaskr/templates/base.html``48+49 <!doctype html>40- <title>Flaskr</title>41- <link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">42- <div class=page>50+ <title>{% block title %}{% endblock %} - Flaskr</title>51+ <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">52+ <nav>53 <h1>Flaskr</h1>44- <div class=metanav>45- {% if not session.logged_in %}46- <a href="{{ url_for('login') }}">log in</a>47- {% else %}48- <a href="{{ url_for('logout') }}">log out</a>49- {% endif %}50- </div>54+ <ul>55+ {% if g.user %}56+ <li><span>{{ g.user['username'] }}</span>57+ <li><a href="{{ url_for('auth.logout') }}">Log Out</a>58+ {% else %}59+ <li><a href="{{ url_for('auth.register') }}">Register</a>60+ <li><a href="{{ url_for('auth.login') }}">Log In</a>61+ {% endif %}62+ </ul>63+ </nav>64+ <section class="content">65+ <header>66+ {% block header %}{% endblock %}67+ </header>68 {% for message in get_flashed_messages() %}52- <div class=flash>{{ message }}</div>69+ <div class="flash">{{ message }}</div>70 {% endfor %}54- {% block body %}{% endblock %}55- </div>71+ {% block content %}{% endblock %}72+ </section>73 57-show_entries.html58------------------74+:data:`g` is automatically available in templates. Based on if75+``g.user`` is set (from ``load_logged_in_user``), either the username76+and a log out link are displayed, otherwise links to register and log in77+are displayed. :func:`url_for` is also automatically available, and is78+used to generate URLs to views instead of writing them out manually.79 60-This template extends the :file:`layout.html` template from above to display the61-messages. Note that the ``for`` loop iterates over the messages we passed62-in with the :func:`~flask.render_template` function. Notice that the form is63-configured to submit to the `add_entry` view function and use ``POST`` as64-HTTP method:80+After the page title, and before the content, the template loops over81+each message returned by :func:`get_flashed_messages`. You used82+:func:`flash` in the views to show error messages, and this is the code83+that will display them.84 66-.. sourcecode:: html+jinja85+There are three blocks defined here that will be overridden in the other86+templates:87 68- {% extends "layout.html" %}69- {% block body %}70- {% if session.logged_in %}71- <form action="{{ url_for('add_entry') }}" method=post class=add-entry>72- <dl>73- <dt>Title:74- <dd><input type=text size=30 name=title>75- <dt>Text:76- <dd><textarea name=text rows=5 cols=40></textarea>77- <dd><input type=submit value=Share>78- </dl>79- </form>80- {% endif %}81- <ul class=entries>82- {% for entry in entries %}83- <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}</li>84- {% else %}85- <li><em>Unbelievable. No entries here so far</em></li>86- {% endfor %}87- </ul>88+#. ``{% block title %}`` will change the title displayed in the89+ browser's tab and window title.90+91+#. ``{% block header %}`` is similar to ``title`` but will change the92+ title displayed on the page.93+94+#. ``{% block content %}`` is where the content of each page goes, such95+ as the login form or a blog post.96+97+The base template is directly in the ``templates`` directory. To keep98+the others organized, the templates for a blueprint will be placed in a99+directory with the same name as the blueprint.100+101+102+Register103+--------104+105+.. code-block:: html+jinja106+ :caption: ``flaskr/templates/auth/register.html``107+108+ {% extends 'base.html' %}109+110+ {% block header %}111+ <h1>{% block title %}Register{% endblock %}</h1>112 {% endblock %}113 90-login.html91-----------114+ {% block content %}115+ <form method="post">116+ <label for="username">Username</label>117+ <input name="username" id="username" required>118+ <label for="password">Password</label>119+ <input type="password" name="password" id="password" required>120+ <input type="submit" value="Register">121+ </form>122+ {% endblock %}123 93-This is the login template, which basically just displays a form to allow94-the user to login:124+``{% extends 'base.html' %}`` tells Jinja that this template should125+replace the blocks from the base template. All the rendered content must126+appear inside ``{% block %}`` tags that override blocks from the base127+template.128 96-.. sourcecode:: html+jinja129+A useful pattern used here is to place ``{% block title %}`` inside130+``{% block header %}``. This will set the title block and then output131+the value of it into the header block, so that both the window and page132+share the same title without writing it twice.133 98- {% extends "layout.html" %}99- {% block body %}100- <h2>Login</h2>101- {% if error %}<p class=error><strong>Error:</strong> {{ error }}{% endif %}102- <form action="{{ url_for('login') }}" method=post>103- <dl>104- <dt>Username:105- <dd><input type=text name=username>106- <dt>Password:107- <dd><input type=password name=password>108- <dd><input type=submit value=Login>109- </dl>134+The ``input`` tags are using the ``required`` attribute here. This tells135+the browser not to submit the form until those fields are filled in. If136+the user is using an older browser that doesn't support that attribute,137+or if they are using something besides a browser to make requests, you138+still want to validate the data in the Flask view. It's important to139+always fully validate the data on the server, even if the client does140+some validation as well.141+142+143+Log In144+------145+146+This is identical to the register template except for the title and147+submit button.148+149+.. code-block:: html+jinja150+ :caption: ``flaskr/templates/auth/login.html``151+152+ {% extends 'base.html' %}153+154+ {% block header %}155+ <h1>{% block title %}Log In{% endblock %}</h1>156+ {% endblock %}157+158+ {% block content %}159+ <form method="post">160+ <label for="username">Username</label>161+ <input name="username" id="username" required>162+ <label for="password">Password</label>163+ <input type="password" name="password" id="password" required>164+ <input type="submit" value="Log In">165 </form>166 {% endblock %}167 113-Continue with :ref:`tutorial-css`.168+169+Register A User170+---------------171+172+Now that the authentication templates are written, you can register a173+user. Make sure the server is still running (``flask run`` if it's not),174+then go to http://127.0.0.1:5000/auth/register.175+176+Try clicking the "Register" button without filling out the form and see177+that the browser shows an error message. Try removing the ``required``178+attributes from the ``register.html`` template and click "Register"179+again. Instead of the browser showing an error, the page will reload and180+the error from :func:`flash` in the view will be shown.181+182+Fill out a username and password and you'll be redirected to the login183+page. Try entering an incorrect username, or the correct username and184+incorrect password. If you log in you'll get an error because there's185+no ``index`` view to redirect to yet.186+187+Continue to :doc:`static`.deleted:docs/tutorial/testing.rst-96 removed
1-.. _tutorial-testing:2-3-Bonus: Testing the Application4-==============================5-6-Now that you have finished the application and everything works as7-expected, it's probably not a bad idea to add automated tests to simplify8-modifications in the future. The application above is used as a basic9-example of how to perform 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.added:docs/tutorial/tests.rst+561 added
1+.. currentmodule:: flask2+3+Test Coverage4+=============5+6+Writing unit tests for your application lets you check that the code7+you wrote works the way you expect. Flask provides a test client that8+simulates requests to the application and returns the response data.9+10+You should test as much of your code as possible. Code in functions only11+runs when the function is called, and code in branches, such as ``if``12+blocks, only runs when the condition is met. You want to make sure that13+each function is tested with data that covers each branch.14+15+The closer you get to 100% coverage, the more comfortable you can be16+that making a change won't unexpectedly change other behavior. However,17+100% coverage doesn't guarantee that your application doesn't have bugs.18+In particular, it doesn't test how the user interacts with the19+application in the browser. Despite this, test coverage is an important20+tool to use during development.21+22+.. note::23+ This is being introduced late in the tutorial, but in your future24+ projects you should test as you develop.25+26+You'll use `pytest`_ and `coverage`_ to test and measure your code.27+Install them both:28+29+.. code-block:: none30+31+ pip install pytest coverage32+33+.. _pytest: https://pytest.readthedocs.io/34+.. _coverage: https://coverage.readthedocs.io/35+36+37+Setup and Fixtures38+------------------39+40+The test code is located in the ``tests`` directory. This directory is41+*next to* the ``flaskr`` package, not inside it. The42+``tests/conftest.py`` file contains setup functions called *fixtures*43+that each test will use. Tests are in Python modules that start with44+``test_``, and each test function in those modules also starts with45+``test_``.46+47+Each test will create a new temporary database file and populate some48+data that will be used in the tests. Write a SQL file to insert that49+data.50+51+.. code-block:: sql52+ :caption: ``tests/data.sql``53+54+ INSERT INTO user (username, password)55+ VALUES56+ ('test', 'pbkdf2:sha256:50000$TCI4GzcX$0de171a4f4dac32e3364c7ddc7c14f3e2fa61f2d17574483f7ffbb431b4acb2f'),57+ ('other', 'pbkdf2:sha256:50000$kJPKsz6N$d2d4784f1b030a9761f5ccaeeaca413f27f2ecb76d6168407af962ddce849f79');58+59+ INSERT INTO post (title, body, author_id, created)60+ VALUES61+ ('test title', 'test' || x'0a' || 'body', 1, '2018-01-01 00:00:00');62+63+The ``app`` fixture will call the factory and pass ``test_config`` to64+configure the application and database for testing instead of using your65+local development configuration.66+67+.. code-block:: python68+ :caption: ``tests/conftest.py``69+70+ import os71+ import tempfile72+73+ import pytest74+ from flaskr import create_app75+ from flaskr.db import get_db, init_db76+77+ with open(os.path.join(os.path.dirname(__file__), 'data.sql'), 'rb') as f:78+ _data_sql = f.read().decode('utf8')79+80+81+ @pytest.fixture82+ def app():83+ db_fd, db_path = tempfile.mkstemp()84+85+ app = create_app({86+ 'TESTING': True,87+ 'DATABASE': db_path,88+ })89+90+ with app.app_context():91+ init_db()92+ get_db().executescript(_data_sql)93+94+ yield app95+96+ os.close(db_fd)97+ os.unlink(db_path)98+99+100+ @pytest.fixture101+ def client(app):102+ return app.test_client()103+104+105+ @pytest.fixture106+ def runner(app):107+ return app.test_cli_runner()108+109+:func:`tempfile.mkstemp` creates and opens a temporary file, returning110+the file object and the path to it. The ``DATABASE`` path is111+overridden so it points to this temporary path instead of the instance112+folder. After setting the path, the database tables are created and the113+test data is inserted. After the test is over, the temporary file is114+closed and removed.115+116+:data:`TESTING` tells Flask that the app is in test mode. Flask changes117+some internal behavior so it's easier to test, and other extensions can118+also use the flag to make testing them easier.119+120+The ``client`` fixture calls121+:meth:`app.test_client() <Flask.test_client>` with the application122+object created by the ``app`` fixture. Tests will use the client to make123+requests to the application without running the server.124+125+The ``runner`` fixture is similar to ``client``.126+:meth:`app.test_cli_runner() <Flask.test_cli_runner>` creates a runner127+that can call the Click commands registered with the application.128+129+Pytest uses fixtures by matching their function names with the names130+of arguments in the test functions. For example, the ``test_hello``131+function you'll write next takes a ``client`` argument. Pytest matches132+that with the ``client`` fixture function, calls it, and passes the133+returned value to the test function.134+135+136+Factory137+-------138+139+There's not much to test about the factory itself. Most of the code will140+be executed for each test already, so if something fails the other tests141+will notice.142+143+The only behavior that can change is passing test config. If config is144+not passed, there should be some default configuration, otherwise the145+configuration should be overridden.146+147+.. code-block:: python148+ :caption: ``tests/test_factory.py``149+150+ from flaskr import create_app151+152+153+ def test_config():154+ assert not create_app().testing155+ assert create_app({'TESTING': True}).testing156+157+158+ def test_hello(client):159+ response = client.get('/hello')160+ assert response.data == b'Hello, World!'161+162+You added the ``hello`` route as an example when writing the factory at163+the beginning of the tutorial. It returns "Hello, World!", so the test164+checks that the response data matches.165+166+167+Database168+--------169+170+Within an application context, ``get_db`` should return the same171+connection each time it's called. After the context, the connection172+should be closed.173+174+.. code-block:: python175+ :caption: ``tests/test_db.py``176+177+ import sqlite3178+179+ import pytest180+ from flaskr.db import get_db181+182+183+ def test_get_close_db(app):184+ with app.app_context():185+ db = get_db()186+ assert db is get_db()187+188+ with pytest.raises(sqlite3.ProgrammingError) as e:189+ db.execute('SELECT 1')190+191+ assert 'closed' in str(e)192+193+The ``init-db`` command should call the ``init_db`` function and output194+a message.195+196+.. code-block:: python197+ :caption: ``tests/test_db.py``198+199+ def test_init_db_command(runner, monkeypatch):200+ class Recorder(object):201+ called = False202+203+ def fake_init_db():204+ Recorder.called = True205+206+ monkeypatch.setattr('flaskr.db.init_db', fake_init_db)207+ result = runner.invoke(args=['init-db'])208+ assert 'Initialized' in result.output209+ assert Recorder.called210+211+This test uses Pytest's ``monkeypatch`` fixture to replace the212+``init_db`` function with one that records that it's been called. The213+``runner`` fixture you wrote above is used to call the ``init-db``214+command by name.215+216+217+Authentication218+--------------219+220+For most of the views, a user needs to be logged in. The easiest way to221+do this in tests is to make a ``POST`` request to the ``login`` view222+with the client. Rather than writing that out every time, you can write223+a class with methods to do that, and use a fixture to pass it the client224+for each test.225+226+.. code-block:: python227+ :caption: ``tests/conftest.py``228+229+ class AuthActions(object):230+ def __init__(self, client):231+ self._client = client232+233+ def login(self, username='test', password='test'):234+ return self._client.post(235+ '/auth/login',236+ data={'username': username, 'password': password}237+ )238+239+ def logout(self):240+ return self._client.get('/auth/logout')241+242+243+ @pytest.fixture244+ def auth(client):245+ return AuthActions(client)246+247+With the ``auth`` fixture, you can call ``auth.login()`` in a test to248+log in as the ``test`` user, which was inserted as part of the test249+data in the ``app`` fixture.250+251+The ``register`` view should render successfully on ``GET``. On ``POST``252+with valid form data, it should redirect to the login URL and the user's253+data should be in the database. Invalid data should display error254+messages.255+256+.. code-block:: python257+ :caption: ``tests/test_auth.py``258+259+ import pytest260+ from flask import g, session261+ from flaskr.db import get_db262+263+264+ def test_register(client, app):265+ assert client.get('/auth/register').status_code == 200266+ response = client.post(267+ '/auth/register', data={'username': 'a', 'password': 'a'}268+ )269+ assert 'http://localhost/auth/login' == response.headers['Location']270+271+ with app.app_context():272+ assert get_db().execute(273+ "select * from user where username = 'a'",274+ ).fetchone() is not None275+276+277+ @pytest.mark.parametrize(('username', 'password', 'message'), (278+ ('', '', b'Username is required.'),279+ ('a', '', b'Password is required.'),280+ ('test', 'test', b'already registered'),281+ ))282+ def test_register_validate_input(client, username, password, message):283+ response = client.post(284+ '/auth/register',285+ data={'username': username, 'password': password}286+ )287+ assert message in response.data288+289+:meth:`client.get() <werkzeug.test.Client.get>` makes a ``GET`` request290+and returns the :class:`Response` object returned by Flask. Similarly,291+:meth:`client.post() <werkzeug.test.Client.post>` makes a ``POST``292+request, converting the ``data`` dict into form data.293+294+To test that the page renders successfully, a simple request is made and295+checked for a ``200 OK`` :attr:`~Response.status_code`. If296+rendering failed, Flask would return a ``500 Internal Server Error``297+code.298+299+:attr:`~Response.headers` will have a ``Location`` header with the login300+URL when the register view redirects to the login view.301+302+:attr:`~Response.data` contains the body of the response as bytes. If303+you expect a certain value to render on the page, check that it's in304+``data``. Bytes must be compared to bytes. If you want to compare305+Unicode text, use :meth:`get_data(as_text=True) <werkzeug.wrappers.BaseResponse.get_data>`306+instead.307+308+``pytest.mark.parametrize`` tells Pytest to run the same test function309+with different arguments. You use it here to test different invalid310+input and error messages without writing the same code three times.311+312+The tests for the ``login`` view are very similar to those for313+``register``. Rather than testing the data in the database,314+:data:`session` should have ``user_id`` set after logging in.315+316+.. code-block:: python317+ :caption: ``tests/test_auth.py``318+319+ def test_login(client, auth):320+ assert client.get('/auth/login').status_code == 200321+ response = auth.login()322+ assert response.headers['Location'] == 'http://localhost/'323+324+ with client:325+ client.get('/')326+ assert session['user_id'] == 1327+ assert g.user['username'] == 'test'328+329+330+ @pytest.mark.parametrize(('username', 'password', 'message'), (331+ ('a', 'test', b'Incorrect username.'),332+ ('test', 'a', b'Incorrect password.'),333+ ))334+ def test_login_validate_input(auth, username, password, message):335+ response = auth.login(username, password)336+ assert message in response.data337+338+Using ``client`` in a ``with`` block allows accessing context variables339+such as :data:`session` after the response is returned. Normally,340+accessing ``session`` outside of a request would raise an error.341+342+Testing ``logout`` is the opposite of ``login``. :data:`session` should343+not contain ``user_id`` after logging out.344+345+.. code-block:: python346+ :caption: ``tests/test_auth.py``347+348+ def test_logout(client, auth):349+ auth.login()350+351+ with client:352+ auth.logout()353+ assert 'user_id' not in session354+355+356+Blog357+----358+359+All the blog views use the ``auth`` fixture you wrote earlier. Call360+``auth.login()`` and subsequent requests from the client will be logged361+in as the ``test`` user.362+363+The ``index`` view should display information about the post that was364+added with the test data. When logged in as the author, there should be365+a link to edit the post.366+367+You can also test some more authentication behavior while testing the368+``index`` view. When not logged in, each page shows links to log in or369+register. When logged in, there's a link to log out.370+371+.. code-block:: python372+ :caption: ``tests/test_blog.py``373+374+ import pytest375+ from flaskr.db import get_db376+377+378+ def test_index(client, auth):379+ response = client.get('/')380+ assert b"Log In" in response.data381+ assert b"Register" in response.data382+383+ auth.login()384+ response = client.get('/')385+ assert b'Log Out' in response.data386+ assert b'test title' in response.data387+ assert b'by test on 2018-01-01' in response.data388+ assert b'test\nbody' in response.data389+ assert b'href="/1/update"' in response.data390+391+A user must be logged in to access the ``create``, ``update``, and392+``delete`` views. The logged in user must be the author of the post to393+access ``update`` and ``delete``, otherwise a ``403 Forbidden`` status394+is returned. If a ``post`` with the given ``id`` doesn't exist,395+``update`` and ``delete`` should return ``404 Not Found``.396+397+.. code-block:: python398+ :caption: ``tests/test_blog.py``399+400+ @pytest.mark.parametrize('path', (401+ '/create',402+ '/1/update',403+ '/1/delete',404+ ))405+ def test_login_required(client, path):406+ response = client.post(path)407+ assert response.headers['Location'] == 'http://localhost/auth/login'408+409+410+ def test_author_required(app, client, auth):411+ # change the post author to another user412+ with app.app_context():413+ db = get_db()414+ db.execute('UPDATE post SET author_id = 2 WHERE id = 1')415+ db.commit()416+417+ auth.login()418+ # current user can't modify other user's post419+ assert client.post('/1/update').status_code == 403420+ assert client.post('/1/delete').status_code == 403421+ # current user doesn't see edit link422+ assert b'href="/1/update"' not in client.get('/').data423+424+425+ @pytest.mark.parametrize('path', (426+ '/2/update',427+ '/2/delete',428+ ))429+ def test_exists_required(client, auth, path):430+ auth.login()431+ assert client.post(path).status_code == 404432+433+The ``create`` and ``update`` views should render and return a434+``200 OK`` status for a ``GET`` request. When valid data is sent in a435+``POST`` request, ``create`` should insert the new post data into the436+database, and ``update`` should modify the existing data. Both pages437+should show an error message on invalid data.438+439+.. code-block:: python440+ :caption: ``tests/test_blog.py``441+442+ def test_create(client, auth, app):443+ auth.login()444+ assert client.get('/create').status_code == 200445+ client.post('/create', data={'title': 'created', 'body': ''})446+447+ with app.app_context():448+ db = get_db()449+ count = db.execute('SELECT COUNT(id) FROM post').fetchone()[0]450+ assert count == 2451+452+453+ def test_update(client, auth, app):454+ auth.login()455+ assert client.get('/1/update').status_code == 200456+ client.post('/1/update', data={'title': 'updated', 'body': ''})457+458+ with app.app_context():459+ db = get_db()460+ post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()461+ assert post['title'] == 'updated'462+463+464+ @pytest.mark.parametrize('path', (465+ '/create',466+ '/1/update',467+ ))468+ def test_create_update_validate(client, auth, path):469+ auth.login()470+ response = client.post(path, data={'title': '', 'body': ''})471+ assert b'Title is required.' in response.data472+473+The ``delete`` view should redirect to the index URL and the post should474+no longer exist in the database.475+476+.. code-block:: python477+ :caption: ``tests/test_blog.py``478+479+ def test_delete(client, auth, app):480+ auth.login()481+ response = client.post('/1/delete')482+ assert response.headers['Location'] == 'http://localhost/'483+484+ with app.app_context():485+ db = get_db()486+ post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()487+ assert post is None488+489+490+Running the Tests491+-----------------492+493+Some extra configuration, which is not required but makes running494+tests with coverage less verbose, can be added to the project's495+``setup.cfg`` file.496+497+.. code-block:: none498+ :caption: ``setup.cfg``499+500+ [tool:pytest]501+ testpaths = tests502+503+ [coverage:run]504+ branch = True505+ source =506+ flaskr507+508+To run the tests, use the ``pytest`` command. It will find and run all509+the test functions you've written.510+511+.. code-block:: none512+513+ pytest514+515+ ========================= test session starts ==========================516+ platform linux -- Python 3.6.4, pytest-3.5.0, py-1.5.3, pluggy-0.6.0517+ rootdir: /home/user/Projects/flask-tutorial, inifile: setup.cfg518+ collected 23 items519+520+ tests/test_auth.py ........ [ 34%]521+ tests/test_blog.py ............ [ 86%]522+ tests/test_db.py .. [ 95%]523+ tests/test_factory.py .. [100%]524+525+ ====================== 24 passed in 0.64 seconds =======================526+527+If any tests fail, pytest will show the error that was raised. You can528+run ``pytest -v`` to get a list of each test function rather than dots.529+530+To measure the code coverage of your tests, use the ``coverage`` command531+to run pytest instead of running it directly.532+533+.. code-block:: none534+535+ coverage run -m pytest536+537+You can either view a simple coverage report in the terminal:538+539+.. code-block:: none540+541+ coverage report542+543+ Name Stmts Miss Branch BrPart Cover544+ ------------------------------------------------------545+ flaskr/__init__.py 21 0 2 0 100%546+ flaskr/auth.py 54 0 22 0 100%547+ flaskr/blog.py 54 0 16 0 100%548+ flaskr/db.py 24 0 4 0 100%549+ ------------------------------------------------------550+ TOTAL 153 0 44 0 100%551+552+An HTML report allows you to see which lines were covered in each file:553+554+.. code-block:: none555+556+ coverage html557+558+This generates files in the ``htmlcov`` directory. Open559+``htmlcov/index.html`` in your browser to see the report.560+561+Continue to :doc:`deploy`.modified:docs/tutorial/views.rst+273 added-90 removed
1-.. _tutorial-views:1+.. currentmodule:: flask2 3-Step 6: The View Functions4-==========================3+Blueprints and Views4+====================5 6-Now that the database connections are working, you can start writing the7-view functions. You will need four of them; Show Entries, Add New Entry,8-Login and Logout. Add the following code snipets to :file:`flaskr.py`.6+A view function is the code you write to respond to requests to your7+application. Flask uses patterns to match the incoming request URL to8+the view that should handle it. The view returns data that Flask turns9+into an outgoing response. Flask can also go the other direction and10+generate a URL to a view based on its name and arguments.11 10-Show Entries11-------------12 13-This view shows all the entries stored in the database. It listens on the14-root of the application and will select title and text from the database.15-The one with the highest id (the newest entry) will be on top. The rows16-returned from the cursor look a bit like dictionaries because we are using17-the :class:`sqlite3.Row` row factory.13+Create a Blueprint14+------------------15 19-The view function will pass the entries to the :file:`show_entries.html`20-template and return the rendered one::16+A :class:`Blueprint` is a way to organize a group of related views and17+other code. Rather than registering views and other code directly with18+an application, they are registered with a blueprint. Then the blueprint19+is registered with the application when it is available in the factory20+function.21 22- @app.route('/')23- def show_entries():24- db = get_db()25- cur = db.execute('select title, text from entries order by id desc')26- entries = cur.fetchall()27- return render_template('show_entries.html', entries=entries)22+Flaskr will have two blueprints, one for authentication functions and23+one for the blog posts functions. The code for each blueprint will go24+in a separate module. Since the blog needs to know about authentication,25+you'll write the authentication one first.26 29-Add New Entry30--------------27+.. code-block:: python28+ :caption: ``flaskr/auth.py``29 32-This view lets the user add new entries if they are logged in. This only33-responds to ``POST`` requests; the actual form is shown on the34-`show_entries` page. If everything worked out well, it will35-:func:`~flask.flash` an information message to the next request and36-redirect back to the `show_entries` page::30+ import functools31 38- @app.route('/add', methods=['POST'])39- def add_entry():40- if not session.get('logged_in'):41- abort(401)42- db = get_db()43- db.execute('insert into entries (title, text) values (?, ?)',44- [request.form['title'], request.form['text']])45- db.commit()46- flash('New entry was successfully posted')47- return redirect(url_for('show_entries'))32+ from flask import (33+ Blueprint, flash, g, redirect, render_template, request, session, url_for34+ )35+ from werkzeug.security import check_password_hash, generate_password_hash36 49-Note that this view checks that the user is logged in (that is, if the50-`logged_in` key is present in the session and ``True``).37+ from flaskr.db import get_db38 52-.. admonition:: Security Note39+ bp = Blueprint('auth', __name__, url_prefix='/auth')40 54- Be sure to use question marks when building SQL statements, as done in the55- example above. Otherwise, your app will be vulnerable to SQL injection when56- you use string formatting to build SQL statements.57- See :ref:`sqlite3` for more.41+This creates a :class:`Blueprint` named ``'auth'``. Like the application42+object, the blueprint needs to know where it's defined, so ``__name__``43+is passed as the second argument. The ``url_prefix`` will be prepended44+to all the URLs associated with the blueprint.45 59-Login and Logout60-----------------46+Import and register the blueprint from the factory using47+:meth:`app.register_blueprint() <Flask.register_blueprint>`. Place the48+new code at the end of the factory function before returning the app.49 62-These functions are used to sign the user in and out. Login checks the63-username and password against the ones from the configuration and sets the64-`logged_in` key for the session. If the user logged in successfully, that65-key is set to ``True``, and the user is redirected back to the `show_entries`66-page. In addition, a message is flashed that informs the user that he or67-she was logged in successfully. If an error occurred, the template is68-notified about that, and the user is asked again::50+.. code-block:: python51+ :caption: ``flaskr/__init__.py``52 70- @app.route('/login', methods=['GET', 'POST'])53+ def create_app():54+ app = ...55+ # existing code omitted56+57+ from . import auth58+ app.register_blueprint(auth.bp)59+60+ return app61+62+The authentication blueprint will have views to register new users and63+to log in and log out.64+65+66+The First View: Register67+------------------------68+69+When the user visits the ``/auth/register`` URL, the ``register`` view70+will return `HTML`_ with a form for them to fill out. When they submit71+the form, it will validate their input and either show the form again72+with an error message or create the new user and go to the login page.73+74+.. _HTML: https://developer.mozilla.org/docs/Web/HTML75+76+For now you will just write the view code. On the next page, you'll77+write templates to generate the HTML form.78+79+.. code-block:: python80+ :caption: ``flaskr/auth.py``81+82+ @bp.route('/register', methods=('GET', 'POST'))83+ def register():84+ if request.method == 'POST':85+ username = request.form['username']86+ password = request.form['password']87+ db = get_db()88+ error = None89+90+ if not username:91+ error = 'Username is required.'92+ elif not password:93+ error = 'Password is required.'94+ elif db.execute(95+ 'SELECT id FROM user WHERE username = ?', (username,)96+ ).fetchone() is not None:97+ error = 'User {} is already registered.'.format(username)98+99+ if error is None:100+ db.execute(101+ 'INSERT INTO user (username, password) VALUES (?, ?)',102+ (username, generate_password_hash(password))103+ )104+ db.commit()105+ return redirect(url_for('auth.login'))106+107+ flash(error)108+109+ return render_template('auth/register.html')110+111+Here's what the ``register`` view function is doing:112+113+#. :meth:`@bp.route <Blueprint.route>` associates the URL ``/register``114+ with the ``register`` view function. When Flask receives a request115+ to ``/auth/register``, it will call the ``register`` view and use116+ the return value as the response.117+118+#. If the user submitted the form,119+ :attr:`request.method <Request.method>` will be ``'POST'``. In this120+ case, start validating the input.121+122+#. :attr:`request.form <Request.form>` is a special type of123+ :class:`dict` mapping submitted form keys and values. The user will124+ input their ``username`` and ``password``.125+126+#. Validate that ``username`` and ``password`` are not empty.127+128+#. Validate that ``username`` is not already registered by querying the129+ database and checking if a result is returned.130+ :meth:`db.execute <sqlite3.Connection.execute>` takes a SQL query131+ with ``?`` placeholders for any user input, and a tuple of values132+ to replace the placeholders with. The database library will take133+ care of escaping the values so you are not vulnerable to a134+ *SQL injection attack*.135+136+ :meth:`~sqlite3.Cursor.fetchone` returns one row from the query.137+ If the query returned no results, it returns ``None``. Later,138+ :meth:`~sqlite3.Cursor.fetchall` is used, which returns a list of139+ all results.140+141+#. If validation succeeds, insert the new user data into the database.142+ For security, passwords should never be stored in the database143+ directly. Instead,144+ :func:`~werkzeug.security.generate_password_hash` is used to145+ securely hash the password, and that hash is stored. Since this146+ query modifies data, :meth:`db.commit() <sqlite3.Connection.commit>`147+ needs to be called afterwards to save the changes.148+149+#. After storing the user, they are redirected to the login page.150+ :func:`url_for` generates the URL for the login view based on its151+ name. This is preferable to writing the URL directly as it allows152+ you to change the URL later without changing all code that links to153+ it. :func:`redirect` generates a redirect response to the generated154+ URL.155+156+#. If validation fails, the error is shown to the user. :func:`flash`157+ stores messages that can be retrieved when rendering the template.158+159+#. When the user initially navigates to ``auth/register``, or160+ there was an validation error, an HTML page with the registration161+ form should be shown. :func:`render_template` will render a template162+ containing the HTML, which you'll write in the next step of the163+ tutorial.164+165+166+Login167+-----168+169+This view follows the same pattern as the ``register`` view above.170+171+.. code-block:: python172+ :caption: ``flaskr/auth.py``173+174+ @bp.route('/login', methods=('GET', 'POST'))175 def login():72- error = None176 if request.method == 'POST':74- if request.form['username'] != app.config['USERNAME']:75- error = 'Invalid username'76- elif request.form['password'] != app.config['PASSWORD']:77- error = 'Invalid password'78- else:79- session['logged_in'] = True80- flash('You were logged in')81- return redirect(url_for('show_entries'))82- return render_template('login.html', error=error)177+ username = request.form['username']178+ password = request.form['password']179+ db = get_db()180+ error = None181+ user = db.execute(182+ 'SELECT * FROM user WHERE username = ?', (username,)183+ ).fetchone()184 84-The `logout` function, on the other hand, removes that key from the session85-again. There is a neat trick here: if you use the :meth:`~dict.pop` method86-of the dict and pass a second parameter to it (the default), the method87-will delete the key from the dictionary if present or do nothing when that88-key is not in there. This is helpful because now it is not necessary to89-check if the user was logged in.185+ if user is None:186+ error = 'Incorrect username.'187+ elif not check_password_hash(user['password'], password):188+ error = 'Incorrect password.'189 91-::190+ if error is None:191+ session.clear()192+ session['user_id'] = user['id']193+ return redirect(url_for('index'))194 195+ flash(error)196+197+ return render_template('auth/login.html')198+199+There are a few differences from the ``register`` view:200+201+#. The user is queried first and stored in a variable for later use.202+203+#. :func:`~werkzeug.security.check_password_hash` hashes the submitted204+ password in the same way as the stored hash and securely compares205+ them. If they match, the password is valid.206+207+#. :data:`session` is a :class:`dict` that stores data across requests.208+ When validation succeeds, the user's ``id`` is stored in a new209+ session. The data is stored in a *cookie* that is sent to the210+ browser, and the browser then sends it back with subsequent requests.211+ Flask securely *signs* the data so that it can't be tampered with.212+213+Now that the user's ``id`` is stored in the :data:`session`, it will be214+available on subsequent requests. At the beginning of each request, if215+a user is logged in their information should be loaded and made216+available to other views.217+218+.. code-block:: python219+ :caption: ``flaskr/auth.py``220+221+ @bp.before_app_request222+ def load_logged_in_user():223+ user_id = session.get('user_id')224+225+ if user_id is None:226+ g.user = None227+ else:228+ g.user = get_db().execute(229+ 'SELECT * FROM user WHERE id = ?', (user_id,)230+ ).fetchone()231+232+:meth:`bp.before_app_request() <Blueprint.before_app_request>` registers233+a function that runs before the view function, no matter what URL is234+requested. ``load_logged_in_user`` checks if a user id is stored in the235+:data:`session` and gets that user's data from the database, storing it236+on :data:`g.user <g>`, which lasts for the length of the request. If237+there is no user id, or if the id doesn't exist, ``g.user`` will be238+``None``.239+240+241+Logout242+------243+244+To log out, you need to remove the user id from the :data:`session`.245+Then ``load_logged_in_user`` won't load a user on subsequent requests.246+247+.. code-block:: python248+ :caption: ``flaskr/auth.py``249+93- @app.route('/logout')250+ @bp.route('/logout')251 def logout():95- session.pop('logged_in', None)96- flash('You were logged out')97- return redirect(url_for('show_entries'))252+ session.clear()253+ return redirect(url_for('index'))254 99-.. admonition:: Security Note255 101- Passwords should never be stored in plain text in a production102- system. This tutorial uses plain text passwords for simplicity. If you103- plan to release a project based off this tutorial out into the world,104- passwords should be both `hashed and salted`_ before being stored in a105- database or file.256+Require Authentication in Other Views257+-------------------------------------258 107- Fortunately, there are Flask extensions for the purpose of108- hashing passwords and verifying passwords against hashes, so adding109- this functionality is fairly straight forward. There are also110- many general python libraries that can be used for hashing.259+Creating, editing, and deleting blog posts will require a user to be260+logged in. A *decorator* can be used to check this for each view it's261+applied to.262 112- You can find a list of recommended Flask extensions113- `here <http://flask.pocoo.org/extensions/>`_263+.. code-block:: python264+ :caption: ``flaskr/auth.py``265 266+ def login_required(view):267+ @functools.wraps(view)268+ def wrapped_view(**kwargs):269+ if g.user is None:270+ return redirect(url_for('auth.login'))271 116-Continue with :ref:`tutorial-templates`.272+ return view(**kwargs)273 118-.. _hashed and salted: https://blog.codinghorror.com/youre-probably-storing-passwords-incorrectly/274+ return wrapped_view275+276+This decorator returns a new view function that wraps the original view277+it's applied to. The new function checks if a user is loaded and278+redirects to the login page otherwise. If a user is loaded the original279+view is called and continues normally. You'll use this decorator when280+writing the blog views.281+282+Endpoints and URLs283+------------------284+285+The :func:`url_for` function generates the URL to a view based on a name286+and arguments. The name associated with a view is also called the287+*endpoint*, and by default it's the same as the name of the view288+function.289+290+For example, the ``hello()`` view that was added to the app291+factory earlier in the tutorial has the name ``'hello'`` and can be292+linked to with ``url_for('hello')``. If it took an argument, which293+you'll see later, it would be linked to using294+``url_for('hello', who='World')``.295+296+When using a blueprint, the name of the blueprint is prepended to the297+name of the function, so the endpoint for the ``login`` function you298+wrote above is ``'auth.login'`` because you added it to the ``'auth'``299+blueprint.300+301+Continue to :doc:`templates`.modified:docs/conf.py+35 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+15+import datetime16 import os17 import sys16-import pkg_resources18 import time18-import datetime19 20-from sphinx.application import Sphinx20+import pkg_resources21 22 BUILD_DATE = datetime.datetime.utcfromtimestamp(int(os.environ.get('SOURCE_DATE_EPOCH', time.time())))23 24 # If extensions (or modules to document with autodoc) are in another directory,274 unmodified lines299 unwrap_decorators()300 del unwrap_decorators301 302 303-def setup(app: Sphinx):303+def setup(app):304 def cut_module_meta(app, what, name, obj, options, lines):305 """Remove metadata from autodoc output."""306 if what != 'module':307 return3 unmodified lines311 if not line.startswith((':copyright:', ':license:'))312 ]313 314 app.connect('autodoc-process-docstring', cut_module_meta)315+316+ def github_link(317+ name, rawtext, text, lineno, inliner,318+ options=None, content=None319+ ):320+ app = inliner.document.settings.env.app321+ release = app.config.release322+ base_url = 'https://github.com/pallets/flask/tree/'323+324+ if text.endswith('>'):325+ words, text = text[:-1].rsplit('<', 1)326+ words = words.strip()327+ else:328+ words = None329+330+ if release.endswith('dev'):331+ url = '{0}master/{1}'.format(base_url, text)332+ else:333+ url = '{0}{1}/{2}'.format(base_url, release, text)334+335+ if words is None:336+ words = url337+338+ from docutils.nodes import reference339+ from docutils.parsers.rst.roles import set_classes340+ options = options or {}341+ set_classes(options)342+ node = reference(rawtext, words, refuri=url, **options)343+ return [node], []344+345+ app.add_role('gh', github_link)modified:docs/installation.rst+2 added
102 unmodified lines103 .. code-block:: bat104 105 \Python27\Scripts\virtualenv.exe venv106 107+.. _install-activate-env:108+109 Activate the environment110 ~~~~~~~~~~~~~~~~~~~~~~~~111 112 Before you work on your project, activate the corresponding environment:71 unmodified linesmodified:docs/testing.rst+1 added-4 removed
26 unmodified lines27 ---------------28 29 First, we need an application to test; we will use the application from30 the :ref:`tutorial`. If you don't have that application yet, get the31-source code from `the examples`_.31+source code from :gh:`the examples <examples/tutorial>`.32 33-.. _the examples:34- https://github.com/pallets/flask/tree/master/examples/flaskr/35-33 The Testing Skeleton34 --------------------35 36 We begin by adding a tests directory under the application root. Then426 unmodified linesdeleted:examples/blueprintexample/simple_page/templates/pages/hello.html-5 removed
1-{% extends "pages/layout.html" %}2-3-{% block body %}4- Hello5-{% endblock %}deleted:examples/blueprintexample/simple_page/templates/pages/index.html-5 removed
1-{% extends "pages/layout.html" %}2-3-{% block body %}4- Blueprint example page5-{% endblock %}deleted:examples/blueprintexample/simple_page/templates/pages/layout.html-20 removed
1-<!doctype html>2-<title>Simple Page Blueprint</title>3-<div class="page">4- <h1>This is blueprint example</h1>5- <p>6- A simple page blueprint is registered under / and /pages7- you can access it using this URLs:8- <ul>9- <li><a href="{{ url_for('simple_page.show', page='hello') }}">/hello</a>10- <li><a href="{{ url_for('simple_page.show', page='world') }}">/world</a>11- </ul>12- <p>13- Also you can register the same blueprint under another path14- <ul>15- <li><a href="/pages/hello">/pages/hello</a>16- <li><a href="/pages/world">/pages/world</a>17- </ul>18-19- {% block body %}{% endblock %}20-</div>deleted:examples/blueprintexample/simple_page/templates/pages/world.html-4 removed
1-{% extends "pages/layout.html" %}2-{% block body %}3- World4-{% endblock %}deleted:examples/blueprintexample/simple_page/__init__.py
deleted:examples/blueprintexample/simple_page/simple_page.py-13 removed
1-from flask import Blueprint, render_template, abort2-from jinja2 import TemplateNotFound3-4-simple_page = Blueprint('simple_page', __name__,5- template_folder='templates')6-7-@simple_page.route('/', defaults={'page': 'index'})8-@simple_page.route('/<page>')9-def show(page):10- try:11- return render_template('pages/%s.html' % page)12- except TemplateNotFound:13- abort(404)deleted:examples/blueprintexample/blueprintexample.py-19 removed
1-# -*- coding: utf-8 -*-2-"""3-Blueprint Example4-~~~~~~~~~~~~~~~~~5-6-:copyright: © 2010 by the Pallets team.7-:license: BSD, see LICENSE for more details.8-"""9-10-from flask import Flask11-from simple_page.simple_page import simple_page12-13-app = Flask(__name__)14-app.register_blueprint(simple_page)15-# Blueprint can be registered many times16-app.register_blueprint(simple_page, url_prefix='/pages')17-18-if __name__=='__main__':19- app.run()deleted:examples/blueprintexample/test_blueprintexample.py-35 removed
1-# -*- coding: utf-8 -*-2-"""3-Blueprint Example Tests4-~~~~~~~~~~~~~~~~~~~~~~~5-6-:copyright: © 2010 by the Pallets team.7-:license: BSD, see LICENSE for more details.8-"""9-10-import pytest11-12-import blueprintexample13-14-15-@pytest.fixture16-def client():17- return blueprintexample.app.test_client()18-19-20-def test_urls(client):21- r = client.get('/')22- assert r.status_code == 20023-24- r = client.get('/hello')25- assert r.status_code == 20026-27- r = client.get('/world')28- assert r.status_code == 20029-30- # second blueprint instance31- r = client.get('/pages/hello')32- assert r.status_code == 20033-34- r = client.get('/pages/world')35- assert r.status_code == 200deleted:examples/flaskr/flaskr/blueprints/__init__.py
deleted:examples/flaskr/flaskr/blueprints/flaskr.py-85 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: © 2010 by the Pallets team.10- :license: BSD, see LICENSE for more details.11-"""12-13-from sqlite3 import dbapi2 as sqlite314-from flask import Blueprint, request, session, g, redirect, url_for, abort, \15- render_template, flash, current_app16-17-18-# create our blueprint :)19-bp = Blueprint('flaskr', __name__)20-21-22-def connect_db():23- """Connects to the specific database."""24- rv = sqlite3.connect(current_app.config['DATABASE'])25- rv.row_factory = sqlite3.Row26- return rv27-28-29-def init_db():30- """Initializes the database."""31- db = get_db()32- with current_app.open_resource('schema.sql', mode='r') as f:33- db.cursor().executescript(f.read())34- db.commit()35-36-37-def get_db():38- """Opens a new database connection if there is none yet for the39- current application context.40- """41- if not hasattr(g, 'sqlite_db'):42- g.sqlite_db = connect_db()43- return g.sqlite_db44-45-46-@bp.route('/')47-def show_entries():48- db = get_db()49- cur = db.execute('select title, text from entries order by id desc')50- entries = cur.fetchall()51- return render_template('show_entries.html', entries=entries)52-53-54-@bp.route('/add', methods=['POST'])55-def add_entry():56- if not session.get('logged_in'):57- abort(401)58- db = get_db()59- db.execute('insert into entries (title, text) values (?, ?)',60- [request.form['title'], request.form['text']])61- db.commit()62- flash('New entry was successfully posted')63- return redirect(url_for('flaskr.show_entries'))64-65-66-@bp.route('/login', methods=['GET', 'POST'])67-def login():68- error = None69- if request.method == 'POST':70- if request.form['username'] != current_app.config['USERNAME']:71- error = 'Invalid username'72- elif request.form['password'] != current_app.config['PASSWORD']:73- error = 'Invalid password'74- else:75- session['logged_in'] = True76- flash('You were logged in')77- return redirect(url_for('flaskr.show_entries'))78- return render_template('login.html', error=error)79-80-81-@bp.route('/logout')82-def logout():83- session.pop('logged_in', None)84- flash('You were logged out')85- return redirect(url_for('flaskr.show_entries'))deleted:examples/flaskr/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/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('flaskr.login') }}">log in</a>9- {% else %}10- <a href="{{ url_for('flaskr.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/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('flaskr.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/flaskr/templates/show_entries.html-21 removed
1-{% extends "layout.html" %}2-{% block body %}3- {% if session.logged_in %}4- <form action="{{ url_for('flaskr.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 %}deleted:examples/flaskr/flaskr/__init__.py
deleted:examples/flaskr/flaskr/factory.py-64 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: © 2010 by the Pallets team.10- :license: BSD, see LICENSE for more details.11-"""12-13-import os14-from flask import Flask, g15-from werkzeug.utils import find_modules, import_string16-from flaskr.blueprints.flaskr import init_db17-18-19-def create_app(config=None):20- app = Flask('flaskr')21-22- app.config.update(dict(23- DATABASE=os.path.join(app.root_path, 'flaskr.db'),24- DEBUG=True,25- SECRET_KEY=b'_5#y2L"F4Q8z\n\xec]/',26- USERNAME='admin',27- PASSWORD='default'28- ))29- app.config.update(config or {})30- app.config.from_envvar('FLASKR_SETTINGS', silent=True)31-32- register_blueprints(app)33- register_cli(app)34- register_teardowns(app)35-36- return app37-38-39-def register_blueprints(app):40- """Register all blueprint modules41-42- Reference: Armin Ronacher, "Flask for Fun and for Profit" PyBay 2016.43- """44- for name in find_modules('flaskr.blueprints'):45- mod = import_string(name)46- if hasattr(mod, 'bp'):47- app.register_blueprint(mod.bp)48- return None49-50-51-def register_cli(app):52- @app.cli.command('initdb')53- def initdb_command():54- """Creates the database tables."""55- init_db()56- print('Initialized the database.')57-58-59-def register_teardowns(app):60- @app.teardown_appcontext61- def close_db(error):62- """Closes the database again at the end of the request."""63- if hasattr(g, 'sqlite_db'):64- g.sqlite_db.close()deleted:examples/flaskr/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-);deleted:examples/flaskr/tests/test_flaskr.py-83 removed
1-# -*- coding: utf-8 -*-2-"""3- Flaskr Tests4- ~~~~~~~~~~~~5-6- Tests the Flaskr application.7-8- :copyright: © 2010 by the Pallets team.9- :license: BSD, see LICENSE for more details.10-"""11-12-import os13-import tempfile14-import pytest15-from flaskr.factory import create_app16-from flaskr.blueprints.flaskr import init_db17-18-19-@pytest.fixture20-def app():21- db_fd, db_path = tempfile.mkstemp()22- config = {23- 'DATABASE': db_path,24- 'TESTING': True,25- }26- app = create_app(config=config)27-28- with app.app_context():29- init_db()30- yield app31-32- os.close(db_fd)33- os.unlink(db_path)34-35-36-@pytest.fixture37-def client(app):38- return app.test_client()39-40-41-def login(client, username, password):42- return client.post('/login', data=dict(43- username=username,44- password=password45- ), follow_redirects=True)46-47-48-def logout(client):49- return client.get('/logout', follow_redirects=True)50-51-52-def test_empty_db(client):53- """Start with a blank database."""54- rv = client.get('/')55- assert b'No entries here so far' in rv.data56-57-58-def test_login_logout(client, app):59- """Make sure login and logout works"""60- rv = login(client, app.config['USERNAME'],61- app.config['PASSWORD'])62- assert b'You were logged in' in rv.data63- rv = logout(client)64- assert b'You were logged out' in rv.data65- rv = login(client,app.config['USERNAME'] + 'x',66- app.config['PASSWORD'])67- assert b'Invalid username' in rv.data68- rv = login(client, app.config['USERNAME'],69- app.config['PASSWORD'] + 'x')70- assert b'Invalid password' in rv.data71-72-73-def test_messages(client, app):74- """Test that messages work"""75- login(client, app.config['USERNAME'],76- app.config['PASSWORD'])77- rv = client.post('/add', data=dict(78- title='<Hello>',79- text='<strong>HTML</strong> allowed here'80- ), follow_redirects=True)81- assert b'No entries here so far' not in rv.data82- assert b'<Hello>' in rv.data83- assert b'<strong>HTML</strong> allowed here' in rv.datadeleted:examples/flaskr/.gitignore-2 removed
1-flaskr.db2-.eggs/deleted:examples/flaskr/MANIFEST.in-3 removed
1-graft flaskr/templates2-graft flaskr/static3-include flaskr/schema.sqldeleted:examples/flaskr/README-40 removed
1- / Flaskr /2-3- a minimal blog application4-5-6- ~ What is Flaskr?7-8- A sqlite powered thumble blog application9-10- ~ How do I use it?11-12- 1. edit the configuration in the factory.py file or13- export a FLASKR_SETTINGS environment variable14- pointing to a configuration file or pass in a15- dictionary with config values using the create_app16- function.17-18- 2. install the app from the root of the project directory19-20- pip install --editable .21-22- 3. instruct flask to use the right application23-24- export FLASK_APP="flaskr.factory:create_app()"25-26- 4. initialize the database with this command:27-28- flask initdb29-30- 5. now you can run flaskr:31-32- flask run33-34- the application will greet you on35- http://localhost:5000/36-37- ~ Is it tested?38-39- You betcha. Run `python setup.py test` to see40- the tests pass.deleted:examples/flaskr/setup.cfg-2 removed
1-[aliases]2-test=pytestdeleted:examples/flaskr/setup.py-27 removed
1-# -*- coding: utf-8 -*-2-"""3- Flaskr Tests4- ~~~~~~~~~~~~5-6- Tests the Flaskr application.7-8- :copyright: © 2010 by the Pallets team.9- :license: BSD, see LICENSE for more details.10-"""11-12-from setuptools import setup, find_packages13-14-setup(15- name='flaskr',16- packages=find_packages(),17- include_package_data=True,18- install_requires=[19- 'flask',20- ],21- setup_requires=[22- 'pytest-runner',23- ],24- tests_require=[25- 'pytest',26- ],27-)deleted:examples/jqueryexample/templates/index.html-33 removed
1-{% extends "layout.html" %}2-{% block body %}3-<script type="text/javascript">4- $(function() {5- var submit_form = function(e) {6- $.getJSON($SCRIPT_ROOT + '/_add_numbers', {7- a: $('input[name="a"]').val(),8- b: $('input[name="b"]').val()9- }, function(data) {10- $('#result').text(data.result);11- $('input[name=a]').focus().select();12- });13- return false;14- };15-16- $('a#calculate').bind('click', submit_form);17-18- $('input[type=text]').bind('keydown', function(e) {19- if (e.keyCode == 13) {20- submit_form(e);21- }22- });23-24- $('input[name=a]').focus();25- });26-</script>27-<h1>jQuery Example</h1>28-<p>29- <input type="text" size="5" name="a"> +30- <input type="text" size="5" name="b"> =31- <span id="result">?</span>32-<p><a href=# id="calculate">calculate server side</a>33-{% endblock %}deleted:examples/jqueryexample/templates/layout.html-8 removed
1-<!doctype html>2-<title>jQuery Example</title>3-<script type="text/javascript"4- src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>5-<script type="text/javascript">6- var $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};7-</script>8-{% block body %}{% endblock %}deleted:examples/jqueryexample/jqueryexample.py-29 removed
1-# -*- coding: utf-8 -*-2-"""3- jQuery Example4- ~~~~~~~~~~~~~~5-6- A simple application that shows how Flask and jQuery get along.7-8- :copyright: © 2010 by the Pallets team.9- :license: BSD, see LICENSE for more details.10-"""11-12-from flask import Flask, jsonify, render_template, request13-app = Flask(__name__)14-15-16-@app.route('/_add_numbers')17-def add_numbers():18- """Add two numbers server side, ridiculous but well..."""19- a = request.args.get('a', 0, type=int)20- b = request.args.get('b', 0, type=int)21- return jsonify(result=a + b)22-23-24-@app.route('/')25-def index():26- return render_template('index.html')27-28-if __name__ == '__main__':29- app.run()deleted:examples/minitwit/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/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/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/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/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 %}deleted:examples/minitwit/minitwit/__init__.py-1 removed
1-from .minitwit import appdeleted:examples/minitwit/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: © 2010 by the Pallets team.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 = b'_5#y2L"F4Q8z\n\xec]/'26-27-# create our little application :)28-app = Flask('minitwit')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_urldeleted:examples/minitwit/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-);deleted:examples/minitwit/tests/test_minitwit.py-150 removed
1-# -*- coding: utf-8 -*-2-"""3- MiniTwit Tests4- ~~~~~~~~~~~~~~5-6- Tests the MiniTwit application.7-8- :copyright: © 2010 by the Pallets team.9- :license: BSD, see LICENSE for more details.10-"""11-12-import os13-import tempfile14-import pytest15-from minitwit import minitwit16-17-18-@pytest.fixture19-def client():20- db_fd, minitwit.app.config['DATABASE'] = tempfile.mkstemp()21- client = minitwit.app.test_client()22- with minitwit.app.app_context():23- minitwit.init_db()24-25- yield client26-27- os.close(db_fd)28- os.unlink(minitwit.app.config['DATABASE'])29-30-31-def register(client, username, password, password2=None, email=None):32- """Helper function to register a user"""33- if password2 is None:34- password2 = password35- if email is None:36- email = username + '@example.com'37- return client.post('/register', data={38- 'username': username,39- 'password': password,40- 'password2': password2,41- 'email': email,42- }, follow_redirects=True)43-44-45-def login(client, username, password):46- """Helper function to login"""47- return client.post('/login', data={48- 'username': username,49- 'password': password50- }, follow_redirects=True)51-52-53-def register_and_login(client, username, password):54- """Registers and logs in in one go"""55- register(client, username, password)56- return login(client, username, password)57-58-59-def logout(client):60- """Helper function to logout"""61- return client.get('/logout', follow_redirects=True)62-63-64-def add_message(client, text):65- """Records a message"""66- rv = client.post('/add_message', data={'text': text},67- follow_redirects=True)68- if text:69- assert b'Your message was recorded' in rv.data70- return rv71-72-73-def test_register(client):74- """Make sure registering works"""75- rv = register(client, 'user1', 'default')76- assert b'You were successfully registered ' \77- b'and can login now' in rv.data78- rv = register(client, 'user1', 'default')79- assert b'The username is already taken' in rv.data80- rv = register(client, '', 'default')81- assert b'You have to enter a username' in rv.data82- rv = register(client, 'meh', '')83- assert b'You have to enter a password' in rv.data84- rv = register(client, 'meh', 'x', 'y')85- assert b'The two passwords do not match' in rv.data86- rv = register(client, 'meh', 'foo', email='broken')87- assert b'You have to enter a valid email address' in rv.data88-89-90-def test_login_logout(client):91- """Make sure logging in and logging out works"""92- rv = register_and_login(client, 'user1', 'default')93- assert b'You were logged in' in rv.data94- rv = logout(client)95- assert b'You were logged out' in rv.data96- rv = login(client, 'user1', 'wrongpassword')97- assert b'Invalid password' in rv.data98- rv = login(client, 'user2', 'wrongpassword')99- assert b'Invalid username' in rv.data100-101-102-def test_message_recording(client):103- """Check if adding messages works"""104- register_and_login(client, 'foo', 'default')105- add_message(client, 'test message 1')106- add_message(client, '<test message 2>')107- rv = client.get('/')108- assert b'test message 1' in rv.data109- assert b'<test message 2>' in rv.data110-111-112-def test_timelines(client):113- """Make sure that timelines work"""114- register_and_login(client, 'foo', 'default')115- add_message(client, 'the message by foo')116- logout(client)117- register_and_login(client, 'bar', 'default')118- add_message(client, 'the message by bar')119- rv = client.get('/public')120- assert b'the message by foo' in rv.data121- assert b'the message by bar' in rv.data122-123- # bar's timeline should just show bar's message124- rv = client.get('/')125- assert b'the message by foo' not in rv.data126- assert b'the message by bar' in rv.data127-128- # now let's follow foo129- rv = client.get('/foo/follow', follow_redirects=True)130- assert b'You are now following "foo"' in rv.data131-132- # we should now see foo's message133- rv = client.get('/')134- assert b'the message by foo' in rv.data135- assert b'the message by bar' in rv.data136-137- # but on the user's page we only want the user's message138- rv = client.get('/bar')139- assert b'the message by foo' not in rv.data140- assert b'the message by bar' in rv.data141- rv = client.get('/foo')142- assert b'the message by foo' in rv.data143- assert b'the message by bar' not in rv.data144-145- # now unfollow and check if that worked146- rv = client.get('/foo/unfollow', follow_redirects=True)147- assert b'You are no longer following "foo"' in rv.data148- rv = client.get('/')149- assert b'the message by foo' not in rv.data150- assert b'the message by bar' in rv.datadeleted:examples/minitwit/.gitignore-2 removed
1-minitwit.db2-.eggs/deleted:examples/minitwit/MANIFEST.in-3 removed
1-graft minitwit/templates2-graft minitwit/static3-include minitwit/schema.sqldeleted:examples/minitwit/README-39 removed
1-2- / MiniTwit /3-4- because writing todo lists is not fun5-6-7- ~ What is MiniTwit?8-9- A SQLite and Flask powered twitter clone10-11- ~ How do I use it?12-13- 1. edit the configuration in the minitwit.py file or14- export an MINITWIT_SETTINGS environment variable15- pointing to a configuration file.16-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-25- 4. fire up a shell and run this:26-27- flask initdb28-29- 5. now you can run minitwit:30-31- flask run32-33- the application will greet you on34- http://localhost:5000/35-36- ~ Is it tested?37-38- You betcha. Run the `python setup.py test` file to39- see the tests pass.deleted:examples/minitwit/setup.cfg-2 removed
1-[aliases]2-test=pytestdeleted:examples/minitwit/setup.py-16 removed
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/patterns/largerapp/tests/test_largerapp.py-21 removed
1-# -*- coding: utf-8 -*-2-"""3-Larger App Tests4-~~~~~~~~~~~~~~~~5-6-:copyright: © 2010 by the Pallets team.7-:license: BSD, see LICENSE for more details.8-"""9-10-from yourapplication import app11-import pytest12-13-@pytest.fixture14-def client():15- app.config['TESTING'] = True16- client = app.test_client()17- return client18-19-def test_index(client):20- rv = client.get('/')21- assert b"Hello World!" in rv.datadeleted:examples/patterns/largerapp/yourapplication/static/style.css
deleted:examples/patterns/largerapp/yourapplication/templates/index.html
deleted:examples/patterns/largerapp/yourapplication/templates/layout.html
deleted:examples/patterns/largerapp/yourapplication/templates/login.html
deleted:examples/patterns/largerapp/yourapplication/__init__.py-13 removed
1-# -*- coding: utf-8 -*-2-"""3-yourapplication4-~~~~~~~~~~~~~~~5-6-:copyright: © 2010 by the Pallets team.7-:license: BSD, see LICENSE for more details.8-"""9-10-from flask import Flask11-app = Flask('yourapplication')12-13-import yourapplication.viewsdeleted:examples/patterns/largerapp/yourapplication/views.py-14 removed
1-# -*- coding: utf-8 -*-2-"""3-yourapplication.views4-~~~~~~~~~~~~~~~~~~~~~5-6-:copyright: © 2010 by the Pallets team.7-:license: BSD, see LICENSE for more details.8-"""9-10-from yourapplication import app11-12-@app.route('/')13-def index():14- return 'Hello World!'deleted:examples/patterns/largerapp/setup.py-10 removed
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-)added:examples/tutorial/flaskr/static/style.css+134 added
1+html {2+ font-family: sans-serif;3+ background: #eee;4+ padding: 1rem;5+}6+7+body {8+ max-width: 960px;9+ margin: 0 auto;10+ background: white;11+}12+13+h1, h2, h3, h4, h5, h6 {14+ font-family: serif;15+ color: #377ba8;16+ margin: 1rem 0;17+}18+19+a {20+ color: #377ba8;21+}22+23+hr {24+ border: none;25+ border-top: 1px solid lightgray;26+}27+28+nav {29+ background: lightgray;30+ display: flex;31+ align-items: center;32+ padding: 0 0.5rem;33+}34+35+nav h1 {36+ flex: auto;37+ margin: 0;38+}39+40+nav h1 a {41+ text-decoration: none;42+ padding: 0.25rem 0.5rem;43+}44+45+nav ul {46+ display: flex;47+ list-style: none;48+ margin: 0;49+ padding: 0;50+}51+52+nav ul li a, nav ul li span, header .action {53+ display: block;54+ padding: 0.5rem;55+}56+57+.content {58+ padding: 0 1rem 1rem;59+}60+61+.content > header {62+ border-bottom: 1px solid lightgray;63+ display: flex;64+ align-items: flex-end;65+}66+67+.content > header h1 {68+ flex: auto;69+ margin: 1rem 0 0.25rem 0;70+}71+72+.flash {73+ margin: 1em 0;74+ padding: 1em;75+ background: #cae6f6;76+ border: 1px solid #377ba8;77+}78+79+.post > header {80+ display: flex;81+ align-items: flex-end;82+ font-size: 0.85em;83+}84+85+.post > header > div:first-of-type {86+ flex: auto;87+}88+89+.post > header h1 {90+ font-size: 1.5em;91+ margin-bottom: 0;92+}93+94+.post .about {95+ color: slategray;96+ font-style: italic;97+}98+99+.post .body {100+ white-space: pre-line;101+}102+103+.content:last-child {104+ margin-bottom: 0;105+}106+107+.content form {108+ margin: 1em 0;109+ display: flex;110+ flex-direction: column;111+}112+113+.content label {114+ font-weight: bold;115+ margin-bottom: 0.5em;116+}117+118+.content input, .content textarea {119+ margin-bottom: 1em;120+}121+122+.content textarea {123+ min-height: 12em;124+ resize: vertical;125+}126+127+input.danger {128+ color: #cc2f2e;129+}130+131+input[type=submit] {132+ align-self: start;133+ min-width: 10em;134+}added:examples/tutorial/flaskr/templates/auth/login.html+15 added
1+{% extends 'base.html' %}2+3+{% block header %}4+ <h1>{% block title %}Log In{% endblock %}</h1>5+{% endblock %}6+7+{% block content %}8+ <form method="post">9+ <label for="username">Username</label>10+ <input name="username" id="username" required>11+ <label for="password">Password</label>12+ <input type="password" name="password" id="password" required>13+ <input type="submit" value="Log In">14+ </form>15+{% endblock %}added:examples/tutorial/flaskr/templates/auth/register.html+15 added
1+{% extends 'base.html' %}2+3+{% block header %}4+ <h1>{% block title %}Register{% endblock %}</h1>5+{% endblock %}6+7+{% block content %}8+ <form method="post">9+ <label for="username">Username</label>10+ <input name="username" id="username" required>11+ <label for="password">Password</label>12+ <input type="password" name="password" id="password" required>13+ <input type="submit" value="Register">14+ </form>15+{% endblock %}added:examples/tutorial/flaskr/templates/blog/create.html+15 added
1+{% extends 'base.html' %}2+3+{% block header %}4+ <h1>{% block title %}New Post{% endblock %}</h1>5+{% endblock %}6+7+{% block content %}8+ <form method="post">9+ <label for="title">Title</label>10+ <input name="title" id="title" value="{{ request.form['title'] }}" required>11+ <label for="body">Body</label>12+ <textarea name="body" id="body">{{ request.form['body'] }}</textarea>13+ <input type="submit" value="Save">14+ </form>15+{% endblock %}added:examples/tutorial/flaskr/templates/blog/index.html+28 added
1+{% extends 'base.html' %}2+3+{% block header %}4+ <h1>{% block title %}Posts{% endblock %}</h1>5+ {% if g.user %}6+ <a class="action" href="{{ url_for('blog.create') }}">New</a>7+ {% endif %}8+{% endblock %}9+10+{% block content %}11+ {% for post in posts %}12+ <article class="post">13+ <header>14+ <div>15+ <h1>{{ post['title'] }}</h1>16+ <div class="about">by {{ post['username'] }} on {{ post['created'].strftime('%Y-%m-%d') }}</div>17+ </div>18+ {% if g.user['id'] == post['author_id'] %}19+ <a class="action" href="{{ url_for('blog.update', id=post['id']) }}">Edit</a>20+ {% endif %}21+ </header>22+ <p class="body">{{ post['body'] }}</p>23+ </article>24+ {% if not loop.last %}25+ <hr>26+ {% endif %}27+ {% endfor %}28+{% endblock %}added:examples/tutorial/flaskr/templates/blog/update.html+19 added
1+{% extends 'base.html' %}2+3+{% block header %}4+ <h1>{% block title %}Edit "{{ post['title'] }}"{% endblock %}</h1>5+{% endblock %}6+7+{% block content %}8+ <form method="post">9+ <label for="title">Title</label>10+ <input name="title" id="title" value="{{ request.form['title'] or post['title'] }}" required>11+ <label for="body">Body</label>12+ <textarea name="body" id="body">{{ request.form['body'] or post['body'] }}</textarea>13+ <input type="submit" value="Save">14+ </form>15+ <hr>16+ <form action="{{ url_for('blog.delete', id=post['id']) }}" method="post">17+ <input class="danger" type="submit" value="Delete" onclick="return confirm('Are you sure?');">18+ </form>19+{% endblock %}added:examples/tutorial/flaskr/templates/base.html+24 added
1+<!doctype html>2+<title>{% block title %}{% endblock %} - Flaskr</title>3+<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">4+<nav>5+ <h1><a href="{{ url_for('index') }}">Flaskr</a></h1>6+ <ul>7+ {% if g.user %}8+ <li><span>{{ g.user['username'] }}</span>9+ <li><a href="{{ url_for('auth.logout') }}">Log Out</a>10+ {% else %}11+ <li><a href="{{ url_for('auth.register') }}">Register</a>12+ <li><a href="{{ url_for('auth.login') }}">Log In</a>13+ {% endif %}14+ </ul>15+</nav>16+<section class="content">17+ <header>18+ {% block header %}{% endblock %}19+ </header>20+ {% for message in get_flashed_messages() %}21+ <div class="flash">{{ message }}</div>22+ {% endfor %}23+ {% block content %}{% endblock %}24+</section>added:examples/tutorial/flaskr/__init__.py+48 added
1+import os2+3+from flask import Flask4+5+6+def create_app(test_config=None):7+ """Create and configure an instance of the Flask application."""8+ app = Flask(__name__, instance_relative_config=True)9+ app.config.from_mapping(10+ # a default secret that should be overridden by instance config11+ SECRET_KEY='dev',12+ # store the database in the instance folder13+ DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),14+ )15+16+ if test_config is None:17+ # load the instance config, if it exists, when not testing18+ app.config.from_pyfile('config.py', silent=True)19+ else:20+ # load the test config if passed in21+ app.config.update(test_config)22+23+ # ensure the instance folder exists24+ try:25+ os.makedirs(app.instance_path)26+ except OSError:27+ pass28+29+ @app.route('/hello')30+ def hello():31+ return 'Hello, World!'32+33+ # register the database commands34+ from flaskr import db35+ db.init_app(app)36+37+ # apply the blueprints to the app38+ from flaskr import auth, blog39+ app.register_blueprint(auth.bp)40+ app.register_blueprint(blog.bp)41+42+ # make url_for('index') == url_for('blog.index')43+ # in another app, you might define a separate main index here with44+ # app.route, while giving the blog blueprint a url_prefix, but for45+ # the tutorial the blog will be the main index46+ app.add_url_rule('/', endpoint='index')47+48+ return appadded:examples/tutorial/flaskr/auth.py+108 added
1+import functools2+3+from flask import (4+ Blueprint, flash, g, redirect, render_template, request, session, url_for5+)6+from werkzeug.security import check_password_hash, generate_password_hash7+8+from flaskr.db import get_db9+10+bp = Blueprint('auth', __name__, url_prefix='/auth')11+12+13+def login_required(view):14+ """View decorator that redirects anonymous users to the login page."""15+ @functools.wraps(view)16+ def wrapped_view(**kwargs):17+ if g.user is None:18+ return redirect(url_for('auth.login'))19+20+ return view(**kwargs)21+22+ return wrapped_view23+24+25+@bp.before_app_request26+def load_logged_in_user():27+ """If a user id is stored in the session, load the user object from28+ the database into ``g.user``."""29+ user_id = session.get('user_id')30+31+ if user_id is None:32+ g.user = None33+ else:34+ g.user = get_db().execute(35+ 'SELECT * FROM user WHERE id = ?', (user_id,)36+ ).fetchone()37+38+39+@bp.route('/register', methods=('GET', 'POST'))40+def register():41+ """Register a new user.42+43+ Validates that the username is not already taken. Hashes the44+ password for security.45+ """46+ if request.method == 'POST':47+ username = request.form['username']48+ password = request.form['password']49+ db = get_db()50+ error = None51+52+ if not username:53+ error = 'Username is required.'54+ elif not password:55+ error = 'Password is required.'56+ elif db.execute(57+ 'SELECT id FROM user WHERE username = ?', (username,)58+ ).fetchone() is not None:59+ error = 'User {} is already registered.'.format(username)60+61+ if error is None:62+ # the name is available, store it in the database and go to63+ # the login page64+ db.execute(65+ 'INSERT INTO user (username, password) VALUES (?, ?)',66+ (username, generate_password_hash(password))67+ )68+ db.commit()69+ return redirect(url_for('auth.login'))70+71+ flash(error)72+73+ return render_template('auth/register.html')74+75+76+@bp.route('/login', methods=('GET', 'POST'))77+def login():78+ """Log in a registered user by adding the user id to the session."""79+ if request.method == 'POST':80+ username = request.form['username']81+ password = request.form['password']82+ db = get_db()83+ error = None84+ user = db.execute(85+ 'SELECT * FROM user WHERE username = ?', (username,)86+ ).fetchone()87+88+ if user is None:89+ error = 'Incorrect username.'90+ elif not check_password_hash(user['password'], password):91+ error = 'Incorrect password.'92+93+ if error is None:94+ # store the user id in a new session and return to the index95+ session.clear()96+ session['user_id'] = user['id']97+ return redirect(url_for('index'))98+99+ flash(error)100+101+ return render_template('auth/login.html')102+103+104+@bp.route('/logout')105+def logout():106+ """Clear the current session, including the stored user id."""107+ session.clear()108+ return redirect(url_for('index'))added:examples/tutorial/flaskr/blog.py+119 added
1+from flask import (2+ Blueprint, flash, g, redirect, render_template, request, url_for3+)4+from werkzeug.exceptions import abort5+6+from flaskr.auth import login_required7+from flaskr.db import get_db8+9+bp = Blueprint('blog', __name__)10+11+12+@bp.route('/')13+def index():14+ """Show all the posts, most recent first."""15+ db = get_db()16+ posts = db.execute(17+ 'SELECT p.id, title, body, created, author_id, username'18+ ' FROM post p JOIN user u ON p.author_id = u.id'19+ ' ORDER BY created DESC'20+ ).fetchall()21+ return render_template('blog/index.html', posts=posts)22+23+24+def get_post(id, check_author=True):25+ """Get a post and its author by id.26+27+ Checks that the id exists and optionally that the current user is28+ the author.29+30+ :param id: id of post to get31+ :param check_author: require the current user to be the author32+ :return: the post with author information33+ :raise 404: if a post with the given id doesn't exist34+ :raise 403: if the current user isn't the author35+ """36+ post = get_db().execute(37+ 'SELECT p.id, title, body, created, author_id, username'38+ ' FROM post p JOIN user u ON p.author_id = u.id'39+ ' WHERE p.id = ?',40+ (id,)41+ ).fetchone()42+43+ if post is None:44+ abort(404, "Post id {0} doesn't exist.".format(id))45+46+ if check_author and post['author_id'] != g.user['id']:47+ abort(403)48+49+ return post50+51+52+@bp.route('/create', methods=('GET', 'POST'))53+@login_required54+def create():55+ """Create a new post for the current user."""56+ if request.method == 'POST':57+ title = request.form['title']58+ body = request.form['body']59+ error = None60+61+ if not title:62+ error = 'Title is required.'63+64+ if error is not None:65+ flash(error)66+ else:67+ db = get_db()68+ db.execute(69+ 'INSERT INTO post (title, body, author_id)'70+ ' VALUES (?, ?, ?)',71+ (title, body, g.user['id'])72+ )73+ db.commit()74+ return redirect(url_for('blog.index'))75+76+ return render_template('blog/create.html')77+78+79+@bp.route('/<int:id>/update', methods=('GET', 'POST'))80+@login_required81+def update(id):82+ """Update a post if the current user is the author."""83+ post = get_post(id)84+85+ if request.method == 'POST':86+ title = request.form['title']87+ body = request.form['body']88+ error = None89+90+ if not title:91+ error = 'Title is required.'92+93+ if error is not None:94+ flash(error)95+ else:96+ db = get_db()97+ db.execute(98+ 'UPDATE post SET title = ?, body = ? WHERE id = ?',99+ (title, body, id)100+ )101+ db.commit()102+ return redirect(url_for('blog.index'))103+104+ return render_template('blog/update.html', post=post)105+106+107+@bp.route('/<int:id>/delete', methods=('POST',))108+@login_required109+def delete(id):110+ """Delete a post.111+112+ Ensures that the post exists and that the logged in user is the113+ author of the post.114+ """115+ get_post(id)116+ db = get_db()117+ db.execute('DELETE FROM post WHERE id = ?', (id,))118+ db.commit()119+ return redirect(url_for('blog.index'))added:examples/tutorial/flaskr/db.py+54 added
1+import sqlite32+3+import click4+from flask import current_app, g5+from flask.cli import with_appcontext6+7+8+def get_db():9+ """Connect to the application's configured database. The connection10+ is unique for each request and will be reused if this is called11+ again.12+ """13+ if 'db' not in g:14+ g.db = sqlite3.connect(15+ current_app.config['DATABASE'],16+ detect_types=sqlite3.PARSE_DECLTYPES17+ )18+ g.db.row_factory = sqlite3.Row19+20+ return g.db21+22+23+def close_db(e=None):24+ """If this request connected to the database, close the25+ connection.26+ """27+ db = g.pop('db', None)28+29+ if db is not None:30+ db.close()31+32+33+def init_db():34+ """Clear existing data and create new tables."""35+ db = get_db()36+37+ with current_app.open_resource('schema.sql') as f:38+ db.executescript(f.read().decode('utf8'))39+40+41+@click.command('init-db')42+@with_appcontext43+def init_db_command():44+ """Clear existing data and create new tables."""45+ init_db()46+ click.echo('Initialized the database.')47+48+49+def init_app(app):50+ """Register database functions with the Flask app. This is called by51+ the application factory.52+ """53+ app.teardown_appcontext(close_db)54+ app.cli.add_command(init_db_command)added:examples/tutorial/flaskr/schema.sql+20 added
1+-- Initialize the database.2+-- Drop any existing data and create empty tables.3+4+DROP TABLE IF EXISTS user;5+DROP TABLE IF EXISTS post;6+7+CREATE TABLE user (8+ id INTEGER PRIMARY KEY AUTOINCREMENT,9+ username TEXT UNIQUE NOT NULL,10+ password TEXT NOT NULL11+);12+13+CREATE TABLE post (14+ id INTEGER PRIMARY KEY AUTOINCREMENT,15+ author_id INTEGER NOT NULL,16+ created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,17+ title TEXT NOT NULL,18+ body TEXT NOT NULL,19+ FOREIGN KEY (author_id) REFERENCES user (id)20+);added:examples/tutorial/tests/conftest.py+64 added
1+import os2+import tempfile3+4+import pytest5+from flaskr import create_app6+from flaskr.db import get_db, init_db7+8+# read in SQL for populating test data9+with open(os.path.join(os.path.dirname(__file__), 'data.sql'), 'rb') as f:10+ _data_sql = f.read().decode('utf8')11+12+13+@pytest.fixture14+def app():15+ """Create and configure a new app instance for each test."""16+ # create a temporary file to isolate the database for each test17+ db_fd, db_path = tempfile.mkstemp()18+ # create the app with common test config19+ app = create_app({20+ 'TESTING': True,21+ 'DATABASE': db_path,22+ })23+24+ # create the database and load test data25+ with app.app_context():26+ init_db()27+ get_db().executescript(_data_sql)28+29+ yield app30+31+ # close and remove the temporary database32+ os.close(db_fd)33+ os.unlink(db_path)34+35+36+@pytest.fixture37+def client(app):38+ """A test client for the app."""39+ return app.test_client()40+41+42+@pytest.fixture43+def runner(app):44+ """A test runner for the app's Click commands."""45+ return app.test_cli_runner()46+47+48+class AuthActions(object):49+ def __init__(self, client):50+ self._client = client51+52+ def login(self, username='test', password='test'):53+ return self._client.post(54+ '/auth/login',55+ data={'username': username, 'password': password}56+ )57+58+ def logout(self):59+ return self._client.get('/auth/logout')60+61+62+@pytest.fixture63+def auth(client):64+ return AuthActions(client)added:examples/tutorial/tests/data.sql+8 added
1+INSERT INTO user (username, password)2+VALUES3+ ('test', 'pbkdf2:sha256:50000$TCI4GzcX$0de171a4f4dac32e3364c7ddc7c14f3e2fa61f2d17574483f7ffbb431b4acb2f'),4+ ('other', 'pbkdf2:sha256:50000$kJPKsz6N$d2d4784f1b030a9761f5ccaeeaca413f27f2ecb76d6168407af962ddce849f79');5+6+INSERT INTO post (title, body, author_id, created)7+VALUES8+ ('test title', 'test' || x'0a' || 'body', 1, '2018-01-01 00:00:00');added:examples/tutorial/tests/test_auth.py+66 added
1+import pytest2+from flask import g, session3+from flaskr.db import get_db4+5+6+def test_register(client, app):7+ # test that viewing the page renders without template errors8+ assert client.get('/auth/register').status_code == 2009+10+ # test that successful registration redirects to the login page11+ response = client.post(12+ '/auth/register', data={'username': 'a', 'password': 'a'}13+ )14+ assert 'http://localhost/auth/login' == response.headers['Location']15+16+ # test that the user was inserted into the database17+ with app.app_context():18+ assert get_db().execute(19+ "select * from user where username = 'a'",20+ ).fetchone() is not None21+22+23+@pytest.mark.parametrize(('username', 'password', 'message'), (24+ ('', '', b'Username is required.'),25+ ('a', '', b'Password is required.'),26+ ('test', 'test', b'already registered'),27+))28+def test_register_validate_input(client, username, password, message):29+ response = client.post(30+ '/auth/register',31+ data={'username': username, 'password': password}32+ )33+ assert message in response.data34+35+36+def test_login(client, auth):37+ # test that viewing the page renders without template errors38+ assert client.get('/auth/login').status_code == 20039+40+ # test that successful login redirects to the index page41+ response = auth.login()42+ assert response.headers['Location'] == 'http://localhost/'43+44+ # login request set the user_id in the session45+ # check that the user is loaded from the session46+ with client:47+ client.get('/')48+ assert session['user_id'] == 149+ assert g.user['username'] == 'test'50+51+52+@pytest.mark.parametrize(('username', 'password', 'message'), (53+ ('a', 'test', b'Incorrect username.'),54+ ('test', 'a', b'Incorrect password.'),55+))56+def test_login_validate_input(auth, username, password, message):57+ response = auth.login(username, password)58+ assert message in response.data59+60+61+def test_logout(client, auth):62+ auth.login()63+64+ with client:65+ auth.logout()66+ assert 'user_id' not in sessionadded:examples/tutorial/tests/test_blog.py+92 added
1+import pytest2+from flaskr.db import get_db3+4+5+def test_index(client, auth):6+ response = client.get('/')7+ assert b"Log In" in response.data8+ assert b"Register" in response.data9+10+ auth.login()11+ response = client.get('/')12+ assert b'test title' in response.data13+ assert b'by test on 2018-01-01' in response.data14+ assert b'test\nbody' in response.data15+ assert b'href="/1/update"' in response.data16+17+18+@pytest.mark.parametrize('path', (19+ '/create',20+ '/1/update',21+ '/1/delete',22+))23+def test_login_required(client, path):24+ response = client.post(path)25+ assert response.headers['Location'] == 'http://localhost/auth/login'26+27+28+def test_author_required(app, client, auth):29+ # change the post author to another user30+ with app.app_context():31+ db = get_db()32+ db.execute('UPDATE post SET author_id = 2 WHERE id = 1')33+ db.commit()34+35+ auth.login()36+ # current user can't modify other user's post37+ assert client.post('/1/update').status_code == 40338+ assert client.post('/1/delete').status_code == 40339+ # current user doesn't see edit link40+ assert b'href="/1/update"' not in client.get('/').data41+42+43+@pytest.mark.parametrize('path', (44+ '/2/update',45+ '/2/delete',46+))47+def test_exists_required(client, auth, path):48+ auth.login()49+ assert client.post(path).status_code == 40450+51+52+def test_create(client, auth, app):53+ auth.login()54+ assert client.get('/create').status_code == 20055+ client.post('/create', data={'title': 'created', 'body': ''})56+57+ with app.app_context():58+ db = get_db()59+ count = db.execute('SELECT COUNT(id) FROM post').fetchone()[0]60+ assert count == 261+62+63+def test_update(client, auth, app):64+ auth.login()65+ assert client.get('/1/update').status_code == 20066+ client.post('/1/update', data={'title': 'updated', 'body': ''})67+68+ with app.app_context():69+ db = get_db()70+ post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()71+ assert post['title'] == 'updated'72+73+74+@pytest.mark.parametrize('path', (75+ '/create',76+ '/1/update',77+))78+def test_create_update_validate(client, auth, path):79+ auth.login()80+ response = client.post(path, data={'title': '', 'body': ''})81+ assert b'Title is required.' in response.data82+83+84+def test_delete(client, auth, app):85+ auth.login()86+ response = client.post('/1/delete')87+ assert response.headers['Location'] == 'http://localhost/'88+89+ with app.app_context():90+ db = get_db()91+ post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()92+ assert post is Noneadded:examples/tutorial/tests/test_db.py+28 added
1+import sqlite32+3+import pytest4+from flaskr.db import get_db5+6+7+def test_get_close_db(app):8+ with app.app_context():9+ db = get_db()10+ assert db is get_db()11+12+ with pytest.raises(sqlite3.ProgrammingError) as e:13+ db.execute('SELECT 1')14+15+ assert 'closed' in str(e)16+17+18+def test_init_db_command(runner, monkeypatch):19+ class Recorder(object):20+ called = False21+22+ def fake_init_db():23+ Recorder.called = True24+25+ monkeypatch.setattr('flaskr.db.init_db', fake_init_db)26+ result = runner.invoke(args=['init-db'])27+ assert 'Initialized' in result.output28+ assert Recorder.calledadded:examples/tutorial/tests/test_factory.py+12 added
1+from flaskr import create_app2+3+4+def test_config():5+ """Test create_app without passing test config."""6+ assert not create_app().testing7+ assert create_app({'TESTING': True}).testing8+9+10+def test_hello(client):11+ response = client.get('/hello')12+ assert response.data == b'Hello, World!'added:examples/tutorial/.gitignore+14 added
1+venv/2+*.pyc3+__pycache__/4+instance/5+.cache/6+.pytest_cache/7+.coverage8+htmlcov/9+dist/10+build/11+*.egg-info/12+.idea/13+*.swp14+*~added:examples/tutorial/LICENSE+31 added
1+Copyright © 2010 by the Pallets team.2+3+Some rights reserved.4+5+Redistribution and use in source and binary forms of the software as6+well as documentation, with or without modification, are permitted7+provided that the following conditions are met:8+9+* Redistributions of source code must retain the above copyright notice,10+ this list of conditions and the following disclaimer.11+12+* Redistributions in binary form must reproduce the above copyright13+ notice, this list of conditions and the following disclaimer in the14+ documentation and/or other materials provided with the distribution.15+16+* Neither the name of the copyright holder nor the names of its17+ contributors may be used to endorse or promote products derived from18+ this software without specific prior written permission.19+20+THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE COPYRIGHT HOLDERS AND21+CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,22+BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND23+FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE24+COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,25+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT26+NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF27+USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON28+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT29+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF30+THIS SOFTWARE AND DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF31+SUCH DAMAGE.added:examples/tutorial/MANIFEST.in+6 added
1+include LICENSE2+include flaskr/schema.sql3+graft flaskr/static4+graft flaskr/templates5+graft tests6+global-exclude *.pycadded:examples/tutorial/README.rst+76 added
1+Flaskr2+======3+4+The basic blog app built in the Flask `tutorial`_.5+6+.. _tutorial: http://flask.pocoo.org/docs/tutorial/7+8+9+Install10+-------11+12+**Be sure to use the same version of the code as the version of the docs13+you're reading.** You probably want the latest tagged version, but the14+default Git version is the master branch. ::15+16+ # clone the repository17+ git clone https://github.com/pallets/flask18+ cd flask19+ # checkout the correct version20+ git tag # shows the tagged versions21+ git checkout latest-tag-found-above22+ cd examples/tutorial23+24+Create a virtualenv and activate it::25+26+ python3 -m venv venv27+ . venv/bin/activate28+29+Or on Windows cmd::30+31+ py -3 -m venv venv32+ venv\Scripts\activate.bat33+34+Install Flaskr::35+36+ pip install -e .37+38+Or if you are using the master branch, install Flask from source before39+installing Flaskr::40+41+ pip install -e ../..42+ pip install -e .43+44+45+Run46+---47+48+::49+50+ export FLASK_APP=flaskr51+ export FLASK_ENV=development52+ flask run53+54+Or on Windows cmd::55+56+ set FLASK_APP=flaskr57+ set FLASK_ENV=development58+ flask run59+60+Open http://127.0.0.1:5000 in a browser.61+62+63+Test64+----65+66+::67+68+ pip install pytest69+ pytest70+71+Run with coverage report::72+73+ pip install pytest coverage74+ coverage run -m pytest75+ coverage report76+ coverage html # open htmlcov/index.html in a browseradded:examples/tutorial/setup.cfg+13 added
1+[metadata]2+license_file = LICENSE3+4+[bdist_wheel]5+universal = False6+7+[tool:pytest]8+testpaths = tests9+10+[coverage:run]11+branch = True12+source =13+ flaskradded:examples/tutorial/setup.py+23 added
1+import io2+3+from setuptools import find_packages, setup4+5+with io.open('README.rst', 'rt', encoding='utf8') as f:6+ readme = f.read()7+8+setup(9+ name='flaskr',10+ version='1.0.0',11+ url='http://flask.pocoo.org/docs/tutorial/',12+ license='BSD',13+ maintainer='Pallets team',14+ maintainer_email='contact@palletsprojects.com',15+ description='The basic blog app built in the Flask tutorial.',16+ long_description=readme,17+ packages=find_packages(),18+ include_package_data=True,19+ zip_safe=False,20+ install_requires=[21+ 'flask',22+ ],23+)modified:CONTRIBUTING.rst+1 added-1 removed
73 unmodified lines74 .. _GitHub account: https://github.com/join75 .. _latest version of git: https://git-scm.com/downloads76 .. _username: https://help.github.com/articles/setting-your-username-in-git/77 .. _email: https://help.github.com/articles/setting-your-email-in-git/78-.. _Fork: https://github.com/pallets/flask/pull/2305#fork-destination-box78+.. _Fork: https://github.com/pallets/flask/fork79 .. _Clone: https://help.github.com/articles/fork-a-repo/#step-2-create-a-local-clone-of-your-fork80 81 Start coding82 ~~~~~~~~~~~~98 unmodified linesmodified:tox.ini+1 added-3 removed
29 unmodified lines30 simplejson: simplejson31 32 commands =33 # the examples need to be installed to test successfully34- pip install -e examples/flaskr -q35- pip install -e examples/minitwit -q36- pip install -e examples/patterns/largerapp -q34+ pip install -e examples/tutorial -q35 36 # pytest-cov doesn't seem to play nice with -p37 coverage run -p -m pytest tests examples38 24 unmodified lines