Merge pull request #2228 from wgwz/improve-flaskr
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Add blueprint and the app factory pattern into the flaskr example
authored by Kenneth Reitz · committed by GitHub · parents cf926b8, e6740ec · Browse files · 13 files·+227 added−142 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+227 added−142 removed
- tests:+39 added−20 removed
- other:+188 added−122 removed
Provenance
- Commit
a63a4cb- Tree
588bf53- Author
Kenneth Reitz <me@kennethreitz.org>- Committer
GitHub <noreply@github.com>- Parent 1
cf926b8- Parent 2
e6740ec
13 files changed+227 added−142 removed
added:examples/flaskr/flaskr/blueprints/__init__.py
added:examples/flaskr/flaskr/blueprints/flaskr.py+85 added
1+# -*- coding: utf-8 -*-2+"""3+ Flaskr4+ ~~~~~~5+6+ A microblog example application written as Flask tutorial with7+ Flask and sqlite3.8+9+ :copyright: (c) 2015 by Armin Ronacher.10+ :license: BSD, see LICENSE for more details.11+"""12+13+from sqlite3 import dbapi2 as sqlite314+from flask import Blueprint, request, session, g, redirect, url_for, abort, \15+ render_template, flash, current_app16+17+18+# create our blueprint :)19+bp = Blueprint('flaskr', __name__)20+21+22+def connect_db():23+ """Connects to the specific database."""24+ rv = sqlite3.connect(current_app.config['DATABASE'])25+ rv.row_factory = sqlite3.Row26+ return rv27+28+29+def init_db():30+ """Initializes the database."""31+ db = get_db()32+ with current_app.open_resource('schema.sql', mode='r') as f:33+ db.cursor().executescript(f.read())34+ db.commit()35+36+37+def get_db():38+ """Opens a new database connection if there is none yet for the39+ current application context.40+ """41+ if not hasattr(g, 'sqlite_db'):42+ g.sqlite_db = connect_db()43+ return g.sqlite_db44+45+46+@bp.route('/')47+def show_entries():48+ db = get_db()49+ cur = db.execute('select title, text from entries order by id desc')50+ entries = cur.fetchall()51+ return render_template('show_entries.html', entries=entries)52+53+54+@bp.route('/add', methods=['POST'])55+def add_entry():56+ if not session.get('logged_in'):57+ abort(401)58+ db = get_db()59+ db.execute('insert into entries (title, text) values (?, ?)',60+ [request.form['title'], request.form['text']])61+ db.commit()62+ flash('New entry was successfully posted')63+ return redirect(url_for('flaskr.show_entries'))64+65+66+@bp.route('/login', methods=['GET', 'POST'])67+def login():68+ error = None69+ if request.method == 'POST':70+ if request.form['username'] != current_app.config['USERNAME']:71+ error = 'Invalid username'72+ elif request.form['password'] != current_app.config['PASSWORD']:73+ error = 'Invalid password'74+ else:75+ session['logged_in'] = True76+ flash('You were logged in')77+ return redirect(url_for('flaskr.show_entries'))78+ return render_template('login.html', error=error)79+80+81+@bp.route('/logout')82+def logout():83+ session.pop('logged_in', None)84+ flash('You were logged out')85+ return redirect(url_for('flaskr.show_entries'))modified:examples/flaskr/flaskr/templates/layout.html+2 added-2 removed
3 unmodified lines45678891010111213143 unmodified lines3 unmodified lines<div class="page"> <h1>Flaskr</h1> <div class="metanav"> {% if not session.logged_in %} <a href="{{ url_for('login') }}">log in</a> <a href="{{ url_for('flaskr.login') }}">log in</a> {% else %} <a href="{{ url_for('logout') }}">log out</a> <a href="{{ url_for('flaskr.logout') }}">log out</a> {% endif %} </div> {% for message in get_flashed_messages() %} <div class="flash">{{ message }}</div>3 unmodified linesmodified:examples/flaskr/flaskr/templates/login.html+1 added-1 removed
12345567895 unmodified lines{% extends "layout.html" %}{% block body %} <h2>Login</h2> {% if error %}<p class="error"><strong>Error:</strong> {{ error }}{% endif %} <form action="{{ url_for('login') }}" method="post"> <form action="{{ url_for('flaskr.login') }}" method="post"> <dl> <dt>Username: <dd><input type="text" name="username"> <dt>Password:5 unmodified linesmodified:examples/flaskr/flaskr/templates/show_entries.html+1 added-1 removed
12344567813 unmodified lines{% extends "layout.html" %}{% block body %} {% if session.logged_in %} <form action="{{ url_for('add_entry') }}" method="post" class="add-entry"> <form action="{{ url_for('flaskr.add_entry') }}" method="post" class="add-entry"> <dl> <dt>Title: <dd><input type="text" size="30" name="title"> <dt>Text:13 unmodified linesmodified:examples/flaskr/flaskr/__init__.py-1 removed
1-from .flaskr import appadded:examples/flaskr/flaskr/_cliapp.py+15 added
1+# -*- coding: utf-8 -*-2+"""3+ Flaskr4+ ~~~~~~5+6+ A microblog example application written as Flask tutorial with7+ Flask and sqlite3.8+9+ :copyright: (c) 2015 by Armin Ronacher.10+ :license: BSD, see LICENSE for more details.11+"""12+13+from flaskr.factory import create_app14+15+app = create_app()added:examples/flaskr/flaskr/factory.py+64 added
1+# -*- coding: utf-8 -*-2+"""3+ Flaskr4+ ~~~~~~5+6+ A microblog example application written as Flask tutorial with7+ Flask and sqlite3.8+9+ :copyright: (c) 2015 by Armin Ronacher.10+ :license: BSD, see LICENSE for more details.11+"""12+13+import os14+from flask import Flask, g15+from werkzeug.utils import find_modules, import_string16+from flaskr.blueprints.flaskr import init_db17+18+19+def create_app(config=None):20+ app = Flask(__name__)21+22+ app.config.update(dict(23+ DATABASE=os.path.join(app.root_path, 'flaskr.db'),24+ DEBUG=True,25+ SECRET_KEY='development key',26+ USERNAME='admin',27+ PASSWORD='default'28+ ))29+ app.config.update(config or {})30+ app.config.from_envvar('FLASKR_SETTINGS', silent=True)31+32+ register_blueprints(app)33+ register_cli(app)34+ register_teardowns(app)35+36+ return app37+38+39+def register_blueprints(app):40+ """Register all blueprint modules41+42+ Reference: Armin Ronacher, "Flask for Fun and for Profit" PyBay 2016.43+ """44+ for name in find_modules('flaskr.blueprints'):45+ mod = import_string(name)46+ if hasattr(mod, 'bp'):47+ app.register_blueprint(mod.bp)48+ return None49+50+51+def register_cli(app):52+ @app.cli.command('initdb')53+ def initdb_command():54+ """Creates the database tables."""55+ init_db()56+ print('Initialized the database.')57+58+59+def register_teardowns(app):60+ @app.teardown_appcontext61+ def close_db(error):62+ """Closes the database again at the end of the request."""63+ if hasattr(g, 'sqlite_db'):64+ g.sqlite_db.close()deleted:examples/flaskr/flaskr/flaskr.py-110 removed
1-# -*- coding: utf-8 -*-2-"""3- Flaskr4- ~~~~~~5-6- A microblog example application written as Flask tutorial with7- Flask and sqlite3.8-9- :copyright: (c) 2015 by Armin Ronacher.10- :license: BSD, see LICENSE for more details.11-"""12-13-import os14-from sqlite3 import dbapi2 as sqlite315-from flask import Flask, request, session, g, redirect, url_for, abort, \16- render_template, flash17-18-19-# create our little application :)20-app = Flask(__name__)21-22-# Load default config and override config from an environment variable23-app.config.update(dict(24- DATABASE=os.path.join(app.root_path, 'flaskr.db'),25- DEBUG=True,26- SECRET_KEY='development key',27- USERNAME='admin',28- PASSWORD='default'29-))30-app.config.from_envvar('FLASKR_SETTINGS', silent=True)31-32-33-def connect_db():34- """Connects to the specific database."""35- rv = sqlite3.connect(app.config['DATABASE'])36- rv.row_factory = sqlite3.Row37- return rv38-39-40-def init_db():41- """Initializes the database."""42- db = get_db()43- with app.open_resource('schema.sql', mode='r') as f:44- db.cursor().executescript(f.read())45- db.commit()46-47-48-@app.cli.command('initdb')49-def initdb_command():50- """Creates the database tables."""51- init_db()52- print('Initialized the database.')53-54-55-def get_db():56- """Opens a new database connection if there is none yet for the57- current application context.58- """59- if not hasattr(g, 'sqlite_db'):60- g.sqlite_db = connect_db()61- return g.sqlite_db62-63-64-@app.teardown_appcontext65-def close_db(error):66- """Closes the database again at the end of the request."""67- if hasattr(g, 'sqlite_db'):68- g.sqlite_db.close()69-70-71-@app.route('/')72-def show_entries():73- db = get_db()74- cur = db.execute('select title, text from entries order by id desc')75- entries = cur.fetchall()76- return render_template('show_entries.html', entries=entries)77-78-79-@app.route('/add', methods=['POST'])80-def add_entry():81- if not session.get('logged_in'):82- abort(401)83- db = get_db()84- db.execute('insert into entries (title, text) values (?, ?)',85- [request.form['title'], request.form['text']])86- db.commit()87- flash('New entry was successfully posted')88- return redirect(url_for('show_entries'))89-90-91-@app.route('/login', methods=['GET', 'POST'])92-def login():93- error = None94- if request.method == 'POST':95- if request.form['username'] != app.config['USERNAME']:96- error = 'Invalid username'97- elif request.form['password'] != app.config['PASSWORD']:98- error = 'Invalid password'99- else:100- session['logged_in'] = True101- flash('You were logged in')102- return redirect(url_for('show_entries'))103- return render_template('login.html', error=error)104-105-106-@app.route('/logout')107-def logout():108- session.pop('logged_in', None)109- flash('You were logged out')110- return redirect(url_for('show_entries'))modified:examples/flaskr/tests/test_flaskr.py+39 added-20 removed
10 unmodified lines11 12 import os13 import tempfile14 import pytest15-from flaskr import flaskr15+from flaskr.factory import create_app16+from flaskr.blueprints.flaskr import init_db17 18 19 @pytest.fixture19-def client():20- db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()21- flaskr.app.config['TESTING'] = True22- client = flaskr.app.test_client()23- with flaskr.app.app_context():24- flaskr.init_db()25- yield client26- os.close(db_fd)27- os.unlink(flaskr.app.config['DATABASE'])20+def app(request):21 22+ db_fd, temp_db_location = tempfile.mkstemp()23+ config = {24+ 'DATABASE': temp_db_location,25+ 'TESTING': True,26+ 'DB_FD': db_fd27+ }28 29+ app = create_app(config=config)30+31+ with app.app_context():32+ init_db()33+ yield app34+35+36+@pytest.fixture37+def client(request, app):38+39+ client = app.test_client()40+41+ def teardown():42+ os.close(app.config['DB_FD'])43+ os.unlink(app.config['DATABASE'])44+ request.addfinalizer(teardown)45+46+ return client47+48+49 def login(client, username, password):50 return client.post('/login', data=dict(51 username=username,52 password=password9 unmodified lines62 rv = client.get('/')63 assert b'No entries here so far' in rv.data64 65 47-def test_login_logout(client):66+def test_login_logout(client, app):67 """Make sure login and logout works"""49- rv = login(client, flaskr.app.config['USERNAME'],50- flaskr.app.config['PASSWORD'])68+ rv = login(client, app.config['USERNAME'],69+ app.config['PASSWORD'])70 assert b'You were logged in' in rv.data71 rv = logout(client)72 assert b'You were logged out' in rv.data54- rv = login(client, flaskr.app.config['USERNAME'] + 'x',55- flaskr.app.config['PASSWORD'])73+ rv = login(client,app.config['USERNAME'] + 'x',74+ app.config['PASSWORD'])75 assert b'Invalid username' in rv.data57- rv = login(client, flaskr.app.config['USERNAME'],58- flaskr.app.config['PASSWORD'] + 'x')76+ rv = login(client, app.config['USERNAME'],77+ app.config['PASSWORD'] + 'x')78 assert b'Invalid password' in rv.data79 80 62-def test_messages(client):81+def test_messages(client, app):82 """Test that messages work"""64- login(client, flaskr.app.config['USERNAME'],65- flaskr.app.config['PASSWORD'])83+ login(client, app.config['USERNAME'],84+ app.config['PASSWORD'])85 rv = client.post('/add', data=dict(86 title='<Hello>',87 text='<strong>HTML</strong> allowed here'88 ), follow_redirects=True)3 unmodified linesmodified:examples/flaskr/README+5 added-3 removed
7 unmodified lines8 A sqlite powered thumble blog application9 10 ~ How do I use it?11 12- 1. edit the configuration in the flaskr.py file or12+ 1. edit the configuration in the factory.py file or13 export an FLASKR_SETTINGS environment variable14- pointing to a configuration file.14+ pointing to a configuration file or pass in a 15+ dictionary with config values using the create_app16+ function.17 18 2. install the app from the root of the project directory19 20 pip install --editable .21 22 3. Instruct flask to use the right application23 22- export FLASK_APP=flaskr24+ export FLASK_APP=flaskr._cliapp25 26 4. initialize the database with this command:27 28 flask initdb12 unmodified linesmodified:examples/flaskr/setup.cfg+2 added-2 removed
1-[tool:pytest]2-test=pytest1+[aliases]2+test=pytestmodified:examples/flaskr/setup.py+13 added-2 removed
1-from setuptools import setup1+# -*- coding: utf-8 -*-2+"""3+ Flaskr Tests4+ ~~~~~~~~~~~~5 6+ Tests the Flaskr application.7+8+ :copyright: (c) 2015 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+from setuptools import setup, find_packages13+14 setup(15 name='flaskr',5- packages=['flaskr'],16+ packages=find_packages(),17 include_package_data=True,18 install_requires=[19 'flask',20 ],7 unmodified lines