Skip to content
Myr

Added mini blogging application as Flask example.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

This should become the tutorial.

authored by Armin Ronacher · committed by Armin Ronacher · parent 2d9bb69 · Browse files · 7 files+241 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+241 added−0 removed

  • other:+241 added−0 removed

7 files+241 added−0 removed

added:examples/flaskr/static/style.css+16 added
added:examples/flaskr/templates/layout.html+17 added
added:examples/flaskr/templates/login.html+14 added
added:examples/flaskr/templates/show_entries.html+21 added
added:examples/flaskr/flaskr_tests.py+64 added
1# -*- coding: utf-8 -*-2"""3 Flaskr Tests4 ~~~~~~~~~~~~56 Tests the Flaskr application.78 :copyright: (c) 2010 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import flaskr12import unittest13import tempfile141516class FlaskrTestCase(unittest.TestCase):1718 def setUp(self):19 """Before each test, set up a blank database"""20 self.db = tempfile.NamedTemporaryFile()21 self.app = flaskr.app.test_client()22 flaskr.DATABASE = self.db.name23 flaskr.init_db()2425 def login(self, username, password):26 return self.app.post('/login', data=dict(27 username=username,28 password=password29 ), follow_redirects=True)3031 def logout(self):32 return self.app.get('/logout', follow_redirects=True)3334 # testing functions3536 def test_login_logout(self):37 """Make sure login and logout works"""38 rv = self.login(flaskr.USERNAME, flaskr.PASSWORD)39 assert 'You were logged in' in rv.data40 rv = self.logout()41 assert 'You were logged out' in rv.data42 rv = self.login(flaskr.USERNAME + 'x', flaskr.PASSWORD)43 assert 'Invalid username' in rv.data44 rv = self.login(flaskr.USERNAME, flaskr.PASSWORD + 'x')45 assert 'Invalid password' in rv.data4647 def test_messages(self):48 """Test that messages work"""49 # start with a blank state50 rv = self.app.get('/')51 assert 'No entries here so far' in rv.data52 self.login(flaskr.USERNAME, flaskr.PASSWORD)53 rv = self.app.post('/add', data=dict(54 title='<Hello>',55 text='<strong>HTML</strong> allowed here'56 ), follow_redirects=True)57 assert 'No entries here so far' not in rv.data58 self.login(flaskr.USERNAME, flaskr.PASSWORD)59 assert '&lt;Hello&gt' in rv.data60 assert '<strong>HTML</strong> allowed here' in rv.data616263if __name__ == '__main__':64 unittest.main()
added:examples/flaskr/flaskr.py+103 added
1# -*- coding: utf-8 -*-2"""3 Flaskr4 ~~~~~~56 A microblog example application written as Flask tutorial with7 Flask and sqlite3.89 :copyright: (c) 2010 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""12from __future__ import with_statement13import time14import sqlite315from contextlib import closing16from flask import Flask, request, session, g, redirect, url_for, abort, \17 render_template, flash18from werkzeug import secure_filename1920# configuration21DATABASE = '/tmp/flaskr.db'22DEBUG = True23SECRET_KEY = 'development key'24USERNAME = 'admin'25PASSWORD = 'default'2627# create our little application :)28app = Flask(__name__)29app.secret_key = SECRET_KEY30app.debug = DEBUG313233def connect_db():34 """Returns a new connection to the database."""35 return sqlite3.connect(DATABASE)363738def init_db():39 """Creates the database tables."""40 with closing(connect_db()) as db:41 with app.open_resource('schema.sql') as f:42 db.cursor().executescript(f.read())43 db.commit()444546@app.request_init47def before_request():48 """Make sure we are connected to the database each request. Also49 set `g.logged_in` to `True` if we are logged in.50 """51 g.db = connect_db()52 g.logged_in = session.get('logged_in', False)535455@app.request_shutdown56def after_request(response):57 """Closes the database again at the end of the request."""58 g.db.close()59 return response606162@app.route('/')63def show_entries():64 cur = g.db.execute('select title, text from entries order by id desc')65 entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]66 return render_template('show_entries.html', entries=entries)676869@app.route('/add', methods=['POST'])70def add_entry():71 if not g.logged_in:72 abort(401)73 g.db.execute('insert into entries (title, text) values (?, ?)',74 [request.form['title'], request.form['text']])75 g.db.commit()76 flash('New entry was successfully posted')77 return redirect(url_for('show_entries'))787980@app.route('/login', methods=['GET', 'POST'])81def login():82 error = None83 if request.method == 'POST':84 if request.form['username'] != USERNAME:85 error = 'Invalid username'86 elif request.form['password'] != PASSWORD:87 error = 'Invalid password'88 else:89 session['logged_in'] = True90 flash('You were logged in')91 return redirect(url_for('show_entries'))92 return render_template('login.html', error=error)939495@app.route('/logout')96def logout():97 session.pop('logged_in', None)98 flash('You were logged out')99 return redirect(url_for('show_entries'))100101102if __name__ == '__main__':103 app.run()
added:examples/flaskr/schema.sql+6 added
1drop table if exists entries;2create table entries (3 id integer primary key autoincrement,4 title string not null,5 text string not null6);