Skip to content
Myr

Update minitwit & improve testing for examples (#1954)

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

* Update minitwit & improve testing for examples * Related to #1945 * Re-works minitwit to be installed and run as: pip install --editable . export FLASK_APP=minitwit.minitwit export FLASK_DEBUG=1 flask initdb flask run * added flaskr and minitwit to norecursedirs * tests not properly run when using pytest standards * see: http://stackoverflow.com/questions/38313171/configuring-pytest-with-installable-examples-in-a-project * Both flaskr and minitwit now follow pytest standards. * Tests can for them as `py.test` or `python setup.py test` * Update minitwit readme * updates the instructions for running * Fixes for updating the minitwit example - This reverts the changes to the *docs/* (I will file separate PR). - Running the app is now: `export FLASK_APP=minitwit` & `flask run` (After installing the app) * Remove unnecessary comma from flaskr/setup.py

authored by Kyle Lawlor · committed by Markus Unterwaditzer · parent 1e5746b · Browse files · 25 files+750 added−732 removed
This commit

State

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

Diff stats

25 files+750 added−732 removed

  • tests:+153 added−8 removed
  • other:+597 added−724 removed

25 files+750 added−732 removed

deleted:examples/flaskr/tests/context.py-6 removed
1import sys, os23basedir = os.path.dirname(os.path.abspath(__file__))4sys.path.insert(0, basedir + '/../')56from flaskr import flaskr
modified:examples/flaskr/tests/test_flaskr.py+2 added-2 removed
7 unmodified lines
8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest12import os13import tempfile14import pytest15from flaskr import flaskr1616from context import flaskr1718@pytest.fixture19def client(request):20 db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()
56 unmodified lines
added:examples/minitwit/minitwit/static/style.css+178 added
1body {2 background: #CAECE9;3 font-family: 'Trebuchet MS', sans-serif;4 font-size: 14px;5}67a {8 color: #26776F;9}1011a:hover {12 color: #333;13}1415input[type="text"],16input[type="password"] {17 background: white;18 border: 1px solid #BFE6E2;19 padding: 2px;20 font-family: 'Trebuchet MS', sans-serif;21 font-size: 14px;22 -moz-border-radius: 2px;23 -webkit-border-radius: 2px;24 color: #105751;25}2627input[type="submit"] {28 background: #105751;29 border: 1px solid #073B36;30 padding: 1px 3px;31 font-family: 'Trebuchet MS', sans-serif;32 font-size: 14px;33 font-weight: bold;34 -moz-border-radius: 2px;35 -webkit-border-radius: 2px;36 color: white;37}3839div.page {40 background: white;41 border: 1px solid #6ECCC4;42 width: 700px;43 margin: 30px auto;44}4546div.page h1 {47 background: #6ECCC4;48 margin: 0;49 padding: 10px 14px;50 color: white;51 letter-spacing: 1px;52 text-shadow: 0 0 3px #24776F;53 font-weight: normal;54}5556div.page div.navigation {57 background: #DEE9E8;58 padding: 4px 10px;59 border-top: 1px solid #ccc;60 border-bottom: 1px solid #eee;61 color: #888;62 font-size: 12px;63 letter-spacing: 0.5px;64}6566div.page div.navigation a {67 color: #444;68 font-weight: bold;69}7071div.page h2 {72 margin: 0 0 15px 0;73 color: #105751;74 text-shadow: 0 1px 2px #ccc;75}7677div.page div.body {78 padding: 10px;79}8081div.page div.footer {82 background: #eee;83 color: #888;84 padding: 5px 10px;85 font-size: 12px;86}8788div.page div.followstatus {89 border: 1px solid #ccc;90 background: #E3EBEA;91 -moz-border-radius: 2px;92 -webkit-border-radius: 2px;93 padding: 3px;94 font-size: 13px;95}9697div.page ul.messages {98 list-style: none;99 margin: 0;100 padding: 0;101}102103div.page ul.messages li {104 margin: 10px 0;105 padding: 5px;106 background: #F0FAF9;107 border: 1px solid #DBF3F1;108 -moz-border-radius: 5px;109 -webkit-border-radius: 5px;110 min-height: 48px;111}112113div.page ul.messages p {114 margin: 0;115}116117div.page ul.messages li img {118 float: left;119 padding: 0 10px 0 0;120}121122div.page ul.messages li small {123 font-size: 0.9em;124 color: #888;125}126127div.page div.twitbox {128 margin: 10px 0;129 padding: 5px;130 background: #F0FAF9;131 border: 1px solid #94E2DA;132 -moz-border-radius: 5px;133 -webkit-border-radius: 5px;134}135136div.page div.twitbox h3 {137 margin: 0;138 font-size: 1em;139 color: #2C7E76;140}141142div.page div.twitbox p {143 margin: 0;144}145146div.page div.twitbox input[type="text"] {147 width: 585px;148}149150div.page div.twitbox input[type="submit"] {151 width: 70px;152 margin-left: 5px;153}154155ul.flashes {156 list-style: none;157 margin: 10px 10px 0 10px;158 padding: 0;159}160161ul.flashes li {162 background: #B9F3ED;163 border: 1px solid #81CEC6;164 -moz-border-radius: 2px;165 -webkit-border-radius: 2px;166 padding: 4px;167 font-size: 13px;168}169170div.error {171 margin: 10px 0;172 background: #FAE4E4;173 border: 1px solid #DD6F6F;174 -moz-border-radius: 2px;175 -webkit-border-radius: 2px;176 padding: 4px;177 font-size: 13px;178}
added:examples/minitwit/minitwit/templates/layout.html+32 added
added:examples/minitwit/minitwit/templates/login.html+16 added
added:examples/minitwit/minitwit/templates/register.html+19 added
added:examples/minitwit/minitwit/templates/timeline.html+49 added
added:examples/minitwit/minitwit/__init__.py+1 added
1from minitwit import app
added:examples/minitwit/minitwit/minitwit.py+256 added
1# -*- coding: utf-8 -*-2"""3 MiniTwit4 ~~~~~~~~56 A microblogging application written with Flask and sqlite3.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import time13from sqlite3 import dbapi2 as sqlite314from hashlib import md515from datetime import datetime16from flask import Flask, request, session, url_for, redirect, \17 render_template, abort, g, flash, _app_ctx_stack18from werkzeug import check_password_hash, generate_password_hash192021# configuration22DATABASE = '/tmp/minitwit.db'23PER_PAGE = 3024DEBUG = True25SECRET_KEY = 'development key'2627# create our little application :)28app = Flask(__name__)29app.config.from_object(__name__)30app.config.from_envvar('MINITWIT_SETTINGS', silent=True)313233def get_db():34 """Opens a new database connection if there is none yet for the35 current application context.36 """37 top = _app_ctx_stack.top38 if not hasattr(top, 'sqlite_db'):39 top.sqlite_db = sqlite3.connect(app.config['DATABASE'])40 top.sqlite_db.row_factory = sqlite3.Row41 return top.sqlite_db424344@app.teardown_appcontext45def close_database(exception):46 """Closes the database again at the end of the request."""47 top = _app_ctx_stack.top48 if hasattr(top, 'sqlite_db'):49 top.sqlite_db.close()505152def init_db():53 """Initializes the database."""54 db = get_db()55 with app.open_resource('schema.sql', mode='r') as f:56 db.cursor().executescript(f.read())57 db.commit()585960@app.cli.command('initdb')61def initdb_command():62 """Creates the database tables."""63 init_db()64 print('Initialized the database.')656667def query_db(query, args=(), one=False):68 """Queries the database and returns a list of dictionaries."""69 cur = get_db().execute(query, args)70 rv = cur.fetchall()71 return (rv[0] if rv else None) if one else rv727374def get_user_id(username):75 """Convenience method to look up the id for a username."""76 rv = query_db('select user_id from user where username = ?',77 [username], one=True)78 return rv[0] if rv else None798081def format_datetime(timestamp):82 """Format a timestamp for display."""83 return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d @ %H:%M')848586def gravatar_url(email, size=80):87 """Return the gravatar image for the given email address."""88 return 'http://www.gravatar.com/avatar/%s?d=identicon&s=%d' % \89 (md5(email.strip().lower().encode('utf-8')).hexdigest(), size)909192@app.before_request93def before_request():94 g.user = None95 if 'user_id' in session:96 g.user = query_db('select * from user where user_id = ?',97 [session['user_id']], one=True)9899100@app.route('/')101def timeline():102 """Shows a users timeline or if no user is logged in it will103 redirect to the public timeline. This timeline shows the user's104 messages as well as all the messages of followed users.105 """106 if not g.user:107 return redirect(url_for('public_timeline'))108 return render_template('timeline.html', messages=query_db('''109 select message.*, user.* from message, user110 where message.author_id = user.user_id and (111 user.user_id = ? or112 user.user_id in (select whom_id from follower113 where who_id = ?))114 order by message.pub_date desc limit ?''',115 [session['user_id'], session['user_id'], PER_PAGE]))116117118@app.route('/public')119def public_timeline():120 """Displays the latest messages of all users."""121 return render_template('timeline.html', messages=query_db('''122 select message.*, user.* from message, user123 where message.author_id = user.user_id124 order by message.pub_date desc limit ?''', [PER_PAGE]))125126127@app.route('/<username>')128def user_timeline(username):129 """Display's a users tweets."""130 profile_user = query_db('select * from user where username = ?',131 [username], one=True)132 if profile_user is None:133 abort(404)134 followed = False135 if g.user:136 followed = query_db('''select 1 from follower where137 follower.who_id = ? and follower.whom_id = ?''',138 [session['user_id'], profile_user['user_id']],139 one=True) is not None140 return render_template('timeline.html', messages=query_db('''141 select message.*, user.* from message, user where142 user.user_id = message.author_id and user.user_id = ?143 order by message.pub_date desc limit ?''',144 [profile_user['user_id'], PER_PAGE]), followed=followed,145 profile_user=profile_user)146147148@app.route('/<username>/follow')149def follow_user(username):150 """Adds the current user as follower of the given user."""151 if not g.user:152 abort(401)153 whom_id = get_user_id(username)154 if whom_id is None:155 abort(404)156 db = get_db()157 db.execute('insert into follower (who_id, whom_id) values (?, ?)',158 [session['user_id'], whom_id])159 db.commit()160 flash('You are now following "%s"' % username)161 return redirect(url_for('user_timeline', username=username))162163164@app.route('/<username>/unfollow')165def unfollow_user(username):166 """Removes the current user as follower of the given user."""167 if not g.user:168 abort(401)169 whom_id = get_user_id(username)170 if whom_id is None:171 abort(404)172 db = get_db()173 db.execute('delete from follower where who_id=? and whom_id=?',174 [session['user_id'], whom_id])175 db.commit()176 flash('You are no longer following "%s"' % username)177 return redirect(url_for('user_timeline', username=username))178179180@app.route('/add_message', methods=['POST'])181def add_message():182 """Registers a new message for the user."""183 if 'user_id' not in session:184 abort(401)185 if request.form['text']:186 db = get_db()187 db.execute('''insert into message (author_id, text, pub_date)188 values (?, ?, ?)''', (session['user_id'], request.form['text'],189 int(time.time())))190 db.commit()191 flash('Your message was recorded')192 return redirect(url_for('timeline'))193194195@app.route('/login', methods=['GET', 'POST'])196def login():197 """Logs the user in."""198 if g.user:199 return redirect(url_for('timeline'))200 error = None201 if request.method == 'POST':202 user = query_db('''select * from user where203 username = ?''', [request.form['username']], one=True)204 if user is None:205 error = 'Invalid username'206 elif not check_password_hash(user['pw_hash'],207 request.form['password']):208 error = 'Invalid password'209 else:210 flash('You were logged in')211 session['user_id'] = user['user_id']212 return redirect(url_for('timeline'))213 return render_template('login.html', error=error)214215216@app.route('/register', methods=['GET', 'POST'])217def register():218 """Registers the user."""219 if g.user:220 return redirect(url_for('timeline'))221 error = None222 if request.method == 'POST':223 if not request.form['username']:224 error = 'You have to enter a username'225 elif not request.form['email'] or \226 '@' not in request.form['email']:227 error = 'You have to enter a valid email address'228 elif not request.form['password']:229 error = 'You have to enter a password'230 elif request.form['password'] != request.form['password2']:231 error = 'The two passwords do not match'232 elif get_user_id(request.form['username']) is not None:233 error = 'The username is already taken'234 else:235 db = get_db()236 db.execute('''insert into user (237 username, email, pw_hash) values (?, ?, ?)''',238 [request.form['username'], request.form['email'],239 generate_password_hash(request.form['password'])])240 db.commit()241 flash('You were successfully registered and can login now')242 return redirect(url_for('login'))243 return render_template('register.html', error=error)244245246@app.route('/logout')247def logout():248 """Logs the user out."""249 flash('You were logged out')250 session.pop('user_id', None)251 return redirect(url_for('public_timeline'))252253254# add some filters to jinja255app.jinja_env.filters['datetimeformat'] = format_datetime256app.jinja_env.filters['gravatar'] = gravatar_url
added:examples/minitwit/minitwit/schema.sql+21 added
1drop table if exists user;2create table user (3 user_id integer primary key autoincrement,4 username text not null,5 email text not null,6 pw_hash text not null7);89drop table if exists follower;10create table follower (11 who_id integer,12 whom_id integer13);1415drop table if exists message;16create table message (17 message_id integer primary key autoincrement,18 author_id integer not null,19 text text not null,20 pub_date integer21);
deleted:examples/minitwit/static/style.css-178 removed
1body {2 background: #CAECE9;3 font-family: 'Trebuchet MS', sans-serif;4 font-size: 14px;5}67a {8 color: #26776F;9}1011a:hover {12 color: #333;13}1415input[type="text"],16input[type="password"] {17 background: white;18 border: 1px solid #BFE6E2;19 padding: 2px;20 font-family: 'Trebuchet MS', sans-serif;21 font-size: 14px;22 -moz-border-radius: 2px;23 -webkit-border-radius: 2px;24 color: #105751;25}2627input[type="submit"] {28 background: #105751;29 border: 1px solid #073B36;30 padding: 1px 3px;31 font-family: 'Trebuchet MS', sans-serif;32 font-size: 14px;33 font-weight: bold;34 -moz-border-radius: 2px;35 -webkit-border-radius: 2px;36 color: white;37}3839div.page {40 background: white;41 border: 1px solid #6ECCC4;42 width: 700px;43 margin: 30px auto;44}4546div.page h1 {47 background: #6ECCC4;48 margin: 0;49 padding: 10px 14px;50 color: white;51 letter-spacing: 1px;52 text-shadow: 0 0 3px #24776F;53 font-weight: normal;54}5556div.page div.navigation {57 background: #DEE9E8;58 padding: 4px 10px;59 border-top: 1px solid #ccc;60 border-bottom: 1px solid #eee;61 color: #888;62 font-size: 12px;63 letter-spacing: 0.5px;64}6566div.page div.navigation a {67 color: #444;68 font-weight: bold;69}7071div.page h2 {72 margin: 0 0 15px 0;73 color: #105751;74 text-shadow: 0 1px 2px #ccc;75}7677div.page div.body {78 padding: 10px;79}8081div.page div.footer {82 background: #eee;83 color: #888;84 padding: 5px 10px;85 font-size: 12px;86}8788div.page div.followstatus {89 border: 1px solid #ccc;90 background: #E3EBEA;91 -moz-border-radius: 2px;92 -webkit-border-radius: 2px;93 padding: 3px;94 font-size: 13px;95}9697div.page ul.messages {98 list-style: none;99 margin: 0;100 padding: 0;101}102103div.page ul.messages li {104 margin: 10px 0;105 padding: 5px;106 background: #F0FAF9;107 border: 1px solid #DBF3F1;108 -moz-border-radius: 5px;109 -webkit-border-radius: 5px;110 min-height: 48px;111}112113div.page ul.messages p {114 margin: 0;115}116117div.page ul.messages li img {118 float: left;119 padding: 0 10px 0 0;120}121122div.page ul.messages li small {123 font-size: 0.9em;124 color: #888;125}126127div.page div.twitbox {128 margin: 10px 0;129 padding: 5px;130 background: #F0FAF9;131 border: 1px solid #94E2DA;132 -moz-border-radius: 5px;133 -webkit-border-radius: 5px;134}135136div.page div.twitbox h3 {137 margin: 0;138 font-size: 1em;139 color: #2C7E76;140}141142div.page div.twitbox p {143 margin: 0;144}145146div.page div.twitbox input[type="text"] {147 width: 585px;148}149150div.page div.twitbox input[type="submit"] {151 width: 70px;152 margin-left: 5px;153}154155ul.flashes {156 list-style: none;157 margin: 10px 10px 0 10px;158 padding: 0;159}160161ul.flashes li {162 background: #B9F3ED;163 border: 1px solid #81CEC6;164 -moz-border-radius: 2px;165 -webkit-border-radius: 2px;166 padding: 4px;167 font-size: 13px;168}169170div.error {171 margin: 10px 0;172 background: #FAE4E4;173 border: 1px solid #DD6F6F;174 -moz-border-radius: 2px;175 -webkit-border-radius: 2px;176 padding: 4px;177 font-size: 13px;178}
deleted:examples/minitwit/templates/layout.html-32 removed
1<!doctype html>2<title>{% block title %}Welcome{% endblock %} | MiniTwit</title>3<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">4<div class="page">5 <h1>MiniTwit</h1>6 <div class="navigation">7 {% if g.user %}8 <a href="{{ url_for('timeline') }}">my timeline</a> |9 <a href="{{ url_for('public_timeline') }}">public timeline</a> |10 <a href="{{ url_for('logout') }}">sign out [{{ g.user.username }}]</a>11 {% else %}12 <a href="{{ url_for('public_timeline') }}">public timeline</a> |13 <a href="{{ url_for('register') }}">sign up</a> |14 <a href="{{ url_for('login') }}">sign in</a>15 {% endif %}16 </div>17 {% with flashes = get_flashed_messages() %}18 {% if flashes %}19 <ul class="flashes">20 {% for message in flashes %}21 <li>{{ message }}22 {% endfor %}23 </ul>24 {% endif %}25 {% endwith %}26 <div class="body">27 {% block body %}{% endblock %}28 </div>29 <div class="footer">30 MiniTwit &mdash; A Flask Application31 </div>32</div>
deleted:examples/minitwit/templates/login.html-16 removed
1{% extends "layout.html" %}2{% block title %}Sign In{% endblock %}3{% block body %}4 <h2>Sign In</h2>5 {% if error %}<div class="error"><strong>Error:</strong> {{ error }}</div>{% endif %}6 <form action="" method="post">7 <dl>8 <dt>Username:9 <dd><input type="text" name="username" size="30" value="{{ request.form.username }}">10 <dt>Password:11 <dd><input type="password" name="password" size="30">12 </dl>13 <div class="actions"><input type="submit" value="Sign In"></div>14 </form>15{% endblock %}16
deleted:examples/minitwit/templates/register.html-19 removed
1{% extends "layout.html" %}2{% block title %}Sign Up{% endblock %}3{% block body %}4 <h2>Sign Up</h2>5 {% if error %}<div class="error"><strong>Error:</strong> {{ error }}</div>{% endif %}6 <form action="" method="post">7 <dl>8 <dt>Username:9 <dd><input type="text" name="username" size="30" value="{{ request.form.username }}">10 <dt>E-Mail:11 <dd><input type="text" name="email" size="30" value="{{ request.form.email }}">12 <dt>Password:13 <dd><input type="password" name="password" size="30">14 <dt>Password <small>(repeat)</small>:15 <dd><input type="password" name="password2" size="30">16 </dl>17 <div class="actions"><input type="submit" value="Sign Up"></div>18 </form>19{% endblock %}
deleted:examples/minitwit/templates/timeline.html-49 removed
1{% extends "layout.html" %}2{% block title %}3 {% if request.endpoint == 'public_timeline' %}4 Public Timeline5 {% elif request.endpoint == 'user_timeline' %}6 {{ profile_user.username }}'s Timeline7 {% else %}8 My Timeline9 {% endif %}10{% endblock %}11{% block body %}12 <h2>{{ self.title() }}</h2>13 {% if g.user %}14 {% if request.endpoint == 'user_timeline' %}15 <div class="followstatus">16 {% if g.user.user_id == profile_user.user_id %}17 This is you!18 {% elif followed %}19 You are currently following this user.20 <a class="unfollow" href="{{ url_for('unfollow_user', username=profile_user.username)21 }}">Unfollow user</a>.22 {% else %}23 You are not yet following this user.24 <a class="follow" href="{{ url_for('follow_user', username=profile_user.username)25 }}">Follow user</a>.26 {% endif %}27 </div>28 {% elif request.endpoint == 'timeline' %}29 <div class="twitbox">30 <h3>What's on your mind {{ g.user.username }}?</h3>31 <form action="{{ url_for('add_message') }}" method="post">32 <p><input type="text" name="text" size="60"><!--33 --><input type="submit" value="Share">34 </form>35 </div>36 {% endif %}37 {% endif %}38 <ul class="messages">39 {% for message in messages %}40 <li><img src="{{ message.email|gravatar(size=48) }}"><p>41 <strong><a href="{{ url_for('user_timeline', username=message.username)42 }}">{{ message.username }}</a></strong>43 {{ message.text }}44 <small>&mdash; {{ message.pub_date|datetimeformat }}</small>45 {% else %}46 <li><em>There's no message so far.</em>47 {% endfor %}48 </ul>49{% endblock %}
added:examples/minitwit/tests/test_minitwit.py+151 added
1# -*- coding: utf-8 -*-2"""3 MiniTwit Tests4 ~~~~~~~~~~~~~~56 Tests the MiniTwit application.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import os12import tempfile13import pytest14from minitwit import minitwit151617@pytest.fixture18def client(request):19 db_fd, minitwit.app.config['DATABASE'] = tempfile.mkstemp()20 client = minitwit.app.test_client()21 with minitwit.app.app_context():22 minitwit.init_db()2324 def teardown():25 """Get rid of the database again after each test."""26 os.close(db_fd)27 os.unlink(minitwit.app.config['DATABASE'])28 request.addfinalizer(teardown)29 return client303132def register(client, username, password, password2=None, email=None):33 """Helper function to register a user"""34 if password2 is None:35 password2 = password36 if email is None:37 email = username + '@example.com'38 return client.post('/register', data={39 'username': username,40 'password': password,41 'password2': password2,42 'email': email,43 }, follow_redirects=True)444546def login(client, username, password):47 """Helper function to login"""48 return client.post('/login', data={49 'username': username,50 'password': password51 }, follow_redirects=True)525354def register_and_login(client, username, password):55 """Registers and logs in in one go"""56 register(client, username, password)57 return login(client, username, password)585960def logout(client):61 """Helper function to logout"""62 return client.get('/logout', follow_redirects=True)636465def add_message(client, text):66 """Records a message"""67 rv = client.post('/add_message', data={'text': text},68 follow_redirects=True)69 if text:70 assert b'Your message was recorded' in rv.data71 return rv727374def test_register(client):75 """Make sure registering works"""76 rv = register(client, 'user1', 'default')77 assert b'You were successfully registered ' \78 b'and can login now' in rv.data79 rv = register(client, 'user1', 'default')80 assert b'The username is already taken' in rv.data81 rv = register(client, '', 'default')82 assert b'You have to enter a username' in rv.data83 rv = register(client, 'meh', '')84 assert b'You have to enter a password' in rv.data85 rv = register(client, 'meh', 'x', 'y')86 assert b'The two passwords do not match' in rv.data87 rv = register(client, 'meh', 'foo', email='broken')88 assert b'You have to enter a valid email address' in rv.data899091def test_login_logout(client):92 """Make sure logging in and logging out works"""93 rv = register_and_login(client, 'user1', 'default')94 assert b'You were logged in' in rv.data95 rv = logout(client)96 assert b'You were logged out' in rv.data97 rv = login(client, 'user1', 'wrongpassword')98 assert b'Invalid password' in rv.data99 rv = login(client, 'user2', 'wrongpassword')100 assert b'Invalid username' in rv.data101102103def test_message_recording(client):104 """Check if adding messages works"""105 register_and_login(client, 'foo', 'default')106 add_message(client, 'test message 1')107 add_message(client, '<test message 2>')108 rv = client.get('/')109 assert b'test message 1' in rv.data110 assert b'&lt;test message 2&gt;' in rv.data111112113def test_timelines(client):114 """Make sure that timelines work"""115 register_and_login(client, 'foo', 'default')116 add_message(client, 'the message by foo')117 logout(client)118 register_and_login(client, 'bar', 'default')119 add_message(client, 'the message by bar')120 rv = client.get('/public')121 assert b'the message by foo' in rv.data122 assert b'the message by bar' in rv.data123124 # bar's timeline should just show bar's message125 rv = client.get('/')126 assert b'the message by foo' not in rv.data127 assert b'the message by bar' in rv.data128129 # now let's follow foo130 rv = client.get('/foo/follow', follow_redirects=True)131 assert b'You are now following &#34;foo&#34;' in rv.data132133 # we should now see foo's message134 rv = client.get('/')135 assert b'the message by foo' in rv.data136 assert b'the message by bar' in rv.data137138 # but on the user's page we only want the user's message139 rv = client.get('/bar')140 assert b'the message by foo' not in rv.data141 assert b'the message by bar' in rv.data142 rv = client.get('/foo')143 assert b'the message by foo' in rv.data144 assert b'the message by bar' not in rv.data145146 # now unfollow and check if that worked147 rv = client.get('/foo/unfollow', follow_redirects=True)148 assert b'You are no longer following &#34;foo&#34;' in rv.data149 rv = client.get('/')150 assert b'the message by foo' not in rv.data151 assert b'the message by bar' in rv.data
added:examples/minitwit/.gitignore+2 added
1minitwit.db2.eggs/
added:examples/minitwit/MANIFEST.in+3 added
1graft minitwit/templates2graft minitwit/static3include minitwit/schema.sql
deleted:examples/minitwit/minitwit.py-256 removed
1# -*- coding: utf-8 -*-2"""3 MiniTwit4 ~~~~~~~~56 A microblogging application written with Flask and sqlite3.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import time13from sqlite3 import dbapi2 as sqlite314from hashlib import md515from datetime import datetime16from flask import Flask, request, session, url_for, redirect, \17 render_template, abort, g, flash, _app_ctx_stack18from werkzeug import check_password_hash, generate_password_hash192021# configuration22DATABASE = '/tmp/minitwit.db'23PER_PAGE = 3024DEBUG = True25SECRET_KEY = 'development key'2627# create our little application :)28app = Flask(__name__)29app.config.from_object(__name__)30app.config.from_envvar('MINITWIT_SETTINGS', silent=True)313233def get_db():34 """Opens a new database connection if there is none yet for the35 current application context.36 """37 top = _app_ctx_stack.top38 if not hasattr(top, 'sqlite_db'):39 top.sqlite_db = sqlite3.connect(app.config['DATABASE'])40 top.sqlite_db.row_factory = sqlite3.Row41 return top.sqlite_db424344@app.teardown_appcontext45def close_database(exception):46 """Closes the database again at the end of the request."""47 top = _app_ctx_stack.top48 if hasattr(top, 'sqlite_db'):49 top.sqlite_db.close()505152def init_db():53 """Initializes the database."""54 db = get_db()55 with app.open_resource('schema.sql', mode='r') as f:56 db.cursor().executescript(f.read())57 db.commit()585960@app.cli.command('initdb')61def initdb_command():62 """Creates the database tables."""63 init_db()64 print('Initialized the database.')656667def query_db(query, args=(), one=False):68 """Queries the database and returns a list of dictionaries."""69 cur = get_db().execute(query, args)70 rv = cur.fetchall()71 return (rv[0] if rv else None) if one else rv727374def get_user_id(username):75 """Convenience method to look up the id for a username."""76 rv = query_db('select user_id from user where username = ?',77 [username], one=True)78 return rv[0] if rv else None798081def format_datetime(timestamp):82 """Format a timestamp for display."""83 return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d @ %H:%M')848586def gravatar_url(email, size=80):87 """Return the gravatar image for the given email address."""88 return 'http://www.gravatar.com/avatar/%s?d=identicon&s=%d' % \89 (md5(email.strip().lower().encode('utf-8')).hexdigest(), size)909192@app.before_request93def before_request():94 g.user = None95 if 'user_id' in session:96 g.user = query_db('select * from user where user_id = ?',97 [session['user_id']], one=True)9899100@app.route('/')101def timeline():102 """Shows a users timeline or if no user is logged in it will103 redirect to the public timeline. This timeline shows the user's104 messages as well as all the messages of followed users.105 """106 if not g.user:107 return redirect(url_for('public_timeline'))108 return render_template('timeline.html', messages=query_db('''109 select message.*, user.* from message, user110 where message.author_id = user.user_id and (111 user.user_id = ? or112 user.user_id in (select whom_id from follower113 where who_id = ?))114 order by message.pub_date desc limit ?''',115 [session['user_id'], session['user_id'], PER_PAGE]))116117118@app.route('/public')119def public_timeline():120 """Displays the latest messages of all users."""121 return render_template('timeline.html', messages=query_db('''122 select message.*, user.* from message, user123 where message.author_id = user.user_id124 order by message.pub_date desc limit ?''', [PER_PAGE]))125126127@app.route('/<username>')128def user_timeline(username):129 """Display's a users tweets."""130 profile_user = query_db('select * from user where username = ?',131 [username], one=True)132 if profile_user is None:133 abort(404)134 followed = False135 if g.user:136 followed = query_db('''select 1 from follower where137 follower.who_id = ? and follower.whom_id = ?''',138 [session['user_id'], profile_user['user_id']],139 one=True) is not None140 return render_template('timeline.html', messages=query_db('''141 select message.*, user.* from message, user where142 user.user_id = message.author_id and user.user_id = ?143 order by message.pub_date desc limit ?''',144 [profile_user['user_id'], PER_PAGE]), followed=followed,145 profile_user=profile_user)146147148@app.route('/<username>/follow')149def follow_user(username):150 """Adds the current user as follower of the given user."""151 if not g.user:152 abort(401)153 whom_id = get_user_id(username)154 if whom_id is None:155 abort(404)156 db = get_db()157 db.execute('insert into follower (who_id, whom_id) values (?, ?)',158 [session['user_id'], whom_id])159 db.commit()160 flash('You are now following "%s"' % username)161 return redirect(url_for('user_timeline', username=username))162163164@app.route('/<username>/unfollow')165def unfollow_user(username):166 """Removes the current user as follower of the given user."""167 if not g.user:168 abort(401)169 whom_id = get_user_id(username)170 if whom_id is None:171 abort(404)172 db = get_db()173 db.execute('delete from follower where who_id=? and whom_id=?',174 [session['user_id'], whom_id])175 db.commit()176 flash('You are no longer following "%s"' % username)177 return redirect(url_for('user_timeline', username=username))178179180@app.route('/add_message', methods=['POST'])181def add_message():182 """Registers a new message for the user."""183 if 'user_id' not in session:184 abort(401)185 if request.form['text']:186 db = get_db()187 db.execute('''insert into message (author_id, text, pub_date)188 values (?, ?, ?)''', (session['user_id'], request.form['text'],189 int(time.time())))190 db.commit()191 flash('Your message was recorded')192 return redirect(url_for('timeline'))193194195@app.route('/login', methods=['GET', 'POST'])196def login():197 """Logs the user in."""198 if g.user:199 return redirect(url_for('timeline'))200 error = None201 if request.method == 'POST':202 user = query_db('''select * from user where203 username = ?''', [request.form['username']], one=True)204 if user is None:205 error = 'Invalid username'206 elif not check_password_hash(user['pw_hash'],207 request.form['password']):208 error = 'Invalid password'209 else:210 flash('You were logged in')211 session['user_id'] = user['user_id']212 return redirect(url_for('timeline'))213 return render_template('login.html', error=error)214215216@app.route('/register', methods=['GET', 'POST'])217def register():218 """Registers the user."""219 if g.user:220 return redirect(url_for('timeline'))221 error = None222 if request.method == 'POST':223 if not request.form['username']:224 error = 'You have to enter a username'225 elif not request.form['email'] or \226 '@' not in request.form['email']:227 error = 'You have to enter a valid email address'228 elif not request.form['password']:229 error = 'You have to enter a password'230 elif request.form['password'] != request.form['password2']:231 error = 'The two passwords do not match'232 elif get_user_id(request.form['username']) is not None:233 error = 'The username is already taken'234 else:235 db = get_db()236 db.execute('''insert into user (237 username, email, pw_hash) values (?, ?, ?)''',238 [request.form['username'], request.form['email'],239 generate_password_hash(request.form['password'])])240 db.commit()241 flash('You were successfully registered and can login now')242 return redirect(url_for('login'))243 return render_template('register.html', error=error)244245246@app.route('/logout')247def logout():248 """Logs the user out."""249 flash('You were logged out')250 session.pop('user_id', None)251 return redirect(url_for('public_timeline'))252253254# add some filters to jinja255app.jinja_env.filters['datetimeformat'] = format_datetime256app.jinja_env.filters['gravatar'] = gravatar_url
modified:examples/minitwit/README+1 added-1 removed
29 unmodified lines
30 http://localhost:5000/3132 ~ Is it tested?3334 You betcha. Run the `test_minitwit.py` file to34 You betcha. Run the `python setup.py test` file to35 see the tests pass.
deleted:examples/minitwit/schema.sql-21 removed
1drop table if exists user;2create table user (3 user_id integer primary key autoincrement,4 username text not null,5 email text not null,6 pw_hash text not null7);89drop table if exists follower;10create table follower (11 who_id integer,12 whom_id integer13);1415drop table if exists message;16create table message (17 message_id integer primary key autoincrement,18 author_id integer not null,19 text text not null,20 pub_date integer21);
added:examples/minitwit/setup.cfg+2 added
1[aliases]2test=pytest
added:examples/minitwit/setup.py+16 added
1from setuptools import setup23setup(4 name='minitwit',5 packages=['minitwit'],6 include_package_data=True,7 install_requires=[8 'flask',9 ],10 setup_requires=[11 'pytest-runner',12 ],13 tests_require=[14 'pytest',15 ],16)
deleted:examples/minitwit/test_minitwit.py-151 removed
1# -*- coding: utf-8 -*-2"""3 MiniTwit Tests4 ~~~~~~~~~~~~~~56 Tests the MiniTwit application.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import os12import minitwit13import tempfile14import pytest151617@pytest.fixture18def client(request):19 db_fd, minitwit.app.config['DATABASE'] = tempfile.mkstemp()20 client = minitwit.app.test_client()21 with minitwit.app.app_context():22 minitwit.init_db()2324 def teardown():25 """Get rid of the database again after each test."""26 os.close(db_fd)27 os.unlink(minitwit.app.config['DATABASE'])28 request.addfinalizer(teardown)29 return client303132def register(client, username, password, password2=None, email=None):33 """Helper function to register a user"""34 if password2 is None:35 password2 = password36 if email is None:37 email = username + '@example.com'38 return client.post('/register', data={39 'username': username,40 'password': password,41 'password2': password2,42 'email': email,43 }, follow_redirects=True)444546def login(client, username, password):47 """Helper function to login"""48 return client.post('/login', data={49 'username': username,50 'password': password51 }, follow_redirects=True)525354def register_and_login(client, username, password):55 """Registers and logs in in one go"""56 register(client, username, password)57 return login(client, username, password)585960def logout(client):61 """Helper function to logout"""62 return client.get('/logout', follow_redirects=True)636465def add_message(client, text):66 """Records a message"""67 rv = client.post('/add_message', data={'text': text},68 follow_redirects=True)69 if text:70 assert b'Your message was recorded' in rv.data71 return rv727374def test_register(client):75 """Make sure registering works"""76 rv = register(client, 'user1', 'default')77 assert b'You were successfully registered ' \78 b'and can login now' in rv.data79 rv = register(client, 'user1', 'default')80 assert b'The username is already taken' in rv.data81 rv = register(client, '', 'default')82 assert b'You have to enter a username' in rv.data83 rv = register(client, 'meh', '')84 assert b'You have to enter a password' in rv.data85 rv = register(client, 'meh', 'x', 'y')86 assert b'The two passwords do not match' in rv.data87 rv = register(client, 'meh', 'foo', email='broken')88 assert b'You have to enter a valid email address' in rv.data899091def test_login_logout(client):92 """Make sure logging in and logging out works"""93 rv = register_and_login(client, 'user1', 'default')94 assert b'You were logged in' in rv.data95 rv = logout(client)96 assert b'You were logged out' in rv.data97 rv = login(client, 'user1', 'wrongpassword')98 assert b'Invalid password' in rv.data99 rv = login(client, 'user2', 'wrongpassword')100 assert b'Invalid username' in rv.data101102103def test_message_recording(client):104 """Check if adding messages works"""105 register_and_login(client, 'foo', 'default')106 add_message(client, 'test message 1')107 add_message(client, '<test message 2>')108 rv = client.get('/')109 assert b'test message 1' in rv.data110 assert b'&lt;test message 2&gt;' in rv.data111112113def test_timelines(client):114 """Make sure that timelines work"""115 register_and_login(client, 'foo', 'default')116 add_message(client, 'the message by foo')117 logout(client)118 register_and_login(client, 'bar', 'default')119 add_message(client, 'the message by bar')120 rv = client.get('/public')121 assert b'the message by foo' in rv.data122 assert b'the message by bar' in rv.data123124 # bar's timeline should just show bar's message125 rv = client.get('/')126 assert b'the message by foo' not in rv.data127 assert b'the message by bar' in rv.data128129 # now let's follow foo130 rv = client.get('/foo/follow', follow_redirects=True)131 assert b'You are now following &#34;foo&#34;' in rv.data132133 # we should now see foo's message134 rv = client.get('/')135 assert b'the message by foo' in rv.data136 assert b'the message by bar' in rv.data137138 # but on the user's page we only want the user's message139 rv = client.get('/bar')140 assert b'the message by foo' not in rv.data141 assert b'the message by bar' in rv.data142 rv = client.get('/foo')143 assert b'the message by foo' in rv.data144 assert b'the message by bar' not in rv.data145146 # now unfollow and check if that worked147 rv = client.get('/foo/unfollow', follow_redirects=True)148 assert b'You are no longer following &#34;foo&#34;' in rv.data149 rv = client.get('/')150 assert b'the message by foo' not in rv.data151 assert b'the message by bar' in rv.data
modified:setup.cfg+1 added-1 removed
3 unmodified lines
4[wheel]5universal = 167[pytest]8norecursedirs = .* *.egg *.egg-info env* artwork docs8norecursedirs = .* *.egg *.egg-info env* artwork docs examples