Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 98 lines (75 sloc) 2.649 kB
c33675f @mitsuhiko Added mini blogging application as Flask example.
authored
1 # -*- coding: utf-8 -*-
2 """
3 Flaskr
4 ~~~~~~
5
6 A microblog example application written as Flask tutorial with
7 Flask and sqlite3.
8
9 :copyright: (c) 2010 by Armin Ronacher.
10 :license: BSD, see LICENSE for more details.
11 """
12 from __future__ import with_statement
1640679 @mitsuhiko Updated examples to work with pypy which has a incomplete sqlite3 in …
authored
13 from sqlite3 import dbapi2 as sqlite3
c33675f @mitsuhiko Added mini blogging application as Flask example.
authored
14 from contextlib import closing
15 from flask import Flask, request, session, g, redirect, url_for, abort, \
16 render_template, flash
17
18 # configuration
19 DATABASE = '/tmp/flaskr.db'
20 DEBUG = True
21 SECRET_KEY = 'development key'
22 USERNAME = 'admin'
23 PASSWORD = 'default'
24
25 # create our little application :)
26 app = Flask(__name__)
dfecc86 @mitsuhiko Ported examples over to new config. documented upgrading
authored
27 app.config.from_object(__name__)
28 app.config.from_envvar('FLASKR_SETTINGS', silent=True)
c33675f @mitsuhiko Added mini blogging application as Flask example.
authored
29
30
31 def connect_db():
32 """Returns a new connection to the database."""
dfecc86 @mitsuhiko Ported examples over to new config. documented upgrading
authored
33 return sqlite3.connect(app.config['DATABASE'])
c33675f @mitsuhiko Added mini blogging application as Flask example.
authored
34
35
36 def init_db():
37 """Creates the database tables."""
38 with closing(connect_db()) as db:
39 with app.open_resource('schema.sql') as f:
40 db.cursor().executescript(f.read())
41 db.commit()
42
43
fb2d2e4 @mitsuhiko request_init -> before_request and request_shutdown -> after_request
authored
44 @app.before_request
c33675f @mitsuhiko Added mini blogging application as Flask example.
authored
45 def before_request():
1246f40 @mitsuhiko First part of the tutorial. Many explanations missing but it's a start.
authored
46 """Make sure we are connected to the database each request."""
c33675f @mitsuhiko Added mini blogging application as Flask example.
authored
47 g.db = connect_db()
48
49
b51ecd7 @mitsuhiko Updated examples
authored
50 @app.teardown_request
51 def teardown_request(exception):
c33675f @mitsuhiko Added mini blogging application as Flask example.
authored
52 """Closes the database again at the end of the request."""
53 g.db.close()
54
55
56 @app.route('/')
57 def show_entries():
58 cur = g.db.execute('select title, text from entries order by id desc')
59 entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]
60 return render_template('show_entries.html', entries=entries)
61
62
63 @app.route('/add', methods=['POST'])
64 def add_entry():
1246f40 @mitsuhiko First part of the tutorial. Many explanations missing but it's a start.
authored
65 if not session.get('logged_in'):
c33675f @mitsuhiko Added mini blogging application as Flask example.
authored
66 abort(401)
67 g.db.execute('insert into entries (title, text) values (?, ?)',
68 [request.form['title'], request.form['text']])
69 g.db.commit()
70 flash('New entry was successfully posted')
71 return redirect(url_for('show_entries'))
72
73
74 @app.route('/login', methods=['GET', 'POST'])
75 def login():
76 error = None
77 if request.method == 'POST':
dfecc86 @mitsuhiko Ported examples over to new config. documented upgrading
authored
78 if request.form['username'] != app.config['USERNAME']:
c33675f @mitsuhiko Added mini blogging application as Flask example.
authored
79 error = 'Invalid username'
dfecc86 @mitsuhiko Ported examples over to new config. documented upgrading
authored
80 elif request.form['password'] != app.config['PASSWORD']:
c33675f @mitsuhiko Added mini blogging application as Flask example.
authored
81 error = 'Invalid password'
82 else:
83 session['logged_in'] = True
84 flash('You were logged in')
85 return redirect(url_for('show_entries'))
86 return render_template('login.html', error=error)
87
88
89 @app.route('/logout')
90 def logout():
91 session.pop('logged_in', None)
92 flash('You were logged out')
93 return redirect(url_for('show_entries'))
94
95
96 if __name__ == '__main__':
97 app.run()
Something went wrong with that request. Please try again.