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
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
Provenance
- Commit
5f00937- Tree
800c0f3- Author
Kyle Lawlor <wgwz@users.noreply.github.com>- Committer
Markus Unterwaditzer <markus@unterwaditzer.net>- Parent
1e5746b
25 files changed+750 added−732 removed
deleted:examples/flaskr/tests/context.py-6 removed
1-import sys, os2-3-basedir = os.path.dirname(os.path.abspath(__file__))4-sys.path.insert(0, basedir + '/../')5-6-from flaskr import flaskrmodified:examples/flaskr/tests/test_flaskr.py+2 added-2 removed
7 unmodified lines8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12-import pytest12 import os13 import tempfile14+import pytest15+from flaskr import flaskr16 16-from context import flaskr17 18 @pytest.fixture19 def client(request):20 db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()56 unmodified linesadded:examples/minitwit/minitwit/static/style.css+178 added
1+body {2+ background: #CAECE9;3+ font-family: 'Trebuchet MS', sans-serif;4+ font-size: 14px;5+}6+7+a {8+ color: #26776F;9+}10+11+a:hover {12+ color: #333;13+}14+15+input[type="text"],16+input[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+}26+27+input[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+}38+39+div.page {40+ background: white;41+ border: 1px solid #6ECCC4;42+ width: 700px;43+ margin: 30px auto;44+}45+46+div.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+}55+56+div.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+}65+66+div.page div.navigation a {67+ color: #444;68+ font-weight: bold;69+}70+71+div.page h2 {72+ margin: 0 0 15px 0;73+ color: #105751;74+ text-shadow: 0 1px 2px #ccc;75+}76+77+div.page div.body {78+ padding: 10px;79+}80+81+div.page div.footer {82+ background: #eee;83+ color: #888;84+ padding: 5px 10px;85+ font-size: 12px;86+}87+88+div.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+}96+97+div.page ul.messages {98+ list-style: none;99+ margin: 0;100+ padding: 0;101+}102+103+div.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+}112+113+div.page ul.messages p {114+ margin: 0;115+}116+117+div.page ul.messages li img {118+ float: left;119+ padding: 0 10px 0 0;120+}121+122+div.page ul.messages li small {123+ font-size: 0.9em;124+ color: #888;125+}126+127+div.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+}135+136+div.page div.twitbox h3 {137+ margin: 0;138+ font-size: 1em;139+ color: #2C7E76;140+}141+142+div.page div.twitbox p {143+ margin: 0;144+}145+146+div.page div.twitbox input[type="text"] {147+ width: 585px;148+}149+150+div.page div.twitbox input[type="submit"] {151+ width: 70px;152+ margin-left: 5px;153+}154+155+ul.flashes {156+ list-style: none;157+ margin: 10px 10px 0 10px;158+ padding: 0;159+}160+161+ul.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+}169+170+div.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
1234567891011121314151617181920212223242526272829303132<!doctype html><title>{% block title %}Welcome{% endblock %} | MiniTwit</title><link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}"><div class="page"> <h1>MiniTwit</h1> <div class="navigation"> {% if g.user %} <a href="{{ url_for('timeline') }}">my timeline</a> | <a href="{{ url_for('public_timeline') }}">public timeline</a> | <a href="{{ url_for('logout') }}">sign out [{{ g.user.username }}]</a> {% else %} <a href="{{ url_for('public_timeline') }}">public timeline</a> | <a href="{{ url_for('register') }}">sign up</a> | <a href="{{ url_for('login') }}">sign in</a> {% endif %} </div> {% with flashes = get_flashed_messages() %} {% if flashes %} <ul class="flashes"> {% for message in flashes %} <li>{{ message }} {% endfor %} </ul> {% endif %} {% endwith %} <div class="body"> {% block body %}{% endblock %} </div> <div class="footer"> MiniTwit — A Flask Application </div></div>added:examples/minitwit/minitwit/templates/login.html+16 added
12345678910111213141516{% extends "layout.html" %}{% block title %}Sign In{% endblock %}{% block body %} <h2>Sign In</h2> {% if error %}<div class="error"><strong>Error:</strong> {{ error }}</div>{% endif %} <form action="" method="post"> <dl> <dt>Username: <dd><input type="text" name="username" size="30" value="{{ request.form.username }}"> <dt>Password: <dd><input type="password" name="password" size="30"> </dl> <div class="actions"><input type="submit" value="Sign In"></div> </form>{% endblock %}
added:examples/minitwit/minitwit/templates/register.html+19 added
12345678910111213141516171819{% extends "layout.html" %}{% block title %}Sign Up{% endblock %}{% block body %} <h2>Sign Up</h2> {% if error %}<div class="error"><strong>Error:</strong> {{ error }}</div>{% endif %} <form action="" method="post"> <dl> <dt>Username: <dd><input type="text" name="username" size="30" value="{{ request.form.username }}"> <dt>E-Mail: <dd><input type="text" name="email" size="30" value="{{ request.form.email }}"> <dt>Password: <dd><input type="password" name="password" size="30"> <dt>Password <small>(repeat)</small>: <dd><input type="password" name="password2" size="30"> </dl> <div class="actions"><input type="submit" value="Sign Up"></div> </form>{% endblock %}added:examples/minitwit/minitwit/templates/timeline.html+49 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849{% extends "layout.html" %}{% block title %} {% if request.endpoint == 'public_timeline' %} Public Timeline {% elif request.endpoint == 'user_timeline' %} {{ profile_user.username }}'s Timeline {% else %} My Timeline {% endif %}{% endblock %}{% block body %} <h2>{{ self.title() }}</h2> {% if g.user %} {% if request.endpoint == 'user_timeline' %} <div class="followstatus"> {% if g.user.user_id == profile_user.user_id %} This is you! {% elif followed %} You are currently following this user. <a class="unfollow" href="{{ url_for('unfollow_user', username=profile_user.username) }}">Unfollow user</a>. {% else %} You are not yet following this user. <a class="follow" href="{{ url_for('follow_user', username=profile_user.username) }}">Follow user</a>. {% endif %} </div> {% elif request.endpoint == 'timeline' %} <div class="twitbox"> <h3>What's on your mind {{ g.user.username }}?</h3> <form action="{{ url_for('add_message') }}" method="post"> <p><input type="text" name="text" size="60"><!-- --><input type="submit" value="Share"> </form> </div> {% endif %} {% endif %} <ul class="messages"> {% for message in messages %} <li><img src="{{ message.email|gravatar(size=48) }}"><p> <strong><a href="{{ url_for('user_timeline', username=message.username) }}">{{ message.username }}</a></strong> {{ message.text }} <small>— {{ message.pub_date|datetimeformat }}</small> {% else %} <li><em>There's no message so far.</em> {% endfor %} </ul>{% endblock %}added:examples/minitwit/minitwit/__init__.py+1 added
1+from minitwit import appadded:examples/minitwit/minitwit/minitwit.py+256 added
1+# -*- coding: utf-8 -*-2+"""3+ MiniTwit4+ ~~~~~~~~5+6+ A microblogging application written with Flask and sqlite3.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import time13+from sqlite3 import dbapi2 as sqlite314+from hashlib import md515+from datetime import datetime16+from flask import Flask, request, session, url_for, redirect, \17+ render_template, abort, g, flash, _app_ctx_stack18+from werkzeug import check_password_hash, generate_password_hash19+20+21+# configuration22+DATABASE = '/tmp/minitwit.db'23+PER_PAGE = 3024+DEBUG = True25+SECRET_KEY = 'development key'26+27+# create our little application :)28+app = Flask(__name__)29+app.config.from_object(__name__)30+app.config.from_envvar('MINITWIT_SETTINGS', silent=True)31+32+33+def 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_db42+43+44+@app.teardown_appcontext45+def 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()50+51+52+def 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()58+59+60+@app.cli.command('initdb')61+def initdb_command():62+ """Creates the database tables."""63+ init_db()64+ print('Initialized the database.')65+66+67+def 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 rv72+73+74+def 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 None79+80+81+def format_datetime(timestamp):82+ """Format a timestamp for display."""83+ return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d @ %H:%M')84+85+86+def 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)90+91+92+@app.before_request93+def 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)98+99+100+@app.route('/')101+def 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]))116+117+118+@app.route('/public')119+def 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]))125+126+127+@app.route('/<username>')128+def 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)146+147+148+@app.route('/<username>/follow')149+def 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))162+163+164+@app.route('/<username>/unfollow')165+def 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))178+179+180+@app.route('/add_message', methods=['POST'])181+def 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'))193+194+195+@app.route('/login', methods=['GET', 'POST'])196+def 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)214+215+216+@app.route('/register', methods=['GET', 'POST'])217+def 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)244+245+246+@app.route('/logout')247+def 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'))252+253+254+# add some filters to jinja255+app.jinja_env.filters['datetimeformat'] = format_datetime256+app.jinja_env.filters['gravatar'] = gravatar_urladded:examples/minitwit/minitwit/schema.sql+21 added
1+drop table if exists user;2+create 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+);8+9+drop table if exists follower;10+create table follower (11+ who_id integer,12+ whom_id integer13+);14+15+drop table if exists message;16+create 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
1-body {2- background: #CAECE9;3- font-family: 'Trebuchet MS', sans-serif;4- font-size: 14px;5-}6-7-a {8- color: #26776F;9-}10-11-a:hover {12- color: #333;13-}14-15-input[type="text"],16-input[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-}26-27-input[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-}38-39-div.page {40- background: white;41- border: 1px solid #6ECCC4;42- width: 700px;43- margin: 30px auto;44-}45-46-div.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-}55-56-div.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-}65-66-div.page div.navigation a {67- color: #444;68- font-weight: bold;69-}70-71-div.page h2 {72- margin: 0 0 15px 0;73- color: #105751;74- text-shadow: 0 1px 2px #ccc;75-}76-77-div.page div.body {78- padding: 10px;79-}80-81-div.page div.footer {82- background: #eee;83- color: #888;84- padding: 5px 10px;85- font-size: 12px;86-}87-88-div.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-}96-97-div.page ul.messages {98- list-style: none;99- margin: 0;100- padding: 0;101-}102-103-div.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-}112-113-div.page ul.messages p {114- margin: 0;115-}116-117-div.page ul.messages li img {118- float: left;119- padding: 0 10px 0 0;120-}121-122-div.page ul.messages li small {123- font-size: 0.9em;124- color: #888;125-}126-127-div.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-}135-136-div.page div.twitbox h3 {137- margin: 0;138- font-size: 1em;139- color: #2C7E76;140-}141-142-div.page div.twitbox p {143- margin: 0;144-}145-146-div.page div.twitbox input[type="text"] {147- width: 585px;148-}149-150-div.page div.twitbox input[type="submit"] {151- width: 70px;152- margin-left: 5px;153-}154-155-ul.flashes {156- list-style: none;157- margin: 10px 10px 0 10px;158- padding: 0;159-}160-161-ul.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-}169-170-div.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 — 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>— {{ 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+ ~~~~~~~~~~~~~~5+6+ Tests the MiniTwit application.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+import os12+import tempfile13+import pytest14+from minitwit import minitwit15+16+17+@pytest.fixture18+def 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()23+24+ 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 client30+31+32+def 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)44+45+46+def login(client, username, password):47+ """Helper function to login"""48+ return client.post('/login', data={49+ 'username': username,50+ 'password': password51+ }, follow_redirects=True)52+53+54+def 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)58+59+60+def logout(client):61+ """Helper function to logout"""62+ return client.get('/logout', follow_redirects=True)63+64+65+def 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 rv72+73+74+def 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.data89+90+91+def 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.data101+102+103+def 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'<test message 2>' in rv.data111+112+113+def 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.data123+124+ # 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.data128+129+ # now let's follow foo130+ rv = client.get('/foo/follow', follow_redirects=True)131+ assert b'You are now following "foo"' in rv.data132+133+ # 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.data137+138+ # 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.data145+146+ # now unfollow and check if that worked147+ rv = client.get('/foo/unfollow', follow_redirects=True)148+ assert b'You are no longer following "foo"' 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.dataadded:examples/minitwit/.gitignore+2 added
1+minitwit.db2+.eggs/added:examples/minitwit/MANIFEST.in+3 added
1+graft minitwit/templates2+graft minitwit/static3+include minitwit/schema.sqldeleted:examples/minitwit/minitwit.py-256 removed
1-# -*- coding: utf-8 -*-2-"""3- MiniTwit4- ~~~~~~~~5-6- A microblogging application written with Flask and sqlite3.7-8- :copyright: (c) 2015 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-12-import time13-from sqlite3 import dbapi2 as sqlite314-from hashlib import md515-from datetime import datetime16-from flask import Flask, request, session, url_for, redirect, \17- render_template, abort, g, flash, _app_ctx_stack18-from werkzeug import check_password_hash, generate_password_hash19-20-21-# configuration22-DATABASE = '/tmp/minitwit.db'23-PER_PAGE = 3024-DEBUG = True25-SECRET_KEY = 'development key'26-27-# create our little application :)28-app = Flask(__name__)29-app.config.from_object(__name__)30-app.config.from_envvar('MINITWIT_SETTINGS', silent=True)31-32-33-def 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_db42-43-44-@app.teardown_appcontext45-def 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()50-51-52-def 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()58-59-60-@app.cli.command('initdb')61-def initdb_command():62- """Creates the database tables."""63- init_db()64- print('Initialized the database.')65-66-67-def 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 rv72-73-74-def 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 None79-80-81-def format_datetime(timestamp):82- """Format a timestamp for display."""83- return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d @ %H:%M')84-85-86-def 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)90-91-92-@app.before_request93-def 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)98-99-100-@app.route('/')101-def 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]))116-117-118-@app.route('/public')119-def 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]))125-126-127-@app.route('/<username>')128-def 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)146-147-148-@app.route('/<username>/follow')149-def 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))162-163-164-@app.route('/<username>/unfollow')165-def 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))178-179-180-@app.route('/add_message', methods=['POST'])181-def 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'))193-194-195-@app.route('/login', methods=['GET', 'POST'])196-def 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)214-215-216-@app.route('/register', methods=['GET', 'POST'])217-def 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)244-245-246-@app.route('/logout')247-def 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'))252-253-254-# add some filters to jinja255-app.jinja_env.filters['datetimeformat'] = format_datetime256-app.jinja_env.filters['gravatar'] = gravatar_urlmodified:examples/minitwit/README+1 added-1 removed
29 unmodified lines30 http://localhost:5000/31 32 ~ Is it tested?33 34- 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
1-drop table if exists user;2-create 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-);8-9-drop table if exists follower;10-create table follower (11- who_id integer,12- whom_id integer13-);14-15-drop table if exists message;16-create 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]2+test=pytestadded:examples/minitwit/setup.py+16 added
1+from setuptools import setup2+3+setup(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- ~~~~~~~~~~~~~~5-6- Tests the MiniTwit application.7-8- :copyright: (c) 2015 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-import os12-import minitwit13-import tempfile14-import pytest15-16-17-@pytest.fixture18-def 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()23-24- 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 client30-31-32-def 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)44-45-46-def login(client, username, password):47- """Helper function to login"""48- return client.post('/login', data={49- 'username': username,50- 'password': password51- }, follow_redirects=True)52-53-54-def 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)58-59-60-def logout(client):61- """Helper function to logout"""62- return client.get('/logout', follow_redirects=True)63-64-65-def 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 rv72-73-74-def 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.data89-90-91-def 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.data101-102-103-def 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'<test message 2>' in rv.data111-112-113-def 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.data123-124- # 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.data128-129- # now let's follow foo130- rv = client.get('/foo/follow', follow_redirects=True)131- assert b'You are now following "foo"' in rv.data132-133- # 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.data137-138- # 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.data145-146- # now unfollow and check if that worked147- rv = client.get('/foo/unfollow', follow_redirects=True)148- assert b'You are no longer following "foo"' 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.datamodified:setup.cfg+1 added-1 removed
3 unmodified lines4 [wheel]5 universal = 16 7 [pytest]8-norecursedirs = .* *.egg *.egg-info env* artwork docs8+norecursedirs = .* *.egg *.egg-info env* artwork docs examples