Skip to content
Myr

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

104 files+3311 added−2208 removed

deleted:docs/_static/flaskr.pngbinary

A binary file, deleted.

modified:docs/patterns/jquery.rst+2 added-4 removed
160 unmodified lines
161 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.164165If you don't get the whole picture, download the `sourcecode166for this example167<https://github.com/pallets/flask/tree/master/examples/jqueryexample>`_168from GitHub.165If you don't get the whole picture, download the :gh:`sourcecode166for this example <examples/jqueryexample>`.
modified:docs/patterns/packages.rst+7 added-9 removed
15 unmodified lines
16 index.html17 login.html18 ...1920If you find yourself stuck on something, feel free21to take a look at the source code for this example.22You'll find `the full src for this example here`_.20The :ref:`tutorial <tutorial>` is structured this way, see the21:gh:`example code <examples/tutorial>`.2223Simple Packages24---------------25
31 unmodified lines
57 'flask',58 ],59 )6062In order to run the application you need to export an environment variable 63that tells Flask where to find the application instance:: 61In order to run the application you need to export an environment variable62that tells Flask where to find the application instance::6364 export FLASK_APP=yourapplication6567If you are outside of the project directory make sure to provide the exact 66If you are outside of the project directory make sure to provide the exact67path to your application directory. Similarly you can turn on the68development features like this::6970 export FLASK_ENV=development7173In order to install and run the application you need to issue the following 72In order to install and run the application you need to issue the following73commands::7476 pip install -e . 75 pip install -e .76 flask run7778What did we gain from this? Now we can restructure the application a bit79into multiple modules. The only thing you have to remember is the
52 unmodified lines
132 :ref:`becomingbig` section for some inspiration how to deal with that.133134135.. _working-with-modules:137.. _the full src for this example here: https://github.com/pallets/flask/tree/master/examples/patterns/largerapp136137Working with Blueprints138-----------------------139
4 unmodified lines
added:docs/tutorial/blog.rst+336 added
1.. currentmodule:: flask23Blog Blueprint4==============56You'll use the same techniques you learned about when writing the7authentication blueprint to write the blog blueprint. The blog should8list all posts, allow logged in users to create posts, and allow the9author of a post to edit or delete it.1011As you implement each view, keep the development server running. As you12save your changes, try going to the URL in your browser and testing them13out.1415The Blueprint16-------------1718Define the blueprint and register it in the application factory.1920.. code-block:: python21 :caption: ``flaskr/blog.py``2223 from flask import (24 Blueprint, flash, g, redirect, render_template, request, url_for25 )26 from werkzeug.exceptions import abort2728 from flaskr.auth import login_required29 from flaskr.db import get_db3031 bp = Blueprint('blog', __name__)3233Import and register the blueprint from the factory using34:meth:`app.register_blueprint() <Flask.register_blueprint>`. Place the35new code at the end of the factory function before returning the app.3637.. code-block:: python38 :caption: ``flaskr/__init__.py``3940 def create_app():41 app = ...42 # existing code omitted4344 from . import blog45 app.register_blueprint(blog.bp)46 app.add_url_rule('/', endpoint='index')4748 return app495051Unlike the auth blueprint, the blog blueprint does not have a52``url_prefix``. So the ``index`` view will be at ``/``, the ``create``53view at ``/create``, and so on. The blog is the main feature of Flaskr,54so it makes sense that the blog index will be the main index.5556However, 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>`59associates the endpoint name ``'index'`` with the ``/`` url so that60``url_for('index')`` or ``url_for('blog.index')`` will both work,61generating the same ``/`` URL either way.6263In another application you might give the blog blueprint a64``url_prefix`` and define a separate ``index`` view in the application65factory, similar to the ``hello`` view. Then the ``index`` and66``blog.index`` endpoints and URLs would be different.676869Index70-----7172The index will show all of the posts, most recent first. A ``JOIN`` is73used so that the author information from the ``user`` table is74available in the result.7576.. code-block:: python77 :caption: ``flaskr/blog.py``7879 @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)8889.. code-block:: html+jinja90 :caption: ``flaskr/templates/blog/index.html``9192 {% extends 'base.html' %}9394 {% 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 %}100101 {% 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 %}120121When 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 a124special variable available inside `Jinja for loops`_. It's used to125display a line after each post except the last one, to visually separate126them.127128.. _Jinja for loops: http://jinja.pocoo.org/docs/templates/#for129130131Create132------133134The ``create`` view works the same as the auth ``register`` view. Either135the form is displayed, or the posted data is validated and the post is136added to the database or an error is shown.137138The ``login_required`` decorator you wrote earlier is used on the blog139views. A user must be logged in to visit these views, otherwise they140will be redirected to the login page.141142.. code-block:: python143 :caption: ``flaskr/blog.py``144145 @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 = None152153 if not title:154 error = 'Title is required.'155156 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'))167168 return render_template('blog/create.html')169170.. code-block:: html+jinja171 :caption: ``flaskr/templates/blog/create.html``172173 {% extends 'base.html' %}174175 {% block header %}176 <h1>{% block title %}New Post{% endblock %}</h1>177 {% endblock %}178179 {% 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 %}188189190Update191------192193Both the ``update`` and ``delete`` views will need to fetch a ``post``194by ``id`` and check if the author matches the logged in user. To avoid195duplicating code, you can write a function to get the ``post`` and call196it from each view.197198.. code-block:: python199 :caption: ``flaskr/blog.py``200201 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()208209 if post is None:210 abort(404, "Post id {0} doesn't exist.".format(id))211212 if check_author and post['author_id'] != g.user['id']:213 abort(403)214215 return post216217:func:`abort` will raise a special exception that returns an HTTP status218code. It takes an optional message to show with the error, otherwise a219default message is used. ``404`` means "Not Found", and ``403`` means220"Forbidden". (``401`` means "Unauthorized", but you redirect to the221login page instead of returning that status.)222223The ``check_author`` argument is defined so that the function can be224used to get a ``post`` without checking the author. This would be useful225if you wrote a view to show an individual post on a page, where the user226doesn't matter because they're not modifying the post.227228.. code-block:: python229 :caption: ``flaskr/blog.py``230231 @bp.route('/<int:id>/update', methods=('GET', 'POST'))232 @login_required233 def update(id):234 post = get_post(id)235236 if request.method == 'POST':237 title = request.form['title']238 body = request.form['body']239 error = None240241 if not title:242 error = 'Title is required.'243244 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'))255256 return render_template('blog/update.html', post=post)257258Unlike the views you've written so far, the ``update`` function takes259an argument, ``id``. That corresponds to the ``<int:id>`` in the route.260A real URL will look like ``/1/update``. Flask will capture the ``1``,261ensure it's an :class:`int`, and pass it as the ``id`` argument. If you262don't specify ``int:`` and instead do ``<id>``, it will be a string.263To generate a URL to the update page, :func:`url_for` needs to be passed264the ``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.267268The ``create`` and ``update`` views look very similar. The main269difference is that the ``update`` view uses a ``post`` object and an270``UPDATE`` query instead of an ``INSERT``. With some clever refactoring,271you could use one view and template for both actions, but for the272tutorial it's clearer to keep them separate.273274.. code-block:: html+jinja275 :caption: ``flaskr/templates/blog/update.html``276277 {% extends 'base.html' %}278279 {% block header %}280 <h1>{% block title %}Edit "{{ post['title'] }}"{% endblock %}</h1>281 {% endblock %}282283 {% 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 %}297298This template has two forms. The first posts the edited data to the299current page (``/<id>/update``). The other form contains only a button300and specifies an ``action`` attribute that posts to the delete view301instead. The button uses some JavaScript to show a confirmation dialog302before submitting.303304The pattern ``{{ request.form['title'] or post['title'] }}`` is used to305choose what data appears in the form. When the form hasn't been306submitted, the original ``post`` data appears, but if invalid form data307was posted you want to display that so the user can fix the error, so308``request.form`` is used instead. :data:`request` is another variable309that's automatically available in templates.310311312Delete313------314315The delete view doesn't have its own template, the delete button is part316of ``update.html`` and posts to the ``/<id>/delete`` URL. Since there317is no template, it will only handle the ``POST`` method then redirect318to the ``index`` view.319320.. code-block:: python321 :caption: ``flaskr/blog.py``322323 @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'))331332Congratulations, you've now finished writing your application! Take some333time to try out everything in the browser. However, there's still more334to do before the project is complete.335336Continue to :doc:`install`.
deleted:docs/tutorial/css.rst-31 removed
1.. _tutorial-css:23Step 8: Adding Style4====================56Now that everything else works, it's time to add some style to the7application. Just create a stylesheet called :file:`style.css` in the8:file:`static` folder:910.. sourcecode:: css1112 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; }1718 .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; }3031Continue with :ref:`tutorial-testing`.
added:docs/tutorial/database.rst+213 added
1.. currentmodule:: flask23Define and Access the Database4==============================56The application will use a `SQLite`_ database to store users and posts.7Python comes with built-in support for SQLite in the :mod:`sqlite3`8module.910SQLite is convenient because it doesn't require setting up a separate11database server and is built-in to Python. However, if concurrent12requests try to write to the database at the same time, they will slow13down as each write happens sequentially. Small applications won't notice14this. Once you become big, you may want to switch to a different15database.1617The tutorial doesn't go into detail about SQL. If you are not familiar18with it, the SQLite docs describe the `language`_.1920.. _SQLite: https://sqlite.org/about.html21.. _language: https://sqlite.org/lang.html222324Connect to the Database25-----------------------2627The first thing to do when working with a SQLite database (and most28other Python database libraries) is to create a connection to it. Any29queries and operations are performed using the connection, which is30closed after the work is finished.3132In web applications this connection is typically tied to the request. It33is created at some point when handling a request, and closed before the34response is sent.3536.. code-block:: python37 :caption: ``flaskr/db.py``3839 import sqlite34041 import click42 from flask import current_app, g43 from flask.cli import with_appcontext444546 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.Row5354 return g.db555657 def close_db(e=None):58 db = g.pop('db', None)5960 if db is not None:61 db.close()6263:data:`g` is a special object that is unique for each request. It is64used to store data that might be accessed by multiple functions during65the request. The connection is stored and reused instead of creating a66new connection if ``get_db`` is called a second time in the same67request.6869:data:`current_app` is another special object that points to the Flask70application handling the request. Since you used an application factory,71there is no application object when writing the rest of your code.72``get_db`` will be called when the application has been created and is73handling a request, so :data:`current_app` can be used.7475:func:`sqlite3.connect` establishes a connection to the file pointed at76by the ``DATABASE`` configuration key. This file doesn't have to exist77yet, and won't until you initialize the database later.7879:class:`sqlite3.Row` tells the connection to return rows that behave80like dicts. This allows accessing the columns by name.8182``close_db`` checks if a connection was created by checking if ``g.db``83was set. If the connection exists, it is closed. Further down you will84tell your application about the ``close_db`` function in the application85factory so that it is called after each request.868788Create the Tables89-----------------9091In SQLite, data is stored in *tables* and *columns*. These need to be92created before you can store and retrieve data. Flaskr will store users93in the ``user`` table, and posts in the ``post`` table. Create a file94with the SQL commands needed to create empty tables:9596.. code-block:: sql97 :caption: ``flaskr/schema.sql``9899 DROP TABLE IF EXISTS user;100 DROP TABLE IF EXISTS post;101102 CREATE TABLE user (103 id INTEGER PRIMARY KEY AUTOINCREMENT,104 username TEXT UNIQUE NOT NULL,105 password TEXT NOT NULL106 );107108 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 );116117Add the Python functions that will run these SQL commands to the118``db.py`` file:119120.. code-block:: python121 :caption: ``flaskr/db.py``122123 def init_db():124 db = get_db()125126 with current_app.open_resource('schema.sql') as f:127 db.executescript(f.read().decode('utf8'))128129130 @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.')136137:meth:`open_resource() <Flask.open_resource>` opens a file relative to138the ``flaskr`` package, which is useful since you won't necessarily know139where that location is when deploying the application later. ``get_db``140returns a database connection, which is used to execute the commands141read from the file.142143:func:`click.command` defines a command line command called ``init-db``144that calls the ``init_db`` function and shows a success message to the145user. You can read :ref:`cli` to learn more about writing commands.146147148Register with the Application149-----------------------------150151The ``close_db`` and ``init_db_command`` functions need to be registered152with the application instance, otherwise they won't be used by the153application. However, since you're using a factory function, that154instance isn't available when writing the functions. Instead, write a155function that takes an application and does the registration.156157.. code-block:: python158 :caption: ``flaskr/db.py``159160 def init_app(app):161 app.teardown_appcontext(close_db)162 app.cli.add_command(init_db_command)163164:meth:`app.teardown_appcontext() <Flask.teardown_appcontext>` tells165Flask to call that function when cleaning up after returning the166response.167168:meth:`app.cli.add_command() <click.Group.add_command>` adds a new169command that can be called with the ``flask`` command.170171Import and call this function from the factory. Place the new code at172the end of the factory function before returning the app.173174.. code-block:: python175 :caption: ``flaskr/__init__.py``176177 def create_app():178 app = ...179 # existing code omitted180181 from . import db182 db.init_app(app)183184 return app185186187Initialize the Database File188----------------------------189190Now that ``init-db`` has been registered with the app, it can be called191using the ``flask`` command, similar to the ``run`` command from the192previous page.193194.. note::195196 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.202203Run the ``init-db`` command:204205.. code-block:: none206207 flask init-db208 Initialized the database.209210There will now be a ``flaskr.sqlite`` file in the ``instance`` folder in211your project.212213Continue to :doc:`views`.
deleted:docs/tutorial/dbcon.rst-78 removed
1.. _tutorial-dbcon:23Step 4: Database Connections4----------------------------56Let's continue building our code in the ``flaskr.py`` file.7(Scroll to the end of the page for more about project layout.)89You currently have a function for establishing a database connection with10`connect_db`, but by itself, it is not particularly useful. Creating and11closing database connections all the time is very inefficient, so you will12need to keep it around for longer. Because database connections13encapsulate a transaction, you will need to make sure that only one14request at a time uses the connection. An elegant way to do this is by15utilizing the *application context*.1617Flask provides two contexts: the *application context* and the18*request context*. For the time being, all you have to know is that there19are special variables that use these. For instance, the20:data:`~flask.request` variable is the request object associated with21the current request, whereas :data:`~flask.g` is a general purpose22variable associated with the current application context. The tutorial23will cover some more details of this later on.2425For the time being, all you have to know is that you can store information26safely on the :data:`~flask.g` object.2728So when do you put it on there? To do that you can make a helper29function. The first time the function is called, it will create a database30connection for the current context, and successive calls will return the31already established connection::3233 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_db4041Now you know how to connect, but how can you properly disconnect? For42that, Flask provides us with the :meth:`~flask.Flask.teardown_appcontext`43decorator. It's executed every time the application context tears down::4445 @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()5051Functions marked with :meth:`~flask.Flask.teardown_appcontext` are called52every time the app context tears down. What does this mean?53Essentially, the app context is created before the request comes in and is54destroyed (torn down) whenever the request finishes. A teardown can55happen because of two reasons: either everything went well (the error56parameter will be ``None``) or an exception happened, in which case the error57is passed to the teardown function.5859Curious about what these contexts mean? Have a look at the60:ref:`app-context` documentation to learn more.6162Continue to :ref:`tutorial-dbinit`.6364.. hint:: Where do I put this code?6566 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).7172 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.7677.. _example source:78 https://github.com/pallets/flask/tree/master/examples/flaskr/
deleted:docs/tutorial/dbinit.rst-80 removed
1.. _tutorial-dbinit:23Step 5: Creating The Database4=============================56As outlined earlier, Flaskr is a database powered application, and more7precisely, it is an application powered by a relational database system. Such8systems need a schema that tells them how to store that information.9Before starting the server for the first time, it's important to create10that schema.1112Such a schema could be created by piping the ``schema.sql`` file into the13``sqlite3`` command as follows::1415 sqlite3 /tmp/flaskr.db < schema.sql1617However, the downside of this is that it requires the ``sqlite3`` command18to be installed, which is not necessarily the case on every system. This19also requires that you provide the path to the database, which can introduce20errors.2122Instead of the ``sqlite3`` command above, it's a good idea to add a function23to our application that initializes the database for you. To do this, you24can create a function and hook it into a :command:`flask` command that25initializes the database.2627Take a look at the code segment below. A good place to add this function,28and command, is just below the ``connect_db`` function in :file:`flaskr.py`::2930 def init_db():31 db = get_db()3233 with app.open_resource('schema.sql', mode='r') as f:34 db.cursor().executescript(f.read())3536 db.commit()373839 @app.cli.command('initdb')40 def initdb_command():41 """Initializes the database."""4243 init_db()44 print('Initialized the database.')4546The ``app.cli.command()`` decorator registers a new command with the47:command:`flask` script. When the command executes, Flask will automatically48create an application context which is bound to the right application.49Within the function, you can then access :attr:`flask.g` and other things as50you might expect. When the script ends, the application context tears down51and the database connection is released.5253You will want to keep an actual function around that initializes the database,54though, so that we can easily create databases in unit tests later on. (For55more information see :ref:`testing`.)5657The :func:`~flask.Flask.open_resource` method of the application object58is a convenient helper function that will open a resource that the59application provides. This function opens a file from the resource60location (the :file:`flaskr/flaskr` folder) and allows you to read from it.61It is used in this example to execute a script on the database connection.6263The connection object provided by SQLite can give you a cursor object.64On that cursor, there is a method to execute a complete script. Finally, you65only have to commit the changes. SQLite3 and other transactional66databases will not commit unless you explicitly tell it to.6768Now, in a terminal, from the application root directory :file:`flaskr/` it is69possible to create a database with the :command:`flask` script::7071 flask initdb72 Initialized the database.7374.. admonition:: Troubleshooting7576 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).7980Continue with :ref:`tutorial-views`
added:docs/tutorial/deploy.rst+121 added
1Deploy to Production2====================34This part of the tutorial assumes you have a server that you want to5deploy your application to. It gives an overview of how to create the6distribution file and install it, but won't go into specifics about7what server or software to use. You can set up a new environment on your8development computer to try out the instructions below, but probably9shouldn't use it for hosting a real public application. See10:doc:`/deploying/index` for a list of many different ways to host your11application.121314Build and Install15-----------------1617When you want to deploy your application elsewhere, you build a18distribution file. The current standard for Python distribution is the19*wheel* format, with the ``.whl`` extension. Make sure the wheel library20is installed first:2122.. code-block:: none2324 pip install wheel2526Running ``setup.py`` with Python gives you a command line tool to issue27build-related commands. The ``bdist_wheel`` command will build a wheel28distribution file.2930.. code-block:: none3132 python setup.py bdist_wheel3334You can find the file in ``dist/flaskr-1.0.0-py3-none-any.whl``. The35file name is the name of the project, the version, and some tags about36the file can install.3738Copy this file to another machine,39:ref:`set up a new virtualenv <install-create-env>`, then install the40file with ``pip``.4142.. code-block:: none4344 pip install flaskr-1.0.0-py3-none-any.whl4546Pip will install your project along with its dependencies.4748Since this is a different machine, you need to run ``init-db`` again to49create the database in the instance folder.5051.. code-block:: none5253 export FLASK_APP=flaskr54 flask init-db5556When Flask detects that it's installed (not in editable mode), it uses57a different directory for the instance folder. You can find it at58``venv/var/flaskr-instance`` instead.596061Configure the Secret Key62------------------------6364In the beginning of the tutorial that you gave a default value for65:data:`SECRET_KEY`. This should be changed to some random bytes in66production. Otherwise, attackers could use the public ``'dev'`` key to67modify the session cookie, or anything else that uses the secret key.6869You can use the following command to output a random secret key:7071.. code-block:: none7273 python -c 'import os; print(os.urandom(16))'7475 b'_5#y2L"F4Q8z\n\xec]/'7677Create the ``config.py`` file in the instance folder, which the factory78will read from if it exists. Copy the generated value into it.7980.. code-block:: python81 :caption: ``venv/var/flaskr-instance/config.py``8283 SECRET_KEY = b'_5#y2L"F4Q8z\n\xec]/'8485You can also set any other necessary configuration here, although86``SECRET_KEY`` is the only one needed for Flaskr.878889Run with a Production Server90----------------------------9192When running publicly rather than in development, you should not use the93built-in development server (``flask run``). The development server is94provided by Werkzeug for convenience, but is not designed to be95particularly efficient, stable, or secure.9697Instead, use a production WSGI server. For example, to use `Waitress`_,98first install it in the virtual environment:99100.. code-block:: none101102 pip install waitress103104You 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 and106call the application factory to get an application object.107108.. code-block:: none109110 waitress-serve --call 'flaskr:create_app'111112 Serving on http://0.0.0.0:8080113114See :doc:`/deploying/index` for a list of many different ways to host115your application. Waitress is just an example, chosen for the tutorial116because it supports both Windows and Linux. There are many more WSGI117servers and deployment options that you may choose for your project.118119.. _Waitress: https://docs.pylonsproject.org/projects/waitress/120121Continue to :doc:`next`.
added:docs/tutorial/factory.rst+177 added
1.. currentmodule:: flask23Application Setup4=================56A Flask application is an instance of the :class:`Flask` class.7Everything about the application, such as configuration and URLs, will8be registered with this class.910The most straightforward way to create a Flask application is to create11a global :class:`Flask` instance directly at the top of your code, like12how the "Hello, World!" example did on the previous page. While this is13simple and useful in some cases, it can cause some tricky issues as the14project grows.1516Instead of creating a :class:`Flask` instance globally, you will create17it inside a function. This function is known as the *application18factory*. Any configuration, registration, and other setup the19application needs will happen inside the function, then the application20will be returned.212223The Application Factory24-----------------------2526It's time to start coding! Create the ``flaskr`` directory and add the27``__init__.py`` file. The ``__init__.py`` serves double duty: it will28contain the application factory, and it tells Python that the ``flaskr``29directory should be treated as a package.3031.. code-block:: none3233 mkdir flaskr3435.. code-block:: python36 :caption: ``flaskr/__init__.py``3738 import os3940 from flask import Flask414243 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 )5051 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)5758 # ensure the instance folder exists59 try:60 os.makedirs(app.instance_path)61 except OSError:62 pass6364 # a simple page that says hello65 @app.route('/hello')66 def hello():67 return 'Hello, World!'6869 return app7071``create_app`` is the application factory function. You'll add to it72later in the tutorial, but it already does a lot.7374#. ``app = Flask(__name__, instance_relative_config=True)`` creates the75 :class:`Flask` instance.7677 * ``__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.8081 * ``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.8788#. :meth:`app.config.from_mapping() <Config.from_mapping>` sets89 some default configuration that the app will use:9091 * :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.9596 * ``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.101102#. :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``.106107 * ``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.111112#. :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.117118#. :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.123124125Run The Application126-------------------127128Now you can run your application using the ``flask`` command. From the129terminal, tell Flask where to find your application, then run it in130development mode.131132Development mode shows an interactive debugger whenever a page raises an133exception, and restarts the server whenever you make changes to the134code. You can leave it running and just reload the browser page as you135follow the tutorial.136137For Linux and Mac:138139.. code-block:: none140141 export FLASK_APP=flaskr142 export FLASK_ENV=development143 flask run144145For Windows cmd, use ``set`` instead of ``export``:146147.. code-block:: none148149 set FLASK_APP=flaskr150 set FLASK_ENV=development151 flask run152153For Windows PowerShell, use ``$env:`` instead of ``export``:154155.. code-block:: none156157 $env:FLASK_APP = "flaskr"158 $env:FLASK_ENV = "development"159 flask run160161You'll see output similar to this:162163.. code-block:: none164165 * 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-761172173Visit http://127.0.0.1:5000/hello in a browser and you should see the174"Hello, World!" message. Congratulations, you're now running your Flask175web application!176177Continue 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:23Step 0: Creating The Folders4============================56It is recommended to install your Flask application within a virtualenv. Please7read the :ref:`installation` section to set up your environment.89Now that you have installed Flask, you will need to create the folders required10for this tutorial. Your directory structure will look like this::1112 /flaskr13 /flaskr14 /static15 /templates1617The application will be installed and run as Python package. This is the18recommended way to install and run Flask applications. You will see exactly19how to run ``flaskr`` later on in this tutorial.2021For now go ahead and create the applications directory structure. In the next22few steps you will be creating the database schema as well as the main module.2324As a quick side note, the files inside of the :file:`static` folder are25available to users of the application via HTTP. This is the place where CSS and26JavaScript files go. Inside the :file:`templates` folder, Flask will look for27`Jinja2`_ templates. You will see examples of this later on.2829For now you should continue with :ref:`tutorial-schema`.3031.. _Jinja2: http://jinja.pocoo.org/
modified:docs/tutorial/index.rst+55 added-22 removed
1 unmodified line
23Tutorial4========56Learn by example to develop an application with Python and Flask.6.. toctree::7 :caption: Contents:8 :maxdepth: 198In this tutorial, we will create a simple blogging application. It only9supports one user, only allows text entries, and has no feeds or comments.10 layout11 factory12 database13 views14 templates15 static16 blog17 install18 tests19 deploy20 next2111While very simple, this example still features everything you need to get12started. In addition to Flask, we will use SQLite for the database, which is13built-in to Python, so there is nothing else you need.22This tutorial will walk you through creating a basic blog application23called Flaskr. Users will be able to register, log in, create posts,24and edit or delete their own posts. You will be able to package and25install the application on other computers.2615If you want the full source code in advance or for comparison, check out16the `example source`_.27.. image:: flaskr_index.png28 :align: center29 :class: screenshot30 :alt: screenshot of index page3118.. _example source: https://github.com/pallets/flask/tree/master/examples/flaskr/32It's assumed that you're already familiar with Python. The `official33tutorial`_ in the Python docs is a great way to learn or review first.3420.. toctree::21 :maxdepth: 235.. _official tutorial: https://docs.python.org/3/tutorial/3623 introduction24 folders25 schema26 setup27 packaging28 dbcon29 dbinit30 views31 templates32 css33 testing37While it's designed to give a good starting point, the tutorial doesn't38cover all of Flask's features. Check out the :ref:`quickstart` for an39overview of what Flask can do, then dive into the docs to find out more.40The tutorial only uses what's provided by Flask and Python. In another41project, you might decide to use :ref:`extensions` or other libraries to42make some tasks simpler.4344.. image:: flaskr_login.png45 :align: center46 :class: screenshot47 :alt: screenshot of login page4849Flask is flexible. It doesn't require you to use any particular project50or code layout. However, when first starting, it's helpful to use a more51structured approach. This means that the tutorial will require a bit of52boilerplate up front, but it's done to avoid many common pitfalls that53new developers encounter, and it creates a project that's easy to expand54on. Once you become more comfortable with Flask, you can step out of55this structure and take full advantage of Flask's flexibility.5657.. image:: flaskr_edit.png58 :align: center59 :class: screenshot60 :alt: screenshot of login page6162:gh:`The tutorial project is available as an example in the Flask63repository <examples/tutorial>`, if you want to compare your project64with the final product as you follow the tutorial.6566Continue to :doc:`layout`.
added:docs/tutorial/install.rst+113 added
1Make the Project Installable2============================34Making your project installable means that you can build a5*distribution* file and install that in another environment, just like6you installed Flask in your project's environment. This makes deploying7your project the same as installing any other library, so you're using8all the standard Python tools to manage everything.910Installing also comes with other benefits that might not be obvious from11the tutorial or as a new Python user, including:1213* 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.1617* You can manage your project's dependencies just like other packages18 do, so ``pip install yourproject.whl`` installs them.1920* Test tools can isolate your test environment from your development21 environment.2223.. note::24 This is being introduced late in the tutorial, but in your future25 projects you should always start with this.262728Describe the Project29--------------------3031The ``setup.py`` file describes your project and the files that belong32to it.3334.. code-block:: python35 :caption: ``setup.py``3637 from setuptools import find_packages, setup3839 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 )495051``packages`` tells Python what package directories (and the Python files52they contain) to include. ``find_packages()`` finds these directories53automatically so you don't have to type them out. To include other54files, 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.5758.. code-block:: none59 :caption: ``MANIFEST.in``6061 include flaskr/schema.sql62 graft flaskr/static63 graft flaskr/templates64 global-exclude *.pyc6566This tells Python to copy everything in the ``static`` and ``templates``67directories, and the ``schema.sql`` file, but to exclude all bytecode68files.6970See the `official packaging guide`_ for another explanation of the files71and options used.7273.. _official packaging guide: https://packaging.python.org/tutorials/distributing-packages/747576Install the Project77-------------------7879Use ``pip`` to install your project in the virtual environment.8081.. code-block:: none8283 pip install -e .8485This tells pip to find ``setup.py`` in the current directory and install86it in *editable* or *development* mode. Editable mode means that as you87make changes to your local code, you'll only need to re-install if you88change the metadata about the project, such as its dependencies.8990You can observe that the project is now installed with ``pip list``.9192.. code-block:: none9394 pip list9596 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.0108109Nothing changes from how you've been running your project so far.110``FLASK_APP`` is still set to ``flaskr`` and ``flask run`` still runs111the application.112113Continue to :doc:`tests`.
deleted:docs/tutorial/introduction.rst-39 removed
1.. _tutorial-introduction:23Introducing Flaskr4==================56This tutorial will demonstrate a blogging application named Flaskr, but feel7free to choose your own less Web-2.0-ish name ;) Essentially, it will do the8following things:9101. Let the user sign in and out with credentials specified in the11 configuration. Only one user is supported.122. When the user is logged in, they can add new entries to the page13 consisting of a text-only title and some HTML for the text. This HTML14 is not sanitized because we trust the user here.153. The index page shows all entries so far in reverse chronological order16 (newest on top) and the user can add new ones from there if logged in.1718SQLite3 will be used directly for this application because it's good enough19for an application of this size. For larger applications, however,20it makes a lot of sense to use `SQLAlchemy`_, as it handles database21connections in a more intelligent way, allowing you to target different22relational databases at once and more. You might also want to consider23one of the popular NoSQL databases if your data is more suited for those.2425.. 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.2930Here is a screenshot of the final application:3132.. image:: ../_static/flaskr.png33 :align: center34 :class: screenshot35 :alt: screenshot of the final application3637Continue with :ref:`tutorial-folders`.3839.. _SQLAlchemy: https://www.sqlalchemy.org/
added:docs/tutorial/layout.rst+110 added
1Project Layout2==============34Create a project directory and enter it:56.. code-block:: none78 mkdir flask-tutorial9 cd flask-tutorial1011Then follow the :doc:`installation instructions </installation>` to set12up a Python virtual environment and install Flask for your project.1314The tutorial will assume you're working from the ``flask-tutorial``15directory from now on. The file names at the top of each code block are16relative to this directory.1718----1920A Flask application can be as simple as a single file.2122.. code-block:: python23 :caption: ``hello.py``2425 from flask import Flask2627 app = Flask(__name__)282930 @app.route('/')31 def hello():32 return 'Hello, World!'3334However, as a project get bigger, it becomes overwhelming to keep all35the code in one file. Python projects use *packages* to organize code36into multiple modules that can be imported where needed, and the37tutorial will do this as well.3839The project directory will contain:4041* ``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.5152.. _git: https://git-scm.com/5354By the end, your project layout will look like this:5556.. code-block:: none5758 /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.in8687If you're using version control, the following files that are generated88while running your project should be ignored. There may be other files89based on the editor you use. In general, ignore files that you didn't90write. For example, with git:9192.. code-block:: none93 :caption: ``.gitignore``9495 venv/9697 *.pyc98 __pycache__/99100 instance/101102 .pytest_cache/103 .coverage104 htmlcov/105106 dist/107 build/108 *.egg-info/109110Continue to :doc:`factory`.
added:docs/tutorial/next.rst+38 added
1Keep Developing!2================34You've learned about quite a few Flask and Python concepts throughout5the tutorial. Go back and review the tutorial and compare your code with6the steps you took to get there. Compare your project to the7:gh:`example project <examples/tutorial>`, which might look a bit8different due to the step-by-step nature of the tutorial.910There's a lot more to Flask than what you've seen so far. Even so,11you're now equipped to start developing your own web applications. Check12out the :ref:`quickstart` for an overview of what Flask can do, then13dive into the docs to keep learning. Flask uses `Jinja`_, `Click`_,14`Werkzeug`_, and `ItsDangerous`_ behind the scenes, and they all have15their own documentation too. You'll also be interested in16:ref:`extensions` which make tasks like working with the database or17validating form data easier and more powerful.1819If you want to keep developing your Flaskr project, here are some ideas20for what to try next:2122* 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.3233Have fun and make awesome applications!3435.. _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:23Step 3: Installing flaskr as a Package4======================================56Flask is now shipped with built-in support for `Click`_. Click provides7Flask with enhanced and extensible command line utilities. Later in this8tutorial you will see exactly how to extend the ``flask`` command line9interface (CLI).1011A useful pattern to manage a Flask application is to install your app12following the `Python Packaging Guide`_. Presently this involves13creating two new files; :file:`setup.py` and :file:`MANIFEST.in` in the14projects root directory. You also need to add an :file:`__init__.py`15file to make the :file:`flaskr/flaskr` directory a package. After these16changes, your code structure should be::1718 /flaskr19 /flaskr20 __init__.py21 /static22 /templates23 flaskr.py24 schema.sql25 setup.py26 MANIFEST.in2728Create the ``setup.py`` file for ``flaskr`` with the following content::2930 from setuptools import setup3132 setup(33 name='flaskr',34 packages=['flaskr'],35 include_package_data=True,36 install_requires=[37 'flask',38 ],39 )4041When using setuptools, it is also necessary to specify any special files42that should be included in your package (in the :file:`MANIFEST.in`).43In this case, the static and templates directories need to be included,44as well as the schema.4546Create the :file:`MANIFEST.in` and add the following lines::4748 graft flaskr/templates49 graft flaskr/static50 include flaskr/schema.sql5152Next, to simplify locating the application, create the file,53:file:`flaskr/__init__.py` containing only the following import statement::5455 from .flaskr import app5657This import statement brings the application instance into the top-level58of the application package. When it is time to run the application, the59Flask development server needs the location of the app instance. This60import statement simplifies the location process. Without the above61import statement, the export statement a few steps below would need to be62``export FLASK_APP=flaskr.flaskr``.6364At this point you should be able to install the application. As usual, it65is recommended to install your Flask application within a `virtualenv`_.66With that said, from the ``flaskr/`` directory, go ahead and install the67application with::6869 pip install --editable .7071The above installation command assumes that it is run within the projects72root directory, ``flaskr/``. The ``editable`` flag allows editing73source code without having to reinstall the Flask app each time you make74changes. The flaskr app is now installed in your virtualenv (see output75of ``pip freeze``).7677With that out of the way, you should be able to start up the application.78Do this on Mac or Linux with the following commands in ``flaskr/``::7980 export FLASK_APP=flaskr81 export FLASK_ENV=development82 flask run8384(In case you are on Windows you need to use ``set`` instead of ``export``).85Exporting ``FLASK_ENV=development`` turns on all development features86such as enabling the interactive debugger.8788*Never leave debug mode activated in a production system*, because it will89allow users to execute code on the server!9091You will see a message telling you that server has started along with92the address at which you can access it in a browser.9394When you head over to the server in your browser, you will get a 404 error95because we don't have any views yet. That will be addressed a little later,96but first, you should get the database working.9798.. admonition:: Externally Visible Server99100 Want your server to be publicly available? Check out the101 :ref:`externally visible server <public-server>` section for more102 information.103104Continue with :ref:`tutorial-dbcon`.105106.. _Click: http://click.pocoo.org107.. _Python Packaging Guide: https://packaging.python.org108.. _virtualenv: https://virtualenv.pypa.io
deleted:docs/tutorial/schema.rst-25 removed
1.. _tutorial-schema:23Step 1: Database Schema4=======================56In this step, you will create the database schema. Only a single table is7needed for this application and it will only support SQLite. All you need to do8is put the following contents into a file named :file:`schema.sql` in the9:file:`flaskr/flaskr` folder:1011.. sourcecode:: sql1213 drop table if exists entries;14 create table entries (15 id integer primary key autoincrement,16 title text not null,17 'text' text not null18 );1920This schema consists of a single table called ``entries``. Each row in21this table has an ``id``, a ``title``, and a ``text``. The ``id`` is an22automatically incrementing integer and a primary key, the other two are23strings that must not be null.2425Continue with :ref:`tutorial-setup`.
deleted:docs/tutorial/setup.rst-101 removed
1.. _tutorial-setup:23Step 2: Application Setup Code4==============================56Next, 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 be8placed inside of the :file:`flaskr/flaskr` folder.910For 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 you12decide to create).1314The first several lines of code in the application module are the needed import15statements. After that there will be a few lines of configuration code.1617For small applications like ``flaskr``, it is possible to drop the configuration18directly into the module. However, a cleaner solution is to create a separate19``.py`` file, load that, and import the values from there.2021Here are the import statements (in :file:`flaskr.py`)::2223 import os24 import sqlite32526 from flask import (Flask, request, session, g, redirect, url_for, abort,27 render_template, flash)2829The next couple lines will create the actual application instance and30initialize it with the config from the same file in :file:`flaskr.py`::3132 app = Flask(__name__) # create the application instance :)33 app.config.from_object(__name__) # load config from this file , flaskr.py3435 # 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)4344In the above code, the :class:`~flask.Config` object works similarly to a45dictionary, so it can be updated with new values.4647.. admonition:: Database Path4849 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.5354 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.5859 For a real-world application, it's recommended to use60 :ref:`instance-folders` instead.6162Usually, it is a good idea to load a separate, environment-specific63configuration file. Flask allows you to import multiple configurations and it64will use the setting defined in the last import. This enables robust65configuration setups. :meth:`~flask.Config.from_envvar` can help achieve66this. ::6768 app.config.from_envvar('FLASKR_SETTINGS', silent=True)6970If you want to do this (not required for this tutorial) simply define the71environment variable :envvar:`FLASKR_SETTINGS` that points to a config file72to be loaded. The silent switch just tells Flask to not complain if no such73environment key is set.7475In addition to that, you can use the :meth:`~flask.Config.from_object`76method on the config object and provide it with an import name of a77module. Flask will then initialize the variable from that module. Note78that in all cases, only variable names that are uppercase are considered.7980The :data:`SECRET_KEY` is needed to keep the client-side sessions secure.81Choose that key wisely and as hard to guess and complex as possible.8283Lastly, add a method that allows for easy connections to the specified84database. ::8586 def connect_db():87 """Connects to the specific database."""8889 rv = sqlite3.connect(app.config['DATABASE'])90 rv.row_factory = sqlite3.Row91 return rv9293This can be used to open a connection on request and also from the94interactive Python shell or a script. This will come in handy later.95You can create a simple database connection through SQLite and then tell96it to use the :class:`sqlite3.Row` object to represent rows. This allows97the rows to be treated as if they were dictionaries instead of tuples.9899In the next section you will see how to run the application.100101Continue with :ref:`tutorial-packaging`.
added:docs/tutorial/static.rst+72 added
1Static Files2============34The authentication views and templates work, but they look very plain5right now. Some `CSS`_ can be added to add style to the HTML layout you6constructed. The style won't change, so it's a *static* file rather than7a template.89Flask automatically adds a ``static`` view that takes a path relative10to the ``flaskr/static`` directory and serves it. The ``base.html``11template already has a link to the ``style.css`` file:1213.. code-block:: html+jinja1415 {{ url_for('static', filename='style.css') }}1617Besides CSS, other types of static files might be files with JavaScript18functions, or a logo image. They are all placed under the19``flaskr/static`` directory and referenced with20``url_for('static', filename='...')``.2122This tutorial isn't focused on how to write CSS, so you can just copy23the following into the ``flaskr/static/style.css`` file:2425.. code-block:: css26 :caption: ``flaskr/static/style.css``2728 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; }5455You can find a less compact version of ``style.css`` in the56:gh:`example code <examples/tutorial/flaskr/static/style.css>`.5758Go to http://127.0.0.1/auth/login and the page should look like the59screenshot below.6061.. image:: flaskr_login.png62 :align: center63 :class: screenshot64 :alt: screenshot of login page6566You can read more about CSS from `Mozilla's documentation <CSS_>`_. If67you change a static file, refresh the browser page. If the change68doesn't show up, try clearing your browser's cache.6970.. _CSS: https://developer.mozilla.org/docs/Web/CSS7172Continue to :doc:`blog`.
modified:docs/tutorial/templates.rst+161 added-87 removed
1.. _tutorial-templates:1.. currentmodule:: flask23Step 7: The Templates4=====================3Templates4=========56Now it is time to start working on the templates. As you may have7noticed, if you make requests with the app running, you will get8an exception that Flask cannot find the templates. The templates9are using `Jinja2`_ syntax and have autoescaping enabled by10default. This means that unless you mark a value in the code with11:class:`~flask.Markup` or with the ``|safe`` filter in the template,12Jinja2 will ensure that special characters such as ``<`` or ``>`` are13escaped with their XML equivalents.6You've written the authentication views for your application, but if7you'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.10The template files will be stored in the ``templates`` directory inside11the ``flaskr`` package.1215We are also using template inheritance which makes it possible to reuse16the layout of the website in all pages.13Templates are files that contain static data as well as placeholders14for dynamic data. A template is rendered with specific data to produce a15final document. Flask uses the `Jinja`_ template library to render16templates.1718Create the follwing three HTML files and place them in the19:file:`templates` folder:18In your application, you will use templates to render `HTML`_ which19will display in the user's browser. In Flask, Jinja is configured to20*autoescape* any data that is rendered in HTML templates. This means21that it's safe to render user input; any characters they've entered that22could mess with the HTML, such as ``<`` and ``>`` will be *escaped* with23*safe* values that look the same in the browser but don't cause unwanted24effects.2521.. _Jinja2: http://jinja.pocoo.org/docs/templates26Jinja looks and behaves mostly like Python. Special delimiters are used27to distinguish Jinja syntax from the static data in the template.28Anything between ``{{`` and ``}}`` is an expression that will be output29to the final document. ``{%`` and ``%}`` denotes a control flow30statement like ``if`` and ``for``. Unlike Python, blocks are denoted31by start and end tags rather than indentation since static text within32a block could change indentation.3323layout.html24-----------34.. _Jinja: http://jinja.pocoo.org/docs/templates/35.. _HTML: https://developer.mozilla.org/docs/Web/HTML3626This 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 the28flashed messages if there are any. The ``{% block body %}`` block can be29replaced by a block of the same name (``body``) in a child template.3731The :class:`~flask.session` dict is available in the template as well and32you can use that to check if the user is logged in or not. Note that in33Jinja you can access missing attributes and items of objects / dicts which34makes the following code work, even if there is no ``'logged_in'`` key in35the session:38The Base Layout39---------------4037.. sourcecode:: html+jinja41Each page in the application will have the same basic layout around a42different body. Instead of writing the entire HTML structure in each43template, each template will *extend* a base template and override44specific sections.4546.. code-block:: html+jinja47 :caption: ``flaskr/templates/base.html``4849 <!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>7357show_entries.html58-----------------74:data:`g` is automatically available in templates. Based on if75``g.user`` is set (from ``load_logged_in_user``), either the username76and a log out link are displayed, otherwise links to register and log in77are displayed. :func:`url_for` is also automatically available, and is78used to generate URLs to views instead of writing them out manually.7960This template extends the :file:`layout.html` template from above to display the61messages. Note that the ``for`` loop iterates over the messages we passed62in with the :func:`~flask.render_template` function. Notice that the form is63configured to submit to the `add_entry` view function and use ``POST`` as64HTTP method:80After the page title, and before the content, the template loops over81each message returned by :func:`get_flashed_messages`. You used82:func:`flash` in the views to show error messages, and this is the code83that will display them.8466.. sourcecode:: html+jinja85There are three blocks defined here that will be overridden in the other86templates:8768 {% 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.9091#. ``{% block header %}`` is similar to ``title`` but will change the92 title displayed on the page.9394#. ``{% block content %}`` is where the content of each page goes, such95 as the login form or a blog post.9697The base template is directly in the ``templates`` directory. To keep98the others organized, the templates for a blueprint will be placed in a99directory with the same name as the blueprint.100101102Register103--------104105.. code-block:: html+jinja106 :caption: ``flaskr/templates/auth/register.html``107108 {% extends 'base.html' %}109110 {% block header %}111 <h1>{% block title %}Register{% endblock %}</h1>112 {% endblock %}11390login.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 %}12393This is the login template, which basically just displays a form to allow94the user to login:124``{% extends 'base.html' %}`` tells Jinja that this template should125replace the blocks from the base template. All the rendered content must126appear inside ``{% block %}`` tags that override blocks from the base127template.12896.. sourcecode:: html+jinja129A useful pattern used here is to place ``{% block title %}`` inside130``{% block header %}``. This will set the title block and then output131the value of it into the header block, so that both the window and page132share the same title without writing it twice.13398 {% 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>134The ``input`` tags are using the ``required`` attribute here. This tells135the browser not to submit the form until those fields are filled in. If136the user is using an older browser that doesn't support that attribute,137or if they are using something besides a browser to make requests, you138still want to validate the data in the Flask view. It's important to139always fully validate the data on the server, even if the client does140some validation as well.141142143Log In144------145146This is identical to the register template except for the title and147submit button.148149.. code-block:: html+jinja150 :caption: ``flaskr/templates/auth/login.html``151152 {% extends 'base.html' %}153154 {% block header %}155 <h1>{% block title %}Log In{% endblock %}</h1>156 {% endblock %}157158 {% 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 %}167113Continue with :ref:`tutorial-css`.168169Register A User170---------------171172Now that the authentication templates are written, you can register a173user. Make sure the server is still running (``flask run`` if it's not),174then go to http://127.0.0.1:5000/auth/register.175176Try clicking the "Register" button without filling out the form and see177that the browser shows an error message. Try removing the ``required``178attributes from the ``register.html`` template and click "Register"179again. Instead of the browser showing an error, the page will reload and180the error from :func:`flash` in the view will be shown.181182Fill out a username and password and you'll be redirected to the login183page. Try entering an incorrect username, or the correct username and184incorrect password. If you log in you'll get an error because there's185no ``index`` view to redirect to yet.186187Continue to :doc:`static`.
deleted:docs/tutorial/testing.rst-96 removed
1.. _tutorial-testing:23Bonus: Testing the Application4==============================56Now that you have finished the application and everything works as7expected, it's probably not a bad idea to add automated tests to simplify8modifications in the future. The application above is used as a basic9example of how to perform unit testing in the :ref:`testing` section of the10documentation. Go there to see how easy it is to test Flask applications.1112Adding tests to flaskr13----------------------1415Assuming you have seen the :ref:`testing` section and have either written16your own tests for ``flaskr`` or have followed along with the examples17provided, you might be wondering about ways to organize the project.1819One possible and recommended project structure is::2021 flaskr/22 flaskr/23 __init__.py24 static/25 templates/26 tests/27 test_flaskr.py28 setup.py29 MANIFEST.in3031For now go ahead a create the :file:`tests/` directory as well as the 32:file:`test_flaskr.py` file.3334Running the tests35-----------------3637At this point you can run the tests. Here ``pytest`` will be used. 3839.. 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::4243 pip install -e .44 pip install pytest 4546Run and watch the tests pass, within the top-level :file:`flaskr/` 47directory as::4849 pytest5051Testing + setuptools52--------------------5354One way to handle testing is to integrate it with ``setuptools``. Here55that requires adding a couple of lines to the :file:`setup.py` file and56creating a new file :file:`setup.cfg`. One benefit of running the tests 57this way is that you do not have to install ``pytest``. Go ahead and 58update the :file:`setup.py` file to contain::5960 from setuptools import setup6162 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 )7677Now create :file:`setup.cfg` in the project root (alongside78:file:`setup.py`)::7980 [aliases]81 test=pytest8283Now you can run::8485 python setup.py test8687This calls on the alias created in :file:`setup.cfg` which in turn runs88``pytest`` via ``pytest-runner``, as the :file:`setup.py` script has89been called. (Recall the `setup_requires` argument in :file:`setup.py`)90Following the standard rules of test-discovery your tests will be91found, run, and hopefully pass.9293This is one possible way to run and manage testing. Here ``pytest`` is94used, but there are other options such as ``nose``. Integrating testing95with ``setuptools`` is convenient because it is not necessary to actually96download ``pytest`` or any other testing framework one might use.
added:docs/tutorial/tests.rst+561 added
1.. currentmodule:: flask23Test Coverage4=============56Writing unit tests for your application lets you check that the code7you wrote works the way you expect. Flask provides a test client that8simulates requests to the application and returns the response data.910You should test as much of your code as possible. Code in functions only11runs when the function is called, and code in branches, such as ``if``12blocks, only runs when the condition is met. You want to make sure that13each function is tested with data that covers each branch.1415The closer you get to 100% coverage, the more comfortable you can be16that making a change won't unexpectedly change other behavior. However,17100% coverage doesn't guarantee that your application doesn't have bugs.18In particular, it doesn't test how the user interacts with the19application in the browser. Despite this, test coverage is an important20tool to use during development.2122.. note::23 This is being introduced late in the tutorial, but in your future24 projects you should test as you develop.2526You'll use `pytest`_ and `coverage`_ to test and measure your code.27Install them both:2829.. code-block:: none3031 pip install pytest coverage3233.. _pytest: https://pytest.readthedocs.io/34.. _coverage: https://coverage.readthedocs.io/353637Setup and Fixtures38------------------3940The 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*43that each test will use. Tests are in Python modules that start with44``test_``, and each test function in those modules also starts with45``test_``.4647Each test will create a new temporary database file and populate some48data that will be used in the tests. Write a SQL file to insert that49data.5051.. code-block:: sql52 :caption: ``tests/data.sql``5354 INSERT INTO user (username, password)55 VALUES56 ('test', 'pbkdf2:sha256:50000$TCI4GzcX$0de171a4f4dac32e3364c7ddc7c14f3e2fa61f2d17574483f7ffbb431b4acb2f'),57 ('other', 'pbkdf2:sha256:50000$kJPKsz6N$d2d4784f1b030a9761f5ccaeeaca413f27f2ecb76d6168407af962ddce849f79');5859 INSERT INTO post (title, body, author_id, created)60 VALUES61 ('test title', 'test' || x'0a' || 'body', 1, '2018-01-01 00:00:00');6263The ``app`` fixture will call the factory and pass ``test_config`` to64configure the application and database for testing instead of using your65local development configuration.6667.. code-block:: python68 :caption: ``tests/conftest.py``6970 import os71 import tempfile7273 import pytest74 from flaskr import create_app75 from flaskr.db import get_db, init_db7677 with open(os.path.join(os.path.dirname(__file__), 'data.sql'), 'rb') as f:78 _data_sql = f.read().decode('utf8')798081 @pytest.fixture82 def app():83 db_fd, db_path = tempfile.mkstemp()8485 app = create_app({86 'TESTING': True,87 'DATABASE': db_path,88 })8990 with app.app_context():91 init_db()92 get_db().executescript(_data_sql)9394 yield app9596 os.close(db_fd)97 os.unlink(db_path)9899100 @pytest.fixture101 def client(app):102 return app.test_client()103104105 @pytest.fixture106 def runner(app):107 return app.test_cli_runner()108109:func:`tempfile.mkstemp` creates and opens a temporary file, returning110the file object and the path to it. The ``DATABASE`` path is111overridden so it points to this temporary path instead of the instance112folder. After setting the path, the database tables are created and the113test data is inserted. After the test is over, the temporary file is114closed and removed.115116:data:`TESTING` tells Flask that the app is in test mode. Flask changes117some internal behavior so it's easier to test, and other extensions can118also use the flag to make testing them easier.119120The ``client`` fixture calls121:meth:`app.test_client() <Flask.test_client>` with the application122object created by the ``app`` fixture. Tests will use the client to make123requests to the application without running the server.124125The ``runner`` fixture is similar to ``client``.126:meth:`app.test_cli_runner() <Flask.test_cli_runner>` creates a runner127that can call the Click commands registered with the application.128129Pytest uses fixtures by matching their function names with the names130of arguments in the test functions. For example, the ``test_hello``131function you'll write next takes a ``client`` argument. Pytest matches132that with the ``client`` fixture function, calls it, and passes the133returned value to the test function.134135136Factory137-------138139There's not much to test about the factory itself. Most of the code will140be executed for each test already, so if something fails the other tests141will notice.142143The only behavior that can change is passing test config. If config is144not passed, there should be some default configuration, otherwise the145configuration should be overridden.146147.. code-block:: python148 :caption: ``tests/test_factory.py``149150 from flaskr import create_app151152153 def test_config():154 assert not create_app().testing155 assert create_app({'TESTING': True}).testing156157158 def test_hello(client):159 response = client.get('/hello')160 assert response.data == b'Hello, World!'161162You added the ``hello`` route as an example when writing the factory at163the beginning of the tutorial. It returns "Hello, World!", so the test164checks that the response data matches.165166167Database168--------169170Within an application context, ``get_db`` should return the same171connection each time it's called. After the context, the connection172should be closed.173174.. code-block:: python175 :caption: ``tests/test_db.py``176177 import sqlite3178179 import pytest180 from flaskr.db import get_db181182183 def test_get_close_db(app):184 with app.app_context():185 db = get_db()186 assert db is get_db()187188 with pytest.raises(sqlite3.ProgrammingError) as e:189 db.execute('SELECT 1')190191 assert 'closed' in str(e)192193The ``init-db`` command should call the ``init_db`` function and output194a message.195196.. code-block:: python197 :caption: ``tests/test_db.py``198199 def test_init_db_command(runner, monkeypatch):200 class Recorder(object):201 called = False202203 def fake_init_db():204 Recorder.called = True205206 monkeypatch.setattr('flaskr.db.init_db', fake_init_db)207 result = runner.invoke(args=['init-db'])208 assert 'Initialized' in result.output209 assert Recorder.called210211This 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``214command by name.215216217Authentication218--------------219220For most of the views, a user needs to be logged in. The easiest way to221do this in tests is to make a ``POST`` request to the ``login`` view222with the client. Rather than writing that out every time, you can write223a class with methods to do that, and use a fixture to pass it the client224for each test.225226.. code-block:: python227 :caption: ``tests/conftest.py``228229 class AuthActions(object):230 def __init__(self, client):231 self._client = client232233 def login(self, username='test', password='test'):234 return self._client.post(235 '/auth/login',236 data={'username': username, 'password': password}237 )238239 def logout(self):240 return self._client.get('/auth/logout')241242243 @pytest.fixture244 def auth(client):245 return AuthActions(client)246247With the ``auth`` fixture, you can call ``auth.login()`` in a test to248log in as the ``test`` user, which was inserted as part of the test249data in the ``app`` fixture.250251The ``register`` view should render successfully on ``GET``. On ``POST``252with valid form data, it should redirect to the login URL and the user's253data should be in the database. Invalid data should display error254messages.255256.. code-block:: python257 :caption: ``tests/test_auth.py``258259 import pytest260 from flask import g, session261 from flaskr.db import get_db262263264 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']270271 with app.app_context():272 assert get_db().execute(273 "select * from user where username = 'a'",274 ).fetchone() is not None275276277 @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.data288289:meth:`client.get() <werkzeug.test.Client.get>` makes a ``GET`` request290and returns the :class:`Response` object returned by Flask. Similarly,291:meth:`client.post() <werkzeug.test.Client.post>` makes a ``POST``292request, converting the ``data`` dict into form data.293294To test that the page renders successfully, a simple request is made and295checked for a ``200 OK`` :attr:`~Response.status_code`. If296rendering failed, Flask would return a ``500 Internal Server Error``297code.298299:attr:`~Response.headers` will have a ``Location`` header with the login300URL when the register view redirects to the login view.301302:attr:`~Response.data` contains the body of the response as bytes. If303you 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 compare305Unicode text, use :meth:`get_data(as_text=True) <werkzeug.wrappers.BaseResponse.get_data>`306instead.307308``pytest.mark.parametrize`` tells Pytest to run the same test function309with different arguments. You use it here to test different invalid310input and error messages without writing the same code three times.311312The 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.315316.. code-block:: python317 :caption: ``tests/test_auth.py``318319 def test_login(client, auth):320 assert client.get('/auth/login').status_code == 200321 response = auth.login()322 assert response.headers['Location'] == 'http://localhost/'323324 with client:325 client.get('/')326 assert session['user_id'] == 1327 assert g.user['username'] == 'test'328329330 @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.data337338Using ``client`` in a ``with`` block allows accessing context variables339such as :data:`session` after the response is returned. Normally,340accessing ``session`` outside of a request would raise an error.341342Testing ``logout`` is the opposite of ``login``. :data:`session` should343not contain ``user_id`` after logging out.344345.. code-block:: python346 :caption: ``tests/test_auth.py``347348 def test_logout(client, auth):349 auth.login()350351 with client:352 auth.logout()353 assert 'user_id' not in session354355356Blog357----358359All the blog views use the ``auth`` fixture you wrote earlier. Call360``auth.login()`` and subsequent requests from the client will be logged361in as the ``test`` user.362363The ``index`` view should display information about the post that was364added with the test data. When logged in as the author, there should be365a link to edit the post.366367You can also test some more authentication behavior while testing the368``index`` view. When not logged in, each page shows links to log in or369register. When logged in, there's a link to log out.370371.. code-block:: python372 :caption: ``tests/test_blog.py``373374 import pytest375 from flaskr.db import get_db376377378 def test_index(client, auth):379 response = client.get('/')380 assert b"Log In" in response.data381 assert b"Register" in response.data382383 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.data390391A user must be logged in to access the ``create``, ``update``, and392``delete`` views. The logged in user must be the author of the post to393access ``update`` and ``delete``, otherwise a ``403 Forbidden`` status394is returned. If a ``post`` with the given ``id`` doesn't exist,395``update`` and ``delete`` should return ``404 Not Found``.396397.. code-block:: python398 :caption: ``tests/test_blog.py``399400 @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'408409410 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()416417 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('/').data423424425 @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 == 404432433The ``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 the436database, and ``update`` should modify the existing data. Both pages437should show an error message on invalid data.438439.. code-block:: python440 :caption: ``tests/test_blog.py``441442 def test_create(client, auth, app):443 auth.login()444 assert client.get('/create').status_code == 200445 client.post('/create', data={'title': 'created', 'body': ''})446447 with app.app_context():448 db = get_db()449 count = db.execute('SELECT COUNT(id) FROM post').fetchone()[0]450 assert count == 2451452453 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': ''})457458 with app.app_context():459 db = get_db()460 post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()461 assert post['title'] == 'updated'462463464 @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.data472473The ``delete`` view should redirect to the index URL and the post should474no longer exist in the database.475476.. code-block:: python477 :caption: ``tests/test_blog.py``478479 def test_delete(client, auth, app):480 auth.login()481 response = client.post('/1/delete')482 assert response.headers['Location'] == 'http://localhost/'483484 with app.app_context():485 db = get_db()486 post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()487 assert post is None488489490Running the Tests491-----------------492493Some extra configuration, which is not required but makes running494tests with coverage less verbose, can be added to the project's495``setup.cfg`` file.496497.. code-block:: none498 :caption: ``setup.cfg``499500 [tool:pytest]501 testpaths = tests502503 [coverage:run]504 branch = True505 source =506 flaskr507508To run the tests, use the ``pytest`` command. It will find and run all509the test functions you've written.510511.. code-block:: none512513 pytest514515 ========================= 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 items519520 tests/test_auth.py ........ [ 34%]521 tests/test_blog.py ............ [ 86%]522 tests/test_db.py .. [ 95%]523 tests/test_factory.py .. [100%]524525 ====================== 24 passed in 0.64 seconds =======================526527If any tests fail, pytest will show the error that was raised. You can528run ``pytest -v`` to get a list of each test function rather than dots.529530To measure the code coverage of your tests, use the ``coverage`` command531to run pytest instead of running it directly.532533.. code-block:: none534535 coverage run -m pytest536537You can either view a simple coverage report in the terminal:538539.. code-block:: none540541 coverage report542543 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%551552An HTML report allows you to see which lines were covered in each file:553554.. code-block:: none555556 coverage html557558This generates files in the ``htmlcov`` directory. Open559``htmlcov/index.html`` in your browser to see the report.560561Continue to :doc:`deploy`.
modified:docs/tutorial/views.rst+273 added-90 removed
1.. _tutorial-views:1.. currentmodule:: flask23Step 6: The View Functions4==========================3Blueprints and Views4====================56Now that the database connections are working, you can start writing the7view functions. You will need four of them; Show Entries, Add New Entry,8Login and Logout. Add the following code snipets to :file:`flaskr.py`.6A view function is the code you write to respond to requests to your7application. Flask uses patterns to match the incoming request URL to8the view that should handle it. The view returns data that Flask turns9into an outgoing response. Flask can also go the other direction and10generate a URL to a view based on its name and arguments.1110Show Entries11------------1213This view shows all the entries stored in the database. It listens on the14root of the application and will select title and text from the database.15The one with the highest id (the newest entry) will be on top. The rows16returned from the cursor look a bit like dictionaries because we are using17the :class:`sqlite3.Row` row factory.13Create a Blueprint14------------------1519The view function will pass the entries to the :file:`show_entries.html`20template and return the rendered one::16A :class:`Blueprint` is a way to organize a group of related views and17other code. Rather than registering views and other code directly with18an application, they are registered with a blueprint. Then the blueprint19is registered with the application when it is available in the factory20function.2122 @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)22Flaskr will have two blueprints, one for authentication functions and23one for the blog posts functions. The code for each blueprint will go24in a separate module. Since the blog needs to know about authentication,25you'll write the authentication one first.2629Add New Entry30-------------27.. code-block:: python28 :caption: ``flaskr/auth.py``2932This view lets the user add new entries if they are logged in. This only33responds 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 and36redirect back to the `show_entries` page::30 import functools3138 @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_hash3649Note 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_db3852.. admonition:: Security Note39 bp = Blueprint('auth', __name__, url_prefix='/auth')4054 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.41This creates a :class:`Blueprint` named ``'auth'``. Like the application42object, the blueprint needs to know where it's defined, so ``__name__``43is passed as the second argument. The ``url_prefix`` will be prepended44to all the URLs associated with the blueprint.4559Login and Logout60----------------46Import and register the blueprint from the factory using47:meth:`app.register_blueprint() <Flask.register_blueprint>`. Place the48new code at the end of the factory function before returning the app.4962These functions are used to sign the user in and out. Login checks the63username and password against the ones from the configuration and sets the64`logged_in` key for the session. If the user logged in successfully, that65key is set to ``True``, and the user is redirected back to the `show_entries`66page. In addition, a message is flashed that informs the user that he or67she was logged in successfully. If an error occurred, the template is68notified about that, and the user is asked again::50.. code-block:: python51 :caption: ``flaskr/__init__.py``5270 @app.route('/login', methods=['GET', 'POST'])53 def create_app():54 app = ...55 # existing code omitted5657 from . import auth58 app.register_blueprint(auth.bp)5960 return app6162The authentication blueprint will have views to register new users and63to log in and log out.646566The First View: Register67------------------------6869When the user visits the ``/auth/register`` URL, the ``register`` view70will return `HTML`_ with a form for them to fill out. When they submit71the form, it will validate their input and either show the form again72with an error message or create the new user and go to the login page.7374.. _HTML: https://developer.mozilla.org/docs/Web/HTML7576For now you will just write the view code. On the next page, you'll77write templates to generate the HTML form.7879.. code-block:: python80 :caption: ``flaskr/auth.py``8182 @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 = None8990 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)9899 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'))106107 flash(error)108109 return render_template('auth/register.html')110111Here's what the ``register`` view function is doing:112113#. :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.117118#. If the user submitted the form,119 :attr:`request.method <Request.method>` will be ``'POST'``. In this120 case, start validating the input.121122#. :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``.125126#. Validate that ``username`` and ``password`` are not empty.127128#. 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*.135136 :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.140141#. 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.148149#. 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.155156#. If validation fails, the error is shown to the user. :func:`flash`157 stores messages that can be retrieved when rendering the template.158159#. 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.164165166Login167-----168169This view follows the same pattern as the ``register`` view above.170171.. code-block:: python172 :caption: ``flaskr/auth.py``173174 @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()18484The `logout` function, on the other hand, removes that key from the session85again. There is a neat trick here: if you use the :meth:`~dict.pop` method86of the dict and pass a second parameter to it (the default), the method87will delete the key from the dictionary if present or do nothing when that88key is not in there. This is helpful because now it is not necessary to89check 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.'18991::190 if error is None:191 session.clear()192 session['user_id'] = user['id']193 return redirect(url_for('index'))194195 flash(error)196197 return render_template('auth/login.html')198199There are a few differences from the ``register`` view:200201#. The user is queried first and stored in a variable for later use.202203#. :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.206207#. :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.212213Now that the user's ``id`` is stored in the :data:`session`, it will be214available on subsequent requests. At the beginning of each request, if215a user is logged in their information should be loaded and made216available to other views.217218.. code-block:: python219 :caption: ``flaskr/auth.py``220221 @bp.before_app_request222 def load_logged_in_user():223 user_id = session.get('user_id')224225 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()231232:meth:`bp.before_app_request() <Blueprint.before_app_request>` registers233a function that runs before the view function, no matter what URL is234requested. ``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 it236on :data:`g.user <g>`, which lasts for the length of the request. If237there is no user id, or if the id doesn't exist, ``g.user`` will be238``None``.239240241Logout242------243244To log out, you need to remove the user id from the :data:`session`.245Then ``load_logged_in_user`` won't load a user on subsequent requests.246247.. code-block:: python248 :caption: ``flaskr/auth.py``24993 @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'))25499.. admonition:: Security Note255101 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.256Require Authentication in Other Views257-------------------------------------258107 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.259Creating, editing, and deleting blog posts will require a user to be260logged in. A *decorator* can be used to check this for each view it's261applied to.262112 You can find a list of recommended Flask extensions113 `here <http://flask.pocoo.org/extensions/>`_263.. code-block:: python264 :caption: ``flaskr/auth.py``265266 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'))271116Continue with :ref:`tutorial-templates`.272 return view(**kwargs)273118.. _hashed and salted: https://blog.codinghorror.com/youre-probably-storing-passwords-incorrectly/274 return wrapped_view275276This decorator returns a new view function that wraps the original view277it's applied to. The new function checks if a user is loaded and278redirects to the login page otherwise. If a user is loaded the original279view is called and continues normally. You'll use this decorator when280writing the blog views.281282Endpoints and URLs283------------------284285The :func:`url_for` function generates the URL to a view based on a name286and arguments. The name associated with a view is also called the287*endpoint*, and by default it's the same as the name of the view288function.289290For example, the ``hello()`` view that was added to the app291factory earlier in the tutorial has the name ``'hello'`` and can be292linked to with ``url_for('hello')``. If it took an argument, which293you'll see later, it would be linked to using294``url_for('hello', who='World')``.295296When using a blueprint, the name of the blueprint is prepended to the297name of the function, so the endpoint for the ``login`` function you298wrote above is ``'auth.login'`` because you added it to the ``'auth'``299blueprint.300301Continue to :doc:`templates`.
modified:docs/conf.py+35 added-4 removed
9 unmodified lines
10#11# All configuration values have a default; values that are commented out12# serve to show the default.13from __future__ import print_function1415import datetime16import os17import sys16import pkg_resources18import time18import datetime1920from sphinx.application import Sphinx20import pkg_resources2122BUILD_DATE = datetime.datetime.utcfromtimestamp(int(os.environ.get('SOURCE_DATE_EPOCH', time.time())))2324# If extensions (or modules to document with autodoc) are in another directory,
274 unmodified lines
299unwrap_decorators()300del unwrap_decorators301302303def setup(app: Sphinx):303def setup(app):304 def cut_module_meta(app, what, name, obj, options, lines):305 """Remove metadata from autodoc output."""306 if what != 'module':307 return
3 unmodified lines
311 if not line.startswith((':copyright:', ':license:'))312 ]313314 app.connect('autodoc-process-docstring', cut_module_meta)315316 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/'323324 if text.endswith('>'):325 words, text = text[:-1].rsplit('<', 1)326 words = words.strip()327 else:328 words = None329330 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)334335 if words is None:336 words = url337338 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], []344345 app.add_role('gh', github_link)
modified:docs/installation.rst+2 added
102 unmodified lines
103.. code-block:: bat104105 \Python27\Scripts\virtualenv.exe venv106107.. _install-activate-env:108109Activate the environment110~~~~~~~~~~~~~~~~~~~~~~~~111112Before you work on your project, activate the corresponding environment:
71 unmodified lines
modified:docs/testing.rst+1 added-4 removed
26 unmodified lines
27---------------2829First, we need an application to test; we will use the application from30the :ref:`tutorial`. If you don't have that application yet, get the31source code from `the examples`_.31source code from :gh:`the examples <examples/tutorial>`.3233.. _the examples:34 https://github.com/pallets/flask/tree/master/examples/flaskr/3533The Testing Skeleton34--------------------3536We begin by adding a tests directory under the application root. Then
426 unmodified lines
deleted:examples/blueprintexample/simple_page/templates/pages/hello.html-5 removed
1{% extends "pages/layout.html" %}23{% block body %}4 Hello5{% endblock %}
deleted:examples/blueprintexample/simple_page/templates/pages/index.html-5 removed
1{% extends "pages/layout.html" %}23{% 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>1819 {% 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
1from flask import Blueprint, render_template, abort2from jinja2 import TemplateNotFound34simple_page = Blueprint('simple_page', __name__,5 template_folder='templates')67@simple_page.route('/', defaults={'page': 'index'})8@simple_page.route('/<page>')9def 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"""3Blueprint Example4~~~~~~~~~~~~~~~~~56:copyright: © 2010 by the Pallets team.7:license: BSD, see LICENSE for more details.8"""910from flask import Flask11from simple_page.simple_page import simple_page1213app = Flask(__name__)14app.register_blueprint(simple_page)15# Blueprint can be registered many times16app.register_blueprint(simple_page, url_prefix='/pages')1718if __name__=='__main__':19 app.run()
deleted:examples/blueprintexample/test_blueprintexample.py-35 removed
1# -*- coding: utf-8 -*-2"""3Blueprint Example Tests4~~~~~~~~~~~~~~~~~~~~~~~56:copyright: © 2010 by the Pallets team.7:license: BSD, see LICENSE for more details.8"""910import pytest1112import blueprintexample131415@pytest.fixture16def client():17 return blueprintexample.app.test_client()181920def test_urls(client):21 r = client.get('/')22 assert r.status_code == 2002324 r = client.get('/hello')25 assert r.status_code == 2002627 r = client.get('/world')28 assert r.status_code == 2002930 # second blueprint instance31 r = client.get('/pages/hello')32 assert r.status_code == 2003334 r = client.get('/pages/world')35 assert r.status_code == 200
deleted:examples/flaskr/flaskr/blueprints/__init__.py
deleted:examples/flaskr/flaskr/blueprints/flaskr.py-85 removed
1# -*- coding: utf-8 -*-2"""3 Flaskr4 ~~~~~~56 A microblog example application written as Flask tutorial with7 Flask and sqlite3.89 :copyright: © 2010 by the Pallets team.10 :license: BSD, see LICENSE for more details.11"""1213from sqlite3 import dbapi2 as sqlite314from flask import Blueprint, request, session, g, redirect, url_for, abort, \15 render_template, flash, current_app161718# create our blueprint :)19bp = Blueprint('flaskr', __name__)202122def connect_db():23 """Connects to the specific database."""24 rv = sqlite3.connect(current_app.config['DATABASE'])25 rv.row_factory = sqlite3.Row26 return rv272829def 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()353637def 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_db444546@bp.route('/')47def 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)525354@bp.route('/add', methods=['POST'])55def 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'))646566@bp.route('/login', methods=['GET', 'POST'])67def 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)798081@bp.route('/logout')82def 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
1body { font-family: sans-serif; background: #eee; }2a, h1, h2 { color: #377BA8; }3h1, h2 { font-family: 'Georgia', serif; margin: 0; }4h1 { border-bottom: 2px solid #eee; }5h2 { font-size: 1.2em; }67.page { margin: 2em auto; width: 35em; border: 5px solid #ccc;8 padding: 0.8em; background: white; }9.entries { list-style: none; margin: 0; padding: 0; }10.entries li { margin: 0.8em 1.2em; }11.entries li h2 { margin-left: -1em; }12.add-entry { font-size: 0.9em; border-bottom: 1px solid #ccc; }13.add-entry dl { font-weight: bold; }14.metanav { text-align: right; font-size: 0.8em; padding: 0.3em;15 margin-bottom: 1em; background: #fafafa; }16.flash { background: #CEE5F5; padding: 0.5em;17 border: 1px solid #AACBE2; }18.error { background: #F0D6D6; padding: 0.5em; }
deleted:examples/flaskr/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 ~~~~~~56 A microblog example application written as Flask tutorial with7 Flask and sqlite3.89 :copyright: © 2010 by the Pallets team.10 :license: BSD, see LICENSE for more details.11"""1213import os14from flask import Flask, g15from werkzeug.utils import find_modules, import_string16from flaskr.blueprints.flaskr import init_db171819def create_app(config=None):20 app = Flask('flaskr')2122 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)3132 register_blueprints(app)33 register_cli(app)34 register_teardowns(app)3536 return app373839def register_blueprints(app):40 """Register all blueprint modules4142 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 None495051def 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.')575859def 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
1drop table if exists entries;2create table entries (3 id integer primary key autoincrement,4 title text not null,5 'text' text not null6);
deleted:examples/flaskr/tests/test_flaskr.py-83 removed
1# -*- coding: utf-8 -*-2"""3 Flaskr Tests4 ~~~~~~~~~~~~56 Tests the Flaskr application.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112import os13import tempfile14import pytest15from flaskr.factory import create_app16from flaskr.blueprints.flaskr import init_db171819@pytest.fixture20def app():21 db_fd, db_path = tempfile.mkstemp()22 config = {23 'DATABASE': db_path,24 'TESTING': True,25 }26 app = create_app(config=config)2728 with app.app_context():29 init_db()30 yield app3132 os.close(db_fd)33 os.unlink(db_path)343536@pytest.fixture37def client(app):38 return app.test_client()394041def login(client, username, password):42 return client.post('/login', data=dict(43 username=username,44 password=password45 ), follow_redirects=True)464748def logout(client):49 return client.get('/logout', follow_redirects=True)505152def test_empty_db(client):53 """Start with a blank database."""54 rv = client.get('/')55 assert b'No entries here so far' in rv.data565758def 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.data717273def 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'&lt;Hello&gt;' in rv.data83 assert b'<strong>HTML</strong> allowed here' in rv.data
deleted:examples/flaskr/.gitignore-2 removed
1flaskr.db2.eggs/
deleted:examples/flaskr/MANIFEST.in-3 removed
1graft flaskr/templates2graft flaskr/static3include flaskr/schema.sql
deleted:examples/flaskr/README-40 removed
1 / Flaskr /23 a minimal blog application456 ~ What is Flaskr?78 A sqlite powered thumble blog application910 ~ How do I use it?1112 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.1718 2. install the app from the root of the project directory1920 pip install --editable .2122 3. instruct flask to use the right application2324 export FLASK_APP="flaskr.factory:create_app()"2526 4. initialize the database with this command:2728 flask initdb2930 5. now you can run flaskr:3132 flask run3334 the application will greet you on35 http://localhost:5000/3637 ~ Is it tested?3839 You betcha. Run `python setup.py test` to see40 the tests pass.
deleted:examples/flaskr/setup.cfg-2 removed
1[aliases]2test=pytest
deleted:examples/flaskr/setup.py-27 removed
1# -*- coding: utf-8 -*-2"""3 Flaskr Tests4 ~~~~~~~~~~~~56 Tests the Flaskr application.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112from setuptools import setup, find_packages1314setup(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 };1516 $('a#calculate').bind('click', submit_form);1718 $('input[type=text]').bind('keydown', function(e) {19 if (e.keyCode == 13) {20 submit_form(e);21 }22 });2324 $('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 ~~~~~~~~~~~~~~56 A simple application that shows how Flask and jQuery get along.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112from flask import Flask, jsonify, render_template, request13app = Flask(__name__)141516@app.route('/_add_numbers')17def 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)222324@app.route('/')25def index():26 return render_template('index.html')2728if __name__ == '__main__':29 app.run()
deleted:examples/minitwit/minitwit/static/style.css-178 removed
1body {2 background: #CAECE9;3 font-family: 'Trebuchet MS', sans-serif;4 font-size: 14px;5}67a {8 color: #26776F;9}1011a:hover {12 color: #333;13}1415input[type="text"],16input[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}2627input[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}3839div.page {40 background: white;41 border: 1px solid #6ECCC4;42 width: 700px;43 margin: 30px auto;44}4546div.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}5556div.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}6566div.page div.navigation a {67 color: #444;68 font-weight: bold;69}7071div.page h2 {72 margin: 0 0 15px 0;73 color: #105751;74 text-shadow: 0 1px 2px #ccc;75}7677div.page div.body {78 padding: 10px;79}8081div.page div.footer {82 background: #eee;83 color: #888;84 padding: 5px 10px;85 font-size: 12px;86}8788div.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}9697div.page ul.messages {98 list-style: none;99 margin: 0;100 padding: 0;101}102103div.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}112113div.page ul.messages p {114 margin: 0;115}116117div.page ul.messages li img {118 float: left;119 padding: 0 10px 0 0;120}121122div.page ul.messages li small {123 font-size: 0.9em;124 color: #888;125}126127div.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}135136div.page div.twitbox h3 {137 margin: 0;138 font-size: 1em;139 color: #2C7E76;140}141142div.page div.twitbox p {143 margin: 0;144}145146div.page div.twitbox input[type="text"] {147 width: 585px;148}149150div.page div.twitbox input[type="submit"] {151 width: 70px;152 margin-left: 5px;153}154155ul.flashes {156 list-style: none;157 margin: 10px 10px 0 10px;158 padding: 0;159}160161ul.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}169170div.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 &mdash; 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>&mdash; {{ 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
1from .minitwit import app
deleted:examples/minitwit/minitwit/minitwit.py-256 removed
1# -*- coding: utf-8 -*-2"""3 MiniTwit4 ~~~~~~~~56 A microblogging application written with Flask and sqlite3.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112import time13from sqlite3 import dbapi2 as sqlite314from hashlib import md515from datetime import datetime16from flask import Flask, request, session, url_for, redirect, \17 render_template, abort, g, flash, _app_ctx_stack18from werkzeug import check_password_hash, generate_password_hash192021# configuration22DATABASE = '/tmp/minitwit.db'23PER_PAGE = 3024DEBUG = True25SECRET_KEY = b'_5#y2L"F4Q8z\n\xec]/'2627# create our little application :)28app = Flask('minitwit')29app.config.from_object(__name__)30app.config.from_envvar('MINITWIT_SETTINGS', silent=True)313233def 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_db424344@app.teardown_appcontext45def 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()505152def 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()585960@app.cli.command('initdb')61def initdb_command():62 """Creates the database tables."""63 init_db()64 print('Initialized the database.')656667def 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 rv727374def 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 None798081def format_datetime(timestamp):82 """Format a timestamp for display."""83 return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d @ %H:%M')848586def 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)909192@app.before_request93def 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)9899100@app.route('/')101def 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]))116117118@app.route('/public')119def 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]))125126127@app.route('/<username>')128def 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)146147148@app.route('/<username>/follow')149def 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))162163164@app.route('/<username>/unfollow')165def 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))178179180@app.route('/add_message', methods=['POST'])181def 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'))193194195@app.route('/login', methods=['GET', 'POST'])196def 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)214215216@app.route('/register', methods=['GET', 'POST'])217def 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)244245246@app.route('/logout')247def 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'))252253254# add some filters to jinja255app.jinja_env.filters['datetimeformat'] = format_datetime256app.jinja_env.filters['gravatar'] = gravatar_url
deleted:examples/minitwit/minitwit/schema.sql-21 removed
1drop table if exists user;2create 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);89drop table if exists follower;10create table follower (11 who_id integer,12 whom_id integer13);1415drop table if exists message;16create 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 ~~~~~~~~~~~~~~56 Tests the MiniTwit application.78 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112import os13import tempfile14import pytest15from minitwit import minitwit161718@pytest.fixture19def 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()2425 yield client2627 os.close(db_fd)28 os.unlink(minitwit.app.config['DATABASE'])293031def 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)434445def login(client, username, password):46 """Helper function to login"""47 return client.post('/login', data={48 'username': username,49 'password': password50 }, follow_redirects=True)515253def 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)575859def logout(client):60 """Helper function to logout"""61 return client.get('/logout', follow_redirects=True)626364def 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 rv717273def 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.data888990def 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.data100101102def 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'&lt;test message 2&gt;' in rv.data110111112def 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.data122123 # 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.data127128 # now let's follow foo129 rv = client.get('/foo/follow', follow_redirects=True)130 assert b'You are now following &#34;foo&#34;' in rv.data131132 # 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.data136137 # 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.data144145 # now unfollow and check if that worked146 rv = client.get('/foo/unfollow', follow_redirects=True)147 assert b'You are no longer following &#34;foo&#34;' 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.data
deleted:examples/minitwit/.gitignore-2 removed
1minitwit.db2.eggs/
deleted:examples/minitwit/MANIFEST.in-3 removed
1graft minitwit/templates2graft minitwit/static3include minitwit/schema.sql
deleted:examples/minitwit/README-39 removed
12 / MiniTwit /34 because writing todo lists is not fun567 ~ What is MiniTwit?89 A SQLite and Flask powered twitter clone1011 ~ How do I use it?1213 1. edit the configuration in the minitwit.py file or14 export an MINITWIT_SETTINGS environment variable15 pointing to a configuration file.1617 2. install the app from the root of the project directory1819 pip install --editable .2021 3. tell flask about the right application:2223 export FLASK_APP=minitwit2425 4. fire up a shell and run this:2627 flask initdb2829 5. now you can run minitwit:3031 flask run3233 the application will greet you on34 http://localhost:5000/3536 ~ Is it tested?3738 You betcha. Run the `python setup.py test` file to39 see the tests pass.
deleted:examples/minitwit/setup.cfg-2 removed
1[aliases]2test=pytest
deleted:examples/minitwit/setup.py-16 removed
1from setuptools import setup23setup(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"""3Larger App Tests4~~~~~~~~~~~~~~~~56:copyright: © 2010 by the Pallets team.7:license: BSD, see LICENSE for more details.8"""910from yourapplication import app11import pytest1213@pytest.fixture14def client():15 app.config['TESTING'] = True16 client = app.test_client()17 return client1819def test_index(client):20 rv = client.get('/')21 assert b"Hello World!" in rv.data
deleted: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"""3yourapplication4~~~~~~~~~~~~~~~56:copyright: © 2010 by the Pallets team.7:license: BSD, see LICENSE for more details.8"""910from flask import Flask11app = Flask('yourapplication')1213import yourapplication.views
deleted:examples/patterns/largerapp/yourapplication/views.py-14 removed
1# -*- coding: utf-8 -*-2"""3yourapplication.views4~~~~~~~~~~~~~~~~~~~~~56:copyright: © 2010 by the Pallets team.7:license: BSD, see LICENSE for more details.8"""910from yourapplication import app1112@app.route('/')13def index():14 return 'Hello World!'
deleted:examples/patterns/largerapp/setup.py-10 removed
1from setuptools import setup23setup(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
1html {2 font-family: sans-serif;3 background: #eee;4 padding: 1rem;5}67body {8 max-width: 960px;9 margin: 0 auto;10 background: white;11}1213h1, h2, h3, h4, h5, h6 {14 font-family: serif;15 color: #377ba8;16 margin: 1rem 0;17}1819a {20 color: #377ba8;21}2223hr {24 border: none;25 border-top: 1px solid lightgray;26}2728nav {29 background: lightgray;30 display: flex;31 align-items: center;32 padding: 0 0.5rem;33}3435nav h1 {36 flex: auto;37 margin: 0;38}3940nav h1 a {41 text-decoration: none;42 padding: 0.25rem 0.5rem;43}4445nav ul {46 display: flex;47 list-style: none;48 margin: 0;49 padding: 0;50}5152nav ul li a, nav ul li span, header .action {53 display: block;54 padding: 0.5rem;55}5657.content {58 padding: 0 1rem 1rem;59}6061.content > header {62 border-bottom: 1px solid lightgray;63 display: flex;64 align-items: flex-end;65}6667.content > header h1 {68 flex: auto;69 margin: 1rem 0 0.25rem 0;70}7172.flash {73 margin: 1em 0;74 padding: 1em;75 background: #cae6f6;76 border: 1px solid #377ba8;77}7879.post > header {80 display: flex;81 align-items: flex-end;82 font-size: 0.85em;83}8485.post > header > div:first-of-type {86 flex: auto;87}8889.post > header h1 {90 font-size: 1.5em;91 margin-bottom: 0;92}9394.post .about {95 color: slategray;96 font-style: italic;97}9899.post .body {100 white-space: pre-line;101}102103.content:last-child {104 margin-bottom: 0;105}106107.content form {108 margin: 1em 0;109 display: flex;110 flex-direction: column;111}112113.content label {114 font-weight: bold;115 margin-bottom: 0.5em;116}117118.content input, .content textarea {119 margin-bottom: 1em;120}121122.content textarea {123 min-height: 12em;124 resize: vertical;125}126127input.danger {128 color: #cc2f2e;129}130131input[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' %}23{% block header %}4 <h1>{% block title %}Log In{% endblock %}</h1>5{% endblock %}67{% 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' %}23{% block header %}4 <h1>{% block title %}Register{% endblock %}</h1>5{% endblock %}67{% 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' %}23{% block header %}4 <h1>{% block title %}New Post{% endblock %}</h1>5{% endblock %}67{% 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' %}23{% 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 %}910{% 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' %}23{% block header %}4 <h1>{% block title %}Edit "{{ post['title'] }}"{% endblock %}</h1>5{% endblock %}67{% 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
1import os23from flask import Flask456def 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 )1516 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)2223 # ensure the instance folder exists24 try:25 os.makedirs(app.instance_path)26 except OSError:27 pass2829 @app.route('/hello')30 def hello():31 return 'Hello, World!'3233 # register the database commands34 from flaskr import db35 db.init_app(app)3637 # apply the blueprints to the app38 from flaskr import auth, blog39 app.register_blueprint(auth.bp)40 app.register_blueprint(blog.bp)4142 # 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')4748 return app
added:examples/tutorial/flaskr/auth.py+108 added
1import functools23from flask import (4 Blueprint, flash, g, redirect, render_template, request, session, url_for5)6from werkzeug.security import check_password_hash, generate_password_hash78from flaskr.db import get_db910bp = Blueprint('auth', __name__, url_prefix='/auth')111213def 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'))1920 return view(**kwargs)2122 return wrapped_view232425@bp.before_app_request26def 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')3031 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()373839@bp.route('/register', methods=('GET', 'POST'))40def register():41 """Register a new user.4243 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 = None5152 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)6061 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'))7071 flash(error)7273 return render_template('auth/register.html')747576@bp.route('/login', methods=('GET', 'POST'))77def 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()8788 if user is None:89 error = 'Incorrect username.'90 elif not check_password_hash(user['password'], password):91 error = 'Incorrect password.'9293 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'))9899 flash(error)100101 return render_template('auth/login.html')102103104@bp.route('/logout')105def 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
1from flask import (2 Blueprint, flash, g, redirect, render_template, request, url_for3)4from werkzeug.exceptions import abort56from flaskr.auth import login_required7from flaskr.db import get_db89bp = Blueprint('blog', __name__)101112@bp.route('/')13def 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)222324def get_post(id, check_author=True):25 """Get a post and its author by id.2627 Checks that the id exists and optionally that the current user is28 the author.2930 :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()4243 if post is None:44 abort(404, "Post id {0} doesn't exist.".format(id))4546 if check_author and post['author_id'] != g.user['id']:47 abort(403)4849 return post505152@bp.route('/create', methods=('GET', 'POST'))53@login_required54def 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 = None6061 if not title:62 error = 'Title is required.'6364 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'))7576 return render_template('blog/create.html')777879@bp.route('/<int:id>/update', methods=('GET', 'POST'))80@login_required81def update(id):82 """Update a post if the current user is the author."""83 post = get_post(id)8485 if request.method == 'POST':86 title = request.form['title']87 body = request.form['body']88 error = None8990 if not title:91 error = 'Title is required.'9293 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'))103104 return render_template('blog/update.html', post=post)105106107@bp.route('/<int:id>/delete', methods=('POST',))108@login_required109def delete(id):110 """Delete a post.111112 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
1import sqlite323import click4from flask import current_app, g5from flask.cli import with_appcontext678def 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.Row1920 return g.db212223def close_db(e=None):24 """If this request connected to the database, close the25 connection.26 """27 db = g.pop('db', None)2829 if db is not None:30 db.close()313233def init_db():34 """Clear existing data and create new tables."""35 db = get_db()3637 with current_app.open_resource('schema.sql') as f:38 db.executescript(f.read().decode('utf8'))394041@click.command('init-db')42@with_appcontext43def init_db_command():44 """Clear existing data and create new tables."""45 init_db()46 click.echo('Initialized the database.')474849def 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.34DROP TABLE IF EXISTS user;5DROP TABLE IF EXISTS post;67CREATE TABLE user (8 id INTEGER PRIMARY KEY AUTOINCREMENT,9 username TEXT UNIQUE NOT NULL,10 password TEXT NOT NULL11);1213CREATE 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
1import os2import tempfile34import pytest5from flaskr import create_app6from flaskr.db import get_db, init_db78# read in SQL for populating test data9with open(os.path.join(os.path.dirname(__file__), 'data.sql'), 'rb') as f:10 _data_sql = f.read().decode('utf8')111213@pytest.fixture14def 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 })2324 # create the database and load test data25 with app.app_context():26 init_db()27 get_db().executescript(_data_sql)2829 yield app3031 # close and remove the temporary database32 os.close(db_fd)33 os.unlink(db_path)343536@pytest.fixture37def client(app):38 """A test client for the app."""39 return app.test_client()404142@pytest.fixture43def runner(app):44 """A test runner for the app's Click commands."""45 return app.test_cli_runner()464748class AuthActions(object):49 def __init__(self, client):50 self._client = client5152 def login(self, username='test', password='test'):53 return self._client.post(54 '/auth/login',55 data={'username': username, 'password': password}56 )5758 def logout(self):59 return self._client.get('/auth/logout')606162@pytest.fixture63def auth(client):64 return AuthActions(client)
added:examples/tutorial/tests/data.sql+8 added
1INSERT INTO user (username, password)2VALUES3 ('test', 'pbkdf2:sha256:50000$TCI4GzcX$0de171a4f4dac32e3364c7ddc7c14f3e2fa61f2d17574483f7ffbb431b4acb2f'),4 ('other', 'pbkdf2:sha256:50000$kJPKsz6N$d2d4784f1b030a9761f5ccaeeaca413f27f2ecb76d6168407af962ddce849f79');56INSERT INTO post (title, body, author_id, created)7VALUES8 ('test title', 'test' || x'0a' || 'body', 1, '2018-01-01 00:00:00');
added:examples/tutorial/tests/test_auth.py+66 added
1import pytest2from flask import g, session3from flaskr.db import get_db456def test_register(client, app):7 # test that viewing the page renders without template errors8 assert client.get('/auth/register').status_code == 200910 # 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']1516 # 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 None212223@pytest.mark.parametrize(('username', 'password', 'message'), (24 ('', '', b'Username is required.'),25 ('a', '', b'Password is required.'),26 ('test', 'test', b'already registered'),27))28def 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.data343536def test_login(client, auth):37 # test that viewing the page renders without template errors38 assert client.get('/auth/login').status_code == 2003940 # test that successful login redirects to the index page41 response = auth.login()42 assert response.headers['Location'] == 'http://localhost/'4344 # 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'505152@pytest.mark.parametrize(('username', 'password', 'message'), (53 ('a', 'test', b'Incorrect username.'),54 ('test', 'a', b'Incorrect password.'),55))56def test_login_validate_input(auth, username, password, message):57 response = auth.login(username, password)58 assert message in response.data596061def test_logout(client, auth):62 auth.login()6364 with client:65 auth.logout()66 assert 'user_id' not in session
added:examples/tutorial/tests/test_blog.py+92 added
1import pytest2from flaskr.db import get_db345def test_index(client, auth):6 response = client.get('/')7 assert b"Log In" in response.data8 assert b"Register" in response.data910 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.data161718@pytest.mark.parametrize('path', (19 '/create',20 '/1/update',21 '/1/delete',22))23def test_login_required(client, path):24 response = client.post(path)25 assert response.headers['Location'] == 'http://localhost/auth/login'262728def 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()3435 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('/').data414243@pytest.mark.parametrize('path', (44 '/2/update',45 '/2/delete',46))47def test_exists_required(client, auth, path):48 auth.login()49 assert client.post(path).status_code == 404505152def test_create(client, auth, app):53 auth.login()54 assert client.get('/create').status_code == 20055 client.post('/create', data={'title': 'created', 'body': ''})5657 with app.app_context():58 db = get_db()59 count = db.execute('SELECT COUNT(id) FROM post').fetchone()[0]60 assert count == 2616263def 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': ''})6768 with app.app_context():69 db = get_db()70 post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()71 assert post['title'] == 'updated'727374@pytest.mark.parametrize('path', (75 '/create',76 '/1/update',77))78def 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.data828384def test_delete(client, auth, app):85 auth.login()86 response = client.post('/1/delete')87 assert response.headers['Location'] == 'http://localhost/'8889 with app.app_context():90 db = get_db()91 post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()92 assert post is None
added:examples/tutorial/tests/test_db.py+28 added
1import sqlite323import pytest4from flaskr.db import get_db567def test_get_close_db(app):8 with app.app_context():9 db = get_db()10 assert db is get_db()1112 with pytest.raises(sqlite3.ProgrammingError) as e:13 db.execute('SELECT 1')1415 assert 'closed' in str(e)161718def test_init_db_command(runner, monkeypatch):19 class Recorder(object):20 called = False2122 def fake_init_db():23 Recorder.called = True2425 monkeypatch.setattr('flaskr.db.init_db', fake_init_db)26 result = runner.invoke(args=['init-db'])27 assert 'Initialized' in result.output28 assert Recorder.called
added:examples/tutorial/tests/test_factory.py+12 added
1from flaskr import create_app234def test_config():5 """Test create_app without passing test config."""6 assert not create_app().testing7 assert create_app({'TESTING': True}).testing8910def test_hello(client):11 response = client.get('/hello')12 assert response.data == b'Hello, World!'
added:examples/tutorial/.gitignore+14 added
1venv/2*.pyc3__pycache__/4instance/5.cache/6.pytest_cache/7.coverage8htmlcov/9dist/10build/11*.egg-info/12.idea/13*.swp14*~
added:examples/tutorial/LICENSE+31 added
1Copyright © 2010 by the Pallets team.23Some rights reserved.45Redistribution and use in source and binary forms of the software as6well as documentation, with or without modification, are permitted7provided that the following conditions are met:89* Redistributions of source code must retain the above copyright notice,10 this list of conditions and the following disclaimer.1112* 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.1516* 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.1920THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE COPYRIGHT HOLDERS AND21CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,22BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND23FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE24COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,25INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT26NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF27USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON28ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT29(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF30THIS SOFTWARE AND DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF31SUCH DAMAGE.
added:examples/tutorial/MANIFEST.in+6 added
1include LICENSE2include flaskr/schema.sql3graft flaskr/static4graft flaskr/templates5graft tests6global-exclude *.pyc
added:examples/tutorial/README.rst+76 added
1Flaskr2======34The basic blog app built in the Flask `tutorial`_.56.. _tutorial: http://flask.pocoo.org/docs/tutorial/789Install10-------1112**Be sure to use the same version of the code as the version of the docs13you're reading.** You probably want the latest tagged version, but the14default Git version is the master branch. ::1516 # 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/tutorial2324Create a virtualenv and activate it::2526 python3 -m venv venv27 . venv/bin/activate2829Or on Windows cmd::3031 py -3 -m venv venv32 venv\Scripts\activate.bat3334Install Flaskr::3536 pip install -e .3738Or if you are using the master branch, install Flask from source before39installing Flaskr::4041 pip install -e ../..42 pip install -e .434445Run46---4748::4950 export FLASK_APP=flaskr51 export FLASK_ENV=development52 flask run5354Or on Windows cmd::5556 set FLASK_APP=flaskr57 set FLASK_ENV=development58 flask run5960Open http://127.0.0.1:5000 in a browser.616263Test64----6566::6768 pip install pytest69 pytest7071Run with coverage report::7273 pip install pytest coverage74 coverage run -m pytest75 coverage report76 coverage html # open htmlcov/index.html in a browser
added:examples/tutorial/setup.cfg+13 added
1[metadata]2license_file = LICENSE34[bdist_wheel]5universal = False67[tool:pytest]8testpaths = tests910[coverage:run]11branch = True12source =13 flaskr
added:examples/tutorial/setup.py+23 added
1import io23from setuptools import find_packages, setup45with io.open('README.rst', 'rt', encoding='utf8') as f:6 readme = f.read()78setup(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 lines
74.. _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-fork8081Start coding82~~~~~~~~~~~~
98 unmodified lines
modified:tox.ini+1 added-3 removed
29 unmodified lines
30 simplejson: simplejson3132commands =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 -q3536 # pytest-cov doesn't seem to play nice with -p37 coverage run -p -m pytest tests examples38
24 unmodified lines