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
Provenance
- Commit
c33675f- Tree
984456c- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
2d9bb69
7 files changed+241 added−0 removed
added:examples/flaskr/static/style.css+16 added
12345678910111213141516body { 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; }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.flash { background: #CEE5F5; padding: 0.5em; border: 1px solid #AACBE2; }p.error { background: #F0D6D6; padding: 0.5em; }added:examples/flaskr/templates/layout.html+17 added
1234567891011121314151617<!doctype html><title>Flaskr</title><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 %} <a href="{{ url_for('login') }}">log in</a> {% else %} <a href="{{ url_for('logout') }}">log out</a> {% endif %} </div> {% for message in get_flashed_messages() %} <div class=flash>{{ message }}</div> {% endfor %} {% block body %}{% endblock %}</div>added:examples/flaskr/templates/login.html+14 added
1234567891011121314{% extends "layout.html" %}{% block body %} <h2>Login</h2> {% if error %}<p class=error><strong>Error:</strong> {{ error }}{% endif %} <form action="{{ url_for('login') }}" method=post> <dl> <dt>Username: <dd><input type=text name=username> <dt>Password: <dd><input type=passowrd name=password> <dd><input type=submit value=Login> </dl> </form>{% endblock %}added:examples/flaskr/templates/show_entries.html+21 added
123456789101112131415161718192021{% extends "layout.html" %}{% block body %} {% if g.logged_in %} <form action="{{ url_for('add_entry') }}" method=post class=add-entry> <dl> <dt>Title: <dd><input type=text size=30 name=title> <dt>Text: <dd><textarea name=text rows=5 cols=40></textarea> <dd><input type=submit value=Share> </dl> </form> {% endif %} <ul class=entries> {% for entry in entries %} <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }} {% else %} <li><em>Unbelievable. No entries here so far</em> {% endfor %} </ul>{% endblock %}added:examples/flaskr/flaskr_tests.py+64 added
1+# -*- coding: utf-8 -*-2+"""3+ Flaskr Tests4+ ~~~~~~~~~~~~5+6+ Tests the Flaskr application.7+8+ :copyright: (c) 2010 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+import flaskr12+import unittest13+import tempfile14+15+16+class FlaskrTestCase(unittest.TestCase):17+18+ 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()24+25+ def login(self, username, password):26+ return self.app.post('/login', data=dict(27+ username=username,28+ password=password29+ ), follow_redirects=True)30+31+ def logout(self):32+ return self.app.get('/logout', follow_redirects=True)33+34+ # testing functions35+36+ 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.data46+47+ 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 '<Hello>' in rv.data60+ assert '<strong>HTML</strong> allowed here' in rv.data61+62+63+if __name__ == '__main__':64+ unittest.main()added:examples/flaskr/flaskr.py+103 added
1+# -*- coding: utf-8 -*-2+"""3+ Flaskr4+ ~~~~~~5+6+ A microblog example application written as Flask tutorial with7+ 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_statement13+import time14+import sqlite315+from contextlib import closing16+from flask import Flask, request, session, g, redirect, url_for, abort, \17+ render_template, flash18+from werkzeug import secure_filename19+20+# configuration21+DATABASE = '/tmp/flaskr.db'22+DEBUG = True23+SECRET_KEY = 'development key'24+USERNAME = 'admin'25+PASSWORD = 'default'26+27+# create our little application :)28+app = Flask(__name__)29+app.secret_key = SECRET_KEY30+app.debug = DEBUG31+32+33+def connect_db():34+ """Returns a new connection to the database."""35+ return sqlite3.connect(DATABASE)36+37+38+def 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()44+45+46+@app.request_init47+def 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)53+54+55+@app.request_shutdown56+def after_request(response):57+ """Closes the database again at the end of the request."""58+ g.db.close()59+ return response60+61+62+@app.route('/')63+def 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)67+68+69+@app.route('/add', methods=['POST'])70+def 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'))78+79+80+@app.route('/login', methods=['GET', 'POST'])81+def 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)93+94+95+@app.route('/logout')96+def logout():97+ session.pop('logged_in', None)98+ flash('You were logged out')99+ return redirect(url_for('show_entries'))100+101+102+if __name__ == '__main__':103+ app.run()added:examples/flaskr/schema.sql+6 added
1+drop table if exists entries;2+create table entries (3+ id integer primary key autoincrement,4+ title string not null,5+ text string not null6+);