Skip to content
Myr

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

13 files+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 ~~~~~~56 A microblog example application written as Flask tutorial with7 Flask and sqlite3.89 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213from sqlite3 import dbapi2 as sqlite314from flask import Blueprint, request, session, g, redirect, url_for, abort, \15 render_template, flash, current_app161718# create our blueprint :)19bp = Blueprint('flaskr', __name__)202122def connect_db():23 """Connects to the specific database."""24 rv = sqlite3.connect(current_app.config['DATABASE'])25 rv.row_factory = sqlite3.Row26 return rv272829def 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()353637def 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_db444546@bp.route('/')47def 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)525354@bp.route('/add', methods=['POST'])55def 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'))646566@bp.route('/login', methods=['GET', 'POST'])67def 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)798081@bp.route('/logout')82def 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
modified:examples/flaskr/flaskr/templates/login.html+1 added-1 removed
modified:examples/flaskr/flaskr/templates/show_entries.html+1 added-1 removed
modified:examples/flaskr/flaskr/__init__.py-1 removed
1from .flaskr import app
added:examples/flaskr/flaskr/_cliapp.py+15 added
1# -*- coding: utf-8 -*-2"""3 Flaskr4 ~~~~~~56 A microblog example application written as Flask tutorial with7 Flask and sqlite3.89 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213from flaskr.factory import create_app1415app = create_app()
added:examples/flaskr/flaskr/factory.py+64 added
1# -*- coding: utf-8 -*-2"""3 Flaskr4 ~~~~~~56 A microblog example application written as Flask tutorial with7 Flask and sqlite3.89 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213import os14from flask import Flask, g15from werkzeug.utils import find_modules, import_string16from flaskr.blueprints.flaskr import init_db171819def create_app(config=None):20 app = Flask(__name__)2122 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)3132 register_blueprints(app)33 register_cli(app)34 register_teardowns(app)3536 return app373839def register_blueprints(app):40 """Register all blueprint modules4142 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 None495051def 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.')575859def 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 ~~~~~~56 A microblog example application written as Flask tutorial with7 Flask and sqlite3.89 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213import os14from sqlite3 import dbapi2 as sqlite315from flask import Flask, request, session, g, redirect, url_for, abort, \16 render_template, flash171819# create our little application :)20app = Flask(__name__)2122# Load default config and override config from an environment variable23app.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))30app.config.from_envvar('FLASKR_SETTINGS', silent=True)313233def connect_db():34 """Connects to the specific database."""35 rv = sqlite3.connect(app.config['DATABASE'])36 rv.row_factory = sqlite3.Row37 return rv383940def 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()464748@app.cli.command('initdb')49def initdb_command():50 """Creates the database tables."""51 init_db()52 print('Initialized the database.')535455def 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_db626364@app.teardown_appcontext65def 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()697071@app.route('/')72def 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)777879@app.route('/add', methods=['POST'])80def 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'))899091@app.route('/login', methods=['GET', 'POST'])92def 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)104105106@app.route('/logout')107def 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 lines
1112import os13import tempfile14import pytest15from flaskr import flaskr15from flaskr.factory import create_app16from flaskr.blueprints.flaskr import init_db171819@pytest.fixture19def 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'])20def app(request):2122 db_fd, temp_db_location = tempfile.mkstemp()23 config = {24 'DATABASE': temp_db_location,25 'TESTING': True,26 'DB_FD': db_fd27 }2829 app = create_app(config=config)3031 with app.app_context():32 init_db()33 yield app343536@pytest.fixture37def client(request, app):3839 client = app.test_client()4041 def teardown():42 os.close(app.config['DB_FD'])43 os.unlink(app.config['DATABASE'])44 request.addfinalizer(teardown)4546 return client474849def login(client, username, password):50 return client.post('/login', data=dict(51 username=username,52 password=password
9 unmodified lines
62 rv = client.get('/')63 assert b'No entries here so far' in rv.data646547def test_login_logout(client):66def 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.data798062def test_messages(client):81def 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 lines
modified:examples/flaskr/README+5 added-3 removed
7 unmodified lines
8 A sqlite powered thumble blog application910 ~ How do I use it?1112 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.1718 2. install the app from the root of the project directory1920 pip install --editable .2122 3. Instruct flask to use the right application2322 export FLASK_APP=flaskr24 export FLASK_APP=flaskr._cliapp2526 4. initialize the database with this command:2728 flask initdb
12 unmodified lines
modified:examples/flaskr/setup.cfg+2 added-2 removed
1[tool:pytest]2test=pytest1[aliases]2test=pytest
modified:examples/flaskr/setup.py+13 added-2 removed
1from setuptools import setup1# -*- coding: utf-8 -*-2"""3 Flaskr Tests4 ~~~~~~~~~~~~56 Tests the Flaskr application.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112from setuptools import setup, find_packages1314setup(15 name='flaskr',5 packages=['flaskr'],16 packages=find_packages(),17 include_package_data=True,18 install_requires=[19 'flask',20 ],
7 unmodified lines