Adds in blueprints and an application factory
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kyle Lawlor · committed by Kyle Lawlor · parent de555c8 · Browse files · 11 files·+165 added−132 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+165 added−132 removed
- tests:+19 added−15 removed
- other:+146 added−117 removed
Provenance
- Commit
8cf32bc- Tree
1237851- Author
Kyle Lawlor <klawlor419@gmail.com>- Committer
Kyle Lawlor <klawlor419@gmail.com>- Parent
de555c8
11 files changed+165 added−132 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+3 added
1+from flaskr.factory import create_app2+3+app = create_app()added:examples/flaskr/flaskr/factory.py+52 added
1+import os2+from flask import Flask, g3+from werkzeug.utils import find_modules, import_string4+from flaskr.blueprints.flaskr import init_db5+6+7+def create_app(config=None):8+ app = Flask(__name__)9+10+ app.config.update(dict(11+ DATABASE=os.path.join(app.root_path, 'flaskr.db'),12+ DEBUG=True,13+ SECRET_KEY='development key',14+ USERNAME='admin',15+ PASSWORD='default'16+ ))17+ app.config.update(config or {})18+ app.config.from_envvar('FLASKR_SETTINGS', silent=True)19+20+ register_blueprints(app)21+ register_cli(app)22+ register_teardowns(app)23+24+ return app25+26+27+def register_blueprints(app):28+ """Register all blueprint modules29+30+ Reference: Armin Ronacher, "Flask for Fun and for Profit" PyBay 2016.31+ """32+ for name in find_modules('flaskr.blueprints'):33+ mod = import_string(name)34+ if hasattr(mod, 'bp'):35+ app.register_blueprint(mod.bp)36+ return None37+38+39+def register_cli(app):40+ @app.cli.command('initdb')41+ def initdb_command():42+ """Creates the database tables."""43+ init_db()44+ print('Initialized the database.')45+46+47+def register_teardowns(app):48+ @app.teardown_appcontext49+ def close_db(error):50+ """Closes the database again at the end of the request."""51+ if hasattr(g, 'sqlite_db'):52+ 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+19 added-15 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+test_app = create_app()20+21+22 @pytest.fixture23 def client(request):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()24+ db_fd, test_app.config['DATABASE'] = tempfile.mkstemp()25+ test_app.config['TESTING'] = True26+ client = test_app.test_client()27+ with test_app.app_context():28+ init_db()29 30 def teardown():31 os.close(db_fd)28- os.unlink(flaskr.app.config['DATABASE'])32+ os.unlink(test_app.config['DATABASE'])33 request.addfinalizer(teardown)34 35 return client36 16 unmodified lines53 54 55 def test_login_logout(client):56 """Make sure login and logout works"""53- rv = login(client, flaskr.app.config['USERNAME'],54- flaskr.app.config['PASSWORD'])57+ rv = login(client, test_app.config['USERNAME'],58+ test_app.config['PASSWORD'])59 assert b'You were logged in' in rv.data60 rv = logout(client)61 assert b'You were logged out' in rv.data58- rv = login(client, flaskr.app.config['USERNAME'] + 'x',59- flaskr.app.config['PASSWORD'])62+ rv = login(client,test_app.config['USERNAME'] + 'x',63+ test_app.config['PASSWORD'])64 assert b'Invalid username' in rv.data61- rv = login(client, flaskr.app.config['USERNAME'],62- flaskr.app.config['PASSWORD'] + 'x')65+ rv = login(client, test_app.config['USERNAME'],66+ test_app.config['PASSWORD'] + 'x')67 assert b'Invalid password' in rv.data68 69 70 def test_messages(client):71 """Test that messages work"""68- login(client, flaskr.app.config['USERNAME'],69- flaskr.app.config['PASSWORD'])72+ login(client, test_app.config['USERNAME'],73+ test_app.config['PASSWORD'])74 rv = client.post('/add', data=dict(75 title='<Hello>',76 text='<strong>HTML</strong> allowed here'77 ), follow_redirects=True)3 unmodified linesmodified:examples/flaskr/setup.py+2 added-2 removed
1-from setuptools import setup1+from setuptools import setup, find_packages2 3 setup(4 name='flaskr',5- packages=['flaskr'],5+ packages=find_packages(),6 include_package_data=True,7 install_requires=[8 'flask',9 ],7 unmodified lines