Skip to content
Myr

tutorial.rst

This file

Path

docs/tutorial.rst

354 lines · 11.7 KiB

Last changed by

First part of the tutorial. Many explanations missing but it's a start.Armin Ronacherbefore adoption1246f40

History of this file

Take it

1.. _tutorial:23Tutorial4========56You want to develop an application with Python and Flask?  Here you have7the chance to learn that by example.  In this tutorial we will create a8simple microblog application.  It only supports one user that can create9text-only entries and there are no feeds or comments, but it still10features everything you need to get started.  We will use Flask and SQLite11as database which comes out of the box with Python, so there is nothing12else you need.1314If you want the full sourcecode in advance or for comparison, check out15the `example source`_.1617.. _example source:18   http://github.com/mitsuhiko/flask/tree/master/examples/flaskr/1920Introducing Flaskr21------------------2223We will call our blogging application flaskr here, feel free to chose a24less web-2.0-ish name ;)  Basically we want it to do the following things:25261. let the user sign in and out with credentials specified in the27   configuration.  Only one user is supported.282. when the user is logged in he or she can add new entries to the page29   consisting of a text-only title and some HTML for the text.  This HTML30   is not sanitized because we trust the user here.313. the page shows all entries so far in reverse order (newest on top) and32   the user can add new ones from there if logged in.3334Here a screenshot from the final application:3536.. image:: _static/flaskr.png37   :align: center38   :class: screenshot39   :alt: screenshot of the final application4041Step 0: Creating The Folders42----------------------------4344Before we get started, let's create the folders needed for this45application::4647    /flaskr48        /static49        /templates5051The `flaskr` folder is not a python package, but just something where we52drop our files.  Directly into this folder we will then put our database53schema as well as main module in the following steps.5455Step 1: Database Schema56-----------------------5758First we want to create the database schema.  For this application only a59single table is needed and we only want to support SQLite so that is quite60easy.  Just put the following contents into a file named `schema.sql` in61the just created `flaskr` folder:6263.. sourcecode:: sql6465    drop table if exists entries;66    create table entries (67      id integer primary key autoincrement,68      title string not null,69      text string not null70    );7172This schema consists of a single table called `entries` and each row in73this table has an `id`, a `title` and a `text`.  The `id` is an74automatically incrementing integer and a primary key, the other two are75strings that must not be null.7677Step 2: Application Setup Code78------------------------------7980Now that we have the schema in place we can create the application module.81Let's call it `flaskr.py` inside the `flaskr` folder.  For starters we82will add the imports we will need as well as the config section::8384    # all the imports85    import sqlite386    from flask import Flask, request, session, g, redirect, url_for, abort, \87         render_template, flash8889    # configuration90    DATABASE = '/tmp/flaskr.db'91    DEBUG = True92    SECRET_KEY = 'development key'93    USERNAME = 'admin'94    PASSWORD = 'default'9596The `with_statement` and :func:`~contextlib.closing` function are used to97make dealing with the database connection easier later on for setting up98the initial database.  Next we can create our actual application and99initialize it with the config::100101    # create our little application :)102    app = Flask(__name__)103    app.secret_key = SECRET_KEY104    app.debug = DEBUG105106We can also add a method to easily connect to the database sepcified::107108    def connect_db():109        return sqlite3.connect(DATABASE)110111Finally we just add a line to the bottom of the file that fires up the112server if we run that file as standalone application::113114    if __name__ == '__main__':115        app.run()116117.. admonition:: Troubleshooting118119   If you notice later that the browser cannot connect to the server120   during development, you might want to try this line instead::121122       app.run(host='127.0.0.1')123124   In a nutshell: Werkzeug starts up as IPv6 on many operating systems by125   default and not every browser is happy with that.  This forces IPv4126   usage.127128With that out of the way you should be able to start up the application129without problems.  When you head over to the server you will get an 404130page not found error because we don't have any views yet.  But we will131focus on that a little later.  First we should get the database working.132133Step 3: Creating The Database134-----------------------------135136Flaskr is a database powered application as outlined earlier, and more137precisely, an application powered by a relational database system.  Such138systems need a schema that tells them how to store that information. So139before starting the server for the first time it's important to create140that schema.141142Such a schema can be created by piping the `schema.sql` file into the143`sqlite3` command as follows::144145    sqlite3 /tmp/flaskr.db < schema.sql146147The downside of this is that it requires the sqlite3 command to be148installed which is not necessarily the case on every system.  Also one has149to provide the path to the database there which leaves some place for150errors.  It's a good idea to add a function that initializes the database151for you to the application.152153If you want to do that, you first have to import the154:func:`contextlib.closing` function from the contextlib package.  If you155want to use Python 2.5 it's also necessary to enable the `with` statement156first (`__future__` imports must be the very first import)::157158    from __future__ import with_statement159    from contextlib import closing160161Next we can create a function called `init_db` that initializes the162database::163    164    def init_db():165        with closing(connect_db()) as db:166            with app.open_resource('schema.sql') as f:167                db.cursor().executescript(f.read())168            db.commit()169170Now it is possible to create a database by starting up a Python shell and171importing and calling that function::172173>>> from flaskr import init_db174>>> init_db()175176The :meth:`~flask.Flask.open_resource` function opens a file from the177resource location (your flaskr folder) and allows you to read from it.  We178are using this here to execute a script on the database connection.179180When we connect to a database we get a connection object (here called181`db`) that can give us a cursor.  On that cursor there is a method to182execute a complete script.  Finally we only have to commit the changes and183close the transaction.184185Step 4: Request Database Connections186------------------------------------187188Now we know how we can open database connections and use them for scripts,189but how can we elegantly do that for requests?  We will need the database190connection in all our functions so it makes sense to initialize them191before each request and shut them down afterwards.192193Flask allows us to do that with the :meth:`~flask.Flask.request_init` and194:meth:`~flask.Flask.request_shutdown` decorators::195196    @app.request_init197    def before_request():198        g.db = connect_db()199200    @app.request_shutdown201    def after_request(response):202        g.db.close()203        return response204205Functions marked with :meth:`~flask.Flask.request_init` are called before206a request and passed no arguments, functions marked with207:meth:`~flask.Flask.request_shutdown` are called after a request and208passed the response that will be sent to the client.  They have to return209that response object or a different one.  In this case we just return it210unchanged.211212We store our current database connection on the special :data:`~flask.g`213object that flask provides for us.  This object stores information for one214request only and is available from within each function.  Never store such215things on other objects because this would not work with threaded216environments.  That special :data:`~flask.g` object does some magic behind217the scenes to ensure it does the right thing.218219Step 5: The View Functions220--------------------------221222Now that the database connections are working we can start writing the223view functions.  We will need for of them:224225Show Entries226````````````227228This view shows all the entries stored in the database::229230    @app.route('/')231    def show_entries():232        cur = g.db.execute('select title, text from entries order by id desc')233        entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]234        return render_template('show_entries.html', entries=entries)235236Add New Entry237`````````````238239This view lets the user add new entries if he's logged in.  This only240responds to `POST` requests, the actual form is shown on the241`show_entries` page::242243    @app.route('/add', methods=['POST'])244    def add_entry():245        if not session.get('logged_in'):246            abort(401)247        g.db.execute('insert into entries (title, text) values (?, ?)',248                     [request.form['title'], request.form['text']])249        g.db.commit()250        flash('New entry was successfully posted')251        return redirect(url_for('show_entries'))252253Login and Logout254````````````````255256These functions are used to sign the user in and out::257258    @app.route('/login', methods=['GET', 'POST'])259    def login():260        error = None261        if request.method == 'POST':262            if request.form['username'] != USERNAME:263                error = 'Invalid username'264            elif request.form['password'] != PASSWORD:265                error = 'Invalid password'266            else:267                session['logged_in'] = True268                flash('You were logged in')269                return redirect(url_for('show_entries'))270        return render_template('login.html', error=error)271272    @app.route('/logout')273    def logout():274        session.pop('logged_in', None)275        flash('You were logged out')276        return redirect(url_for('show_entries'))277278Step 6: The Templates279---------------------280281Now we should start working on the templates.  If we request the URLs now282we would only get an exception that Flask cannot find the templates.283284Put the following templates into the `templates` folder:285286layout.html287```````````288289.. sourcecode:: html+jinja290291    <!doctype html>292    <title>Flaskr</title>293    <link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">294    <div class=page>295      <h1>Flaskr</h1>296      <div class=metanav>297      {% if not session.logged_in %}298        <a href="{{ url_for('login') }}">log in</a>299      {% else %}300        <a href="{{ url_for('logout') }}">log out</a>301      {% endif %}302      </div>303      {% for message in get_flashed_messages() %}304        <div class=flash>{{ message }}</div>305      {% endfor %}306      {% block body %}{% endblock %}307    </div>308309show_entries.html310`````````````````311312.. sourcecode:: html+jinja313314    {% extends "layout.html" %}315    {% block body %}316      {% if g.logged_in %}317        <form action="{{ url_for('add_entry') }}" method=post class=add-entry>318          <dl>319            <dt>Title:320            <dd><input type=text size=30 name=title>321            <dt>Text:322            <dd><textarea name=text rows=5 cols=40></textarea>323            <dd><input type=submit value=Share>324          </dl>325        </form>326      {% endif %}327      <ul class=entries>328      {% for entry in entries %}329        <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}330      {% else %}331        <li><em>Unbelievable.  No entries here so far</em>332      {% endfor %}333      </ul>334    {% endblock %}335336login.html337``````````338339.. sourcecode:: html+jinja340341    {% extends "layout.html" %}342    {% block body %}343      <h2>Login</h2>344      {% if error %}<p class=error><strong>Error:</strong> {{ error }}{% endif %}345      <form action="{{ url_for('login') }}" method=post>346        <dl>347          <dt>Username:348          <dd><input type=text name=username>349          <dt>Password:350          <dd><input type=password name=password>351          <dd><input type=submit value=Login>352        </dl>353      </form>354    {% endblock %}