Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 99 lines (76 sloc) 2.639 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
13 import sqlite3
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
fb2d2e4 @mitsuhiko request_init -> before_request and request_shutdown -> after_request
authored
50 @app.after_request
c33675f @mitsuhiko Added mini blogging application as Flask example.
authored
51 def after_request(response):
52 """Closes the database again at the end of the request."""
53 g.db.close()
54 return response
55
56
57 @app.route('/')
58 def show_entries():
59 cur = g.db.execute('select title, text from entries order by id desc')
60 entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]
61 return render_template('show_entries.html', entries=entries)
62
63
64 @app.route('/add', methods=['POST'])
65 def add_entry():
1246f40 @mitsuhiko First part of the tutorial. Many explanations missing but it's a start.
authored
66 if not session.get('logged_in'):
c33675f @mitsuhiko Added mini blogging application as Flask example.
authored
67 abort(401)
68 g.db.execute('insert into entries (title, text) values (?, ?)',
69 [request.form['title'], request.form['text']])
70 g.db.commit()
71 flash('New entry was successfully posted')
72 return redirect(url_for('show_entries'))
73
74
75 @app.route('/login', methods=['GET', 'POST'])
76 def login():
77 error = None
78 if request.method == 'POST':
dfecc86 @mitsuhiko Ported examples over to new config. documented upgrading
authored
79 if request.form['username'] != app.config['USERNAME']:
c33675f @mitsuhiko Added mini blogging application as Flask example.
authored
80 error = 'Invalid username'
dfecc86 @mitsuhiko Ported examples over to new config. documented upgrading
authored
81 elif request.form['password'] != app.config['PASSWORD']:
c33675f @mitsuhiko Added mini blogging application as Flask example.
authored
82 error = 'Invalid password'
83 else:
84 session['logged_in'] = True
85 flash('You were logged in')
86 return redirect(url_for('show_entries'))
87 return render_template('login.html', error=error)
88
89
90 @app.route('/logout')
91 def logout():
92 session.pop('logged_in', None)
93 flash('You were logged out')
94 return redirect(url_for('show_entries'))
95
96
97 if __name__ == '__main__':
98 app.run()
Something went wrong with that request. Please try again.