Skip to content
Myr

minitwit.py

This file

Path

examples/minitwit/minitwit.py

248 lines · 8.2 KiB · Python

Last changed by

Updated the docs and examples to non-failing teardown handlersArmin Ronacherbefore adoptiond3ca551

History of this file

Take it

The walk stopped after 200 commits: lines older than de3b6ab point at it.

Fixed a broken sentence about blueprints.Armin Ronacherbefore adoptionde3b6ab

lines 1–87why, one step back
1# -*- coding: utf-8 -*-
2"""3 MiniTwit4 ~~~~~~~~56 A microblogging application written with Flask and sqlite3.78 :copyright: (c) 2010 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from __future__ import with_statement12import time13from sqlite3 import dbapi2 as sqlite314from hashlib import md515from datetime import datetime16from contextlib import closing17from flask import Flask, request, session, url_for, redirect, \18 render_template, abort, g, flash19from werkzeug import check_password_hash, generate_password_hash202122# configuration23DATABASE = '/tmp/minitwit.db'24PER_PAGE = 3025DEBUG = True26SECRET_KEY = 'development key'2728# create our little application :)29app = Flask(__name__)30app.config.from_object(__name__)31app.config.from_envvar('MINITWIT_SETTINGS', silent=True)323334def connect_db():35 """Returns a new connection to the database."""36 return sqlite3.connect(app.config['DATABASE'])373839def init_db():40 """Creates the database tables."""41 with closing(connect_db()) as db:42 with app.open_resource('schema.sql') as f:43 db.cursor().executescript(f.read())44 db.commit()454647def query_db(query, args=(), one=False):48 """Queries the database and returns a list of dictionaries."""49 cur = g.db.execute(query, args)50 rv = [dict((cur.description[idx][0], value)51 for idx, value in enumerate(row)) for row in cur.fetchall()]52 return (rv[0] if rv else None) if one else rv535455def get_user_id(username):56 """Convenience method to look up the id for a username."""57 rv = g.db.execute('select user_id from user where username = ?',58 [username]).fetchone()59 return rv[0] if rv else None606162def format_datetime(timestamp):63 """Format a timestamp for display."""64 return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d @ %H:%M')656667def gravatar_url(email, size=80):68 """Return the gravatar image for the given email address."""69 return 'http://www.gravatar.com/avatar/%s?d=identicon&s=%d' % \70 (md5(email.strip().lower().encode('utf-8')).hexdigest(), size)717273@app.before_request74def before_request():75 """Make sure we are connected to the database each request and look76 up the current user so that we know he's there.77 """78 g.db = connect_db()79 g.user = None80 if 'user_id' in session:81 g.user = query_db('select * from user where user_id = ?',82 [session['user_id']], one=True)838485@app.teardown_request86def teardown_request(exception):87 """Closes the database again at the end of the request."""

Updated the docs and examples to non-failing teardown handlersArmin Ronacherbefore adoptiond3ca551

lines 88–89why, one step back
88 if hasattr(g, 'db'):
89 g.db.close()

Fixed a broken sentence about blueprints.Armin Ronacherbefore adoptionde3b6ab

lines 90–248why, one step back
90
9192@app.route('/')93def timeline():94 """Shows a users timeline or if no user is logged in it will95 redirect to the public timeline. This timeline shows the user's96 messages as well as all the messages of followed users.97 """98 if not g.user:99 return redirect(url_for('public_timeline'))100 return render_template('timeline.html', messages=query_db('''101 select message.*, user.* from message, user102 where message.author_id = user.user_id and (103 user.user_id = ? or104 user.user_id in (select whom_id from follower105 where who_id = ?))106 order by message.pub_date desc limit ?''',107 [session['user_id'], session['user_id'], PER_PAGE]))108109110@app.route('/public')111def public_timeline():112 """Displays the latest messages of all users."""113 return render_template('timeline.html', messages=query_db('''114 select message.*, user.* from message, user115 where message.author_id = user.user_id116 order by message.pub_date desc limit ?''', [PER_PAGE]))117118119@app.route('/<username>')120def user_timeline(username):121 """Display's a users tweets."""122 profile_user = query_db('select * from user where username = ?',123 [username], one=True)124 if profile_user is None:125 abort(404)126 followed = False127 if g.user:128 followed = query_db('''select 1 from follower where129 follower.who_id = ? and follower.whom_id = ?''',130 [session['user_id'], profile_user['user_id']],131 one=True) is not None132 return render_template('timeline.html', messages=query_db('''133 select message.*, user.* from message, user where134 user.user_id = message.author_id and user.user_id = ?135 order by message.pub_date desc limit ?''',136 [profile_user['user_id'], PER_PAGE]), followed=followed,137 profile_user=profile_user)138139140@app.route('/<username>/follow')141def follow_user(username):142 """Adds the current user as follower of the given user."""143 if not g.user:144 abort(401)145 whom_id = get_user_id(username)146 if whom_id is None:147 abort(404)148 g.db.execute('insert into follower (who_id, whom_id) values (?, ?)',149 [session['user_id'], whom_id])150 g.db.commit()151 flash('You are now following "%s"' % username)152 return redirect(url_for('user_timeline', username=username))153154155@app.route('/<username>/unfollow')156def unfollow_user(username):157 """Removes the current user as follower of the given user."""158 if not g.user:159 abort(401)160 whom_id = get_user_id(username)161 if whom_id is None:162 abort(404)163 g.db.execute('delete from follower where who_id=? and whom_id=?',164 [session['user_id'], whom_id])165 g.db.commit()166 flash('You are no longer following "%s"' % username)167 return redirect(url_for('user_timeline', username=username))168169170@app.route('/add_message', methods=['POST'])171def add_message():172 """Registers a new message for the user."""173 if 'user_id' not in session:174 abort(401)175 if request.form['text']:176 g.db.execute('''insert into message (author_id, text, pub_date)177 values (?, ?, ?)''', (session['user_id'], request.form['text'],178 int(time.time())))179 g.db.commit()180 flash('Your message was recorded')181 return redirect(url_for('timeline'))182183184@app.route('/login', methods=['GET', 'POST'])185def login():186 """Logs the user in."""187 if g.user:188 return redirect(url_for('timeline'))189 error = None190 if request.method == 'POST':191 user = query_db('''select * from user where192 username = ?''', [request.form['username']], one=True)193 if user is None:194 error = 'Invalid username'195 elif not check_password_hash(user['pw_hash'],196 request.form['password']):197 error = 'Invalid password'198 else:199 flash('You were logged in')200 session['user_id'] = user['user_id']201 return redirect(url_for('timeline'))202 return render_template('login.html', error=error)203204205@app.route('/register', methods=['GET', 'POST'])206def register():207 """Registers the user."""208 if g.user:209 return redirect(url_for('timeline'))210 error = None211 if request.method == 'POST':212 if not request.form['username']:213 error = 'You have to enter a username'214 elif not request.form['email'] or \215 '@' not in request.form['email']:216 error = 'You have to enter a valid email address'217 elif not request.form['password']:218 error = 'You have to enter a password'219 elif request.form['password'] != request.form['password2']:220 error = 'The two passwords do not match'221 elif get_user_id(request.form['username']) is not None:222 error = 'The username is already taken'223 else:224 g.db.execute('''insert into user (225 username, email, pw_hash) values (?, ?, ?)''',226 [request.form['username'], request.form['email'],227 generate_password_hash(request.form['password'])])228 g.db.commit()229 flash('You were successfully registered and can login now')230 return redirect(url_for('login'))231 return render_template('register.html', error=error)232233234@app.route('/logout')235def logout():236 """Logs the user out."""237 flash('You were logged out')238 session.pop('user_id', None)239 return redirect(url_for('public_timeline'))240241242# add some filters to jinja243app.jinja_env.filters['datetimeformat'] = format_datetime244app.jinja_env.filters['gravatar'] = gravatar_url245246247if __name__ == '__main__':248 app.run()