First part of the tutorial. Many explanations missing but it's a start.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent c4f5c2f · Browse files · 9 files·+394 added−14 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+394 added−14 removed
- other:+394 added−14 removed
Provenance
- Commit
1246f40- Tree
01d6e3c- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
c4f5c2f
9 files changed+394 added−14 removed
added:docs/_static/flaskr.pngbinary
A binary file, added.
modified:docs/_themes/flasky/static/flasky.css_t+12 added
179 unmodified lines180 181 div.body p, div.body dd, div.body li {182 line-height: 1.5em;183 }184+185+div.admonition {186+ border: 1px solid #ddd;187+ background: white;188+ -webkit-box-shadow: 2px 2px 1px #d8d8d8;189+ -moz-box-shadow: 2px 2px 1px #d8d8d8;190+}191 192 div.admonition p.admonition-title + p {193 display: inline;194 }33 unmodified lines228 font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace;229 font-size: 0.9em;230 }231 232+img.screenshot {233+ -webkit-box-shadow: 4px 4px 3px #cdcdcd;234+ -moz-box-shadow: 4px 4px 3px #cdcdcd;235+}236+237 tt.descname, tt.descclassname {238 font-size: 0.95em;239 -webkit-box-shadow: none;240 -moz-box-shadow: none;76 unmodified linesmodified:docs/index.rst+6 added-3 removed
5 unmodified lines6 :align: right7 8 Welcome to Flask's documentation. This documentation is divided in9 different parts. I would suggest to get started with the10-:ref:`installation` and then heading over to the :ref:`quickstart`. If11-you want to dive into all the internal parts of Flask, check out the12-:ref:`api` documentation. Common patterns are described in the10+:ref:`installation` and then heading over to the :ref:`quickstart`.11+Besides the quickstart there is also a more detailed :ref:`tutorial` that12+shows how to create a complete (albeit small) application with Flask. If13+you rather want to dive into all the internal parts of Flask, check out14+the :ref:`api` documentation. Common patterns are described in the15 :ref:`patterns` section.16 17 .. toctree::18 :maxdepth: 219 20 foreword21 installation22 quickstart23+ tutorial24 patterns25 api26 deploying27 testing1 unmodified linemodified:docs/quickstart.rst+13 added
52 unmodified lines53 the Python interpreter and not used as imported module.54 55 To stop the server, hit control-C.56 57+.. admonition:: Troubleshooting58 59+ The browser is unable to access the server? Sometimes this is60+ unfortunately caused by broken IPv6 support in your operating system,61+ browser or a combination. For example on Snow Leopard Google Chrome is62+ known to exhibit this behaviour.63+64+ If the browser does not load up the page, you can change the `app.run`65+ call to force IPv4 usage::66+67+ if __name__ == '__main__':68+ app.run(host='127.0.0.1')69+70+71 Debug Mode72 ----------73 74 Now that :meth:`~flask.Flask.run` method is nice to start a local542 unmodified linesadded:docs/tutorial.rst+354 added
1+.. _tutorial:2+3+Tutorial4+========5+6+You want to develop an application with Python and Flask? Here you have7+the chance to learn that by example. In this tutorial we will create a8+simple microblog application. It only supports one user that can create9+text-only entries and there are no feeds or comments, but it still10+features everything you need to get started. We will use Flask and SQLite11+as database which comes out of the box with Python, so there is nothing12+else you need.13+14+If you want the full sourcecode in advance or for comparison, check out15+the `example source`_.16+17+.. _example source:18+ http://github.com/mitsuhiko/flask/tree/master/examples/flaskr/19+20+Introducing Flaskr21+------------------22+23+We will call our blogging application flaskr here, feel free to chose a24+less web-2.0-ish name ;) Basically we want it to do the following things:25+26+1. let the user sign in and out with credentials specified in the27+ configuration. Only one user is supported.28+2. 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.31+3. 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.33+34+Here a screenshot from the final application:35+36+.. image:: _static/flaskr.png37+ :align: center38+ :class: screenshot39+ :alt: screenshot of the final application40+41+Step 0: Creating The Folders42+----------------------------43+44+Before we get started, let's create the folders needed for this45+application::46+47+ /flaskr48+ /static49+ /templates50+51+The `flaskr` folder is not a python package, but just something where we52+drop our files. Directly into this folder we will then put our database53+schema as well as main module in the following steps.54+55+Step 1: Database Schema56+-----------------------57+58+First we want to create the database schema. For this application only a59+single table is needed and we only want to support SQLite so that is quite60+easy. Just put the following contents into a file named `schema.sql` in61+the just created `flaskr` folder:62+63+.. sourcecode:: sql64+65+ 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+ );71+72+This schema consists of a single table called `entries` and each row in73+this table has an `id`, a `title` and a `text`. The `id` is an74+automatically incrementing integer and a primary key, the other two are75+strings that must not be null.76+77+Step 2: Application Setup Code78+------------------------------79+80+Now that we have the schema in place we can create the application module.81+Let's call it `flaskr.py` inside the `flaskr` folder. For starters we82+will add the imports we will need as well as the config section::83+84+ # all the imports85+ import sqlite386+ from flask import Flask, request, session, g, redirect, url_for, abort, \87+ render_template, flash88+89+ # configuration90+ DATABASE = '/tmp/flaskr.db'91+ DEBUG = True92+ SECRET_KEY = 'development key'93+ USERNAME = 'admin'94+ PASSWORD = 'default'95+96+The `with_statement` and :func:`~contextlib.closing` function are used to97+make dealing with the database connection easier later on for setting up98+the initial database. Next we can create our actual application and99+initialize it with the config::100+101+ # create our little application :)102+ app = Flask(__name__)103+ app.secret_key = SECRET_KEY104+ app.debug = DEBUG105+106+We can also add a method to easily connect to the database sepcified::107+108+ def connect_db():109+ return sqlite3.connect(DATABASE)110+111+Finally we just add a line to the bottom of the file that fires up the112+server if we run that file as standalone application::113+114+ if __name__ == '__main__':115+ app.run()116+117+.. admonition:: Troubleshooting118+119+ If you notice later that the browser cannot connect to the server120+ during development, you might want to try this line instead::121+122+ app.run(host='127.0.0.1')123+124+ 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.127+128+With that out of the way you should be able to start up the application129+without problems. When you head over to the server you will get an 404130+page not found error because we don't have any views yet. But we will131+focus on that a little later. First we should get the database working.132+133+Step 3: Creating The Database134+-----------------------------135+136+Flaskr is a database powered application as outlined earlier, and more137+precisely, an application powered by a relational database system. Such138+systems need a schema that tells them how to store that information. So139+before starting the server for the first time it's important to create140+that schema.141+142+Such a schema can be created by piping the `schema.sql` file into the143+`sqlite3` command as follows::144+145+ sqlite3 /tmp/flaskr.db < schema.sql146+147+The downside of this is that it requires the sqlite3 command to be148+installed which is not necessarily the case on every system. Also one has149+to provide the path to the database there which leaves some place for150+errors. It's a good idea to add a function that initializes the database151+for you to the application.152+153+If you want to do that, you first have to import the154+:func:`contextlib.closing` function from the contextlib package. If you155+want to use Python 2.5 it's also necessary to enable the `with` statement156+first (`__future__` imports must be the very first import)::157+158+ from __future__ import with_statement159+ from contextlib import closing160+161+Next we can create a function called `init_db` that initializes the162+database::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()169+170+Now it is possible to create a database by starting up a Python shell and171+importing and calling that function::172+173+>>> from flaskr import init_db174+>>> init_db()175+176+The :meth:`~flask.Flask.open_resource` function opens a file from the177+resource location (your flaskr folder) and allows you to read from it. We178+are using this here to execute a script on the database connection.179+180+When 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 to182+execute a complete script. Finally we only have to commit the changes and183+close the transaction.184+185+Step 4: Request Database Connections186+------------------------------------187+188+Now we know how we can open database connections and use them for scripts,189+but how can we elegantly do that for requests? We will need the database190+connection in all our functions so it makes sense to initialize them191+before each request and shut them down afterwards.192+193+Flask allows us to do that with the :meth:`~flask.Flask.request_init` and194+:meth:`~flask.Flask.request_shutdown` decorators::195+196+ @app.request_init197+ def before_request():198+ g.db = connect_db()199+200+ @app.request_shutdown201+ def after_request(response):202+ g.db.close()203+ return response204+205+Functions marked with :meth:`~flask.Flask.request_init` are called before206+a request and passed no arguments, functions marked with207+:meth:`~flask.Flask.request_shutdown` are called after a request and208+passed the response that will be sent to the client. They have to return209+that response object or a different one. In this case we just return it210+unchanged.211+212+We store our current database connection on the special :data:`~flask.g`213+object that flask provides for us. This object stores information for one214+request only and is available from within each function. Never store such215+things on other objects because this would not work with threaded216+environments. That special :data:`~flask.g` object does some magic behind217+the scenes to ensure it does the right thing.218+219+Step 5: The View Functions220+--------------------------221+222+Now that the database connections are working we can start writing the223+view functions. We will need for of them:224+225+Show Entries226+````````````227+228+This view shows all the entries stored in the database::229+230+ @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)235+236+Add New Entry237+`````````````238+239+This view lets the user add new entries if he's logged in. This only240+responds to `POST` requests, the actual form is shown on the241+`show_entries` page::242+243+ @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'))252+253+Login and Logout254+````````````````255+256+These functions are used to sign the user in and out::257+258+ @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)271+272+ @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'))277+278+Step 6: The Templates279+---------------------280+281+Now we should start working on the templates. If we request the URLs now282+we would only get an exception that Flask cannot find the templates.283+284+Put the following templates into the `templates` folder:285+286+layout.html287+```````````288+289+.. sourcecode:: html+jinja290+291+ <!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>308+309+show_entries.html310+`````````````````311+312+.. sourcecode:: html+jinja313+314+ {% 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 %}335+336+login.html337+``````````338+339+.. sourcecode:: html+jinja340+341+ {% 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 %}modified:examples/flaskr/static/style.css+5 added-4 removed
1234567678910111112121314151617body { font-family: sans-serif; background: #eee; }a, h1, h2 { color: #377BA8; }h1, h2 { font-family: 'Georgia', serif; margin: 0; }h1 { border-bottom: 2px solid #eee; }h2 { font-size: 1.2em; }div.metanav { text-align: right; font-size: 0.8em; background: #fafafa; padding: 0.3em; margin-bottom: 1em; }
div.page { margin: 2em auto; width: 35em; border: 5px solid #ccc; padding: 0.8em; background: white; }ul.entries { list-style: none; margin: 0; padding: 0; }ul.entries li { margin: 0.8em 1.2em; }ul.entries li h2 { margin-left: -1em; }div.page { margin: 2em auto; width: 35em; border: 5px solid #ccc; padding: 0.8em; background: white; }form.add-entry { font-size: 0.9em; border-bottom: 1px solid #ccc; }form.add-entry dl { font-weight: bold; }div.metanav { text-align: right; font-size: 0.8em; background: #fafafa; padding: 0.3em; margin-bottom: 1em; }div.flash { background: #CEE5F5; padding: 0.5em; border: 1px solid #AACBE2; }p.error { background: #F0D6D6; padding: 0.5em; }modified:examples/flaskr/templates/layout.html+1 added-1 removed
2 unmodified lines3456778910116 unmodified lines2 unmodified lines<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}"><div class=page> <h1>Flaskr</h1> <div class=metanav> {% if not g.logged_in %} {% if not session.logged_in %} <a href="{{ url_for('login') }}">log in</a> {% else %} <a href="{{ url_for('logout') }}">log out</a> {% endif %}6 unmodified linesmodified:examples/flaskr/templates/login.html+1 added-1 removed
5 unmodified lines67891010111213145 unmodified lines <dl> <dt>Username: <dd><input type=text name=username> <dt>Password: <dd><input type=passowrd name=password> <dd><input type=password name=password> <dd><input type=submit value=Login> </dl> </form>{% endblock %}modified:examples/flaskr/flaskr.py+2 added-5 removed
41 unmodified lines42 43 44 @app.request_init45 def before_request():46- """Make sure we are connected to the database each request. Also47- set `g.logged_in` to `True` if we are logged in.48- """46+ """Make sure we are connected to the database each request."""47 g.db = connect_db()50- g.logged_in = session.get('logged_in', False)48 49 50 @app.request_shutdown51 def after_request(response):10 unmodified lines62 63 64 @app.route('/add', methods=['POST'])65 def add_entry():69- if not g.logged_in:66+ if not session.get('logged_in'):67 abort(401)68 g.db.execute('insert into entries (title, text) values (?, ?)',69 [request.form['title'], request.form['text']])70 g.db.commit()28 unmodified lines