Skip to content

Commit

Permalink
Reformat with black
Browse files Browse the repository at this point in the history
  • Loading branch information
singingwolfboy committed May 6, 2019
1 parent 5b30983 commit 025589e
Show file tree
Hide file tree
Showing 63 changed files with 3,788 additions and 3,463 deletions.
12 changes: 6 additions & 6 deletions examples/javascript/js_example/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@
from js_example import app


@app.route('/', defaults={'js': 'plain'})
@app.route('/<any(plain, jquery, fetch):js>')
@app.route("/", defaults={"js": "plain"})
@app.route("/<any(plain, jquery, fetch):js>")
def index(js):
return render_template('{0}.html'.format(js), js=js)
return render_template("{0}.html".format(js), js=js)


@app.route('/add', methods=['POST'])
@app.route("/add", methods=["POST"])
def add():
a = request.form.get('a', 0, type=float)
b = request.form.get('b', 0, type=float)
a = request.form.get("a", 0, type=float)
b = request.form.get("b", 0, type=float)
return jsonify(result=a + b)
28 changes: 10 additions & 18 deletions examples/javascript/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,21 @@

from setuptools import find_packages, setup

with io.open('README.rst', 'rt', encoding='utf8') as f:
with io.open("README.rst", "rt", encoding="utf8") as f:
readme = f.read()

setup(
name='js_example',
version='1.0.0',
url='http://flask.pocoo.org/docs/patterns/jquery/',
license='BSD',
maintainer='Pallets team',
maintainer_email='[email protected]',
description='Demonstrates making Ajax requests to Flask.',
name="js_example",
version="1.0.0",
url="http://flask.pocoo.org/docs/patterns/jquery/",
license="BSD",
maintainer="Pallets team",
maintainer_email="[email protected]",
description="Demonstrates making Ajax requests to Flask.",
long_description=readme,
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'flask',
],
extras_require={
'test': [
'pytest',
'coverage',
'blinker',
],
},
install_requires=["flask"],
extras_require={"test": ["pytest", "coverage", "blinker"]},
)
2 changes: 1 addition & 1 deletion examples/javascript/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from js_example import app


@pytest.fixture(name='app')
@pytest.fixture(name="app")
def fixture_app():
app.testing = True
yield app
Expand Down
28 changes: 14 additions & 14 deletions examples/javascript/tests/test_js_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@
from flask import template_rendered


@pytest.mark.parametrize(('path', 'template_name'), (
('/', 'plain.html'),
('/plain', 'plain.html'),
('/fetch', 'fetch.html'),
('/jquery', 'jquery.html'),
))
@pytest.mark.parametrize(
("path", "template_name"),
(
("/", "plain.html"),
("/plain", "plain.html"),
("/fetch", "fetch.html"),
("/jquery", "jquery.html"),
),
)
def test_index(app, client, path, template_name):
def check(sender, template, context):
assert template.name == template_name
Expand All @@ -17,12 +20,9 @@ def check(sender, template, context):
client.get(path)


@pytest.mark.parametrize(('a', 'b', 'result'), (
(2, 3, 5),
(2.5, 3, 5.5),
(2, None, 2),
(2, 'b', 2),
))
@pytest.mark.parametrize(
("a", "b", "result"), ((2, 3, 5), (2.5, 3, 5.5), (2, None, 2), (2, "b", 2))
)
def test_add(client, a, b, result):
response = client.post('/add', data={'a': a, 'b': b})
assert response.get_json()['result'] == result
response = client.post("/add", data={"a": a, "b": b})
assert response.get_json()["result"] == result
14 changes: 8 additions & 6 deletions examples/tutorial/flaskr/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@ def create_app(test_config=None):
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
# a default secret that should be overridden by instance config
SECRET_KEY='dev',
SECRET_KEY="dev",
# store the database in the instance folder
DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
DATABASE=os.path.join(app.instance_path, "flaskr.sqlite"),
)

if test_config is None:
# load the instance config, if it exists, when not testing
app.config.from_pyfile('config.py', silent=True)
app.config.from_pyfile("config.py", silent=True)
else:
# load the test config if passed in
app.config.update(test_config)
Expand All @@ -26,23 +26,25 @@ def create_app(test_config=None):
except OSError:
pass

@app.route('/hello')
@app.route("/hello")
def hello():
return 'Hello, World!'
return "Hello, World!"

# register the database commands
from flaskr import db

db.init_app(app)

# apply the blueprints to the app
from flaskr import auth, blog

app.register_blueprint(auth.bp)
app.register_blueprint(blog.bp)

# make url_for('index') == url_for('blog.index')
# in another app, you might define a separate main index here with
# app.route, while giving the blog blueprint a url_prefix, but for
# the tutorial the blog will be the main index
app.add_url_rule('/', endpoint='index')
app.add_url_rule("/", endpoint="index")

return app
77 changes: 43 additions & 34 deletions examples/tutorial/flaskr/auth.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,29 @@
import functools

from flask import (
Blueprint, flash, g, redirect, render_template, request, session, url_for
Blueprint,
flash,
g,
redirect,
render_template,
request,
session,
url_for,
)
from werkzeug.security import check_password_hash, generate_password_hash

from flaskr.db import get_db

bp = Blueprint('auth', __name__, url_prefix='/auth')
bp = Blueprint("auth", __name__, url_prefix="/auth")


def login_required(view):
"""View decorator that redirects anonymous users to the login page."""

@functools.wraps(view)
def wrapped_view(**kwargs):
if g.user is None:
return redirect(url_for('auth.login'))
return redirect(url_for("auth.login"))

return view(**kwargs)

Expand All @@ -26,83 +34,84 @@ def wrapped_view(**kwargs):
def load_logged_in_user():
"""If a user id is stored in the session, load the user object from
the database into ``g.user``."""
user_id = session.get('user_id')
user_id = session.get("user_id")

if user_id is None:
g.user = None
else:
g.user = get_db().execute(
'SELECT * FROM user WHERE id = ?', (user_id,)
).fetchone()
g.user = (
get_db().execute("SELECT * FROM user WHERE id = ?", (user_id,)).fetchone()
)


@bp.route('/register', methods=('GET', 'POST'))
@bp.route("/register", methods=("GET", "POST"))
def register():
"""Register a new user.
Validates that the username is not already taken. Hashes the
password for security.
"""
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
db = get_db()
error = None

if not username:
error = 'Username is required.'
error = "Username is required."
elif not password:
error = 'Password is required.'
elif db.execute(
'SELECT id FROM user WHERE username = ?', (username,)
).fetchone() is not None:
error = 'User {0} is already registered.'.format(username)
error = "Password is required."
elif (
db.execute("SELECT id FROM user WHERE username = ?", (username,)).fetchone()
is not None
):
error = "User {0} is already registered.".format(username)

if error is None:
# the name is available, store it in the database and go to
# the login page
db.execute(
'INSERT INTO user (username, password) VALUES (?, ?)',
(username, generate_password_hash(password))
"INSERT INTO user (username, password) VALUES (?, ?)",
(username, generate_password_hash(password)),
)
db.commit()
return redirect(url_for('auth.login'))
return redirect(url_for("auth.login"))

flash(error)

return render_template('auth/register.html')
return render_template("auth/register.html")


@bp.route('/login', methods=('GET', 'POST'))
@bp.route("/login", methods=("GET", "POST"))
def login():
"""Log in a registered user by adding the user id to the session."""
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
db = get_db()
error = None
user = db.execute(
'SELECT * FROM user WHERE username = ?', (username,)
"SELECT * FROM user WHERE username = ?", (username,)
).fetchone()

if user is None:
error = 'Incorrect username.'
elif not check_password_hash(user['password'], password):
error = 'Incorrect password.'
error = "Incorrect username."
elif not check_password_hash(user["password"], password):
error = "Incorrect password."

if error is None:
# store the user id in a new session and return to the index
session.clear()
session['user_id'] = user['id']
return redirect(url_for('index'))
session["user_id"] = user["id"]
return redirect(url_for("index"))

flash(error)

return render_template('auth/login.html')
return render_template("auth/login.html")


@bp.route('/logout')
@bp.route("/logout")
def logout():
"""Clear the current session, including the stored user id."""
session.clear()
return redirect(url_for('index'))
return redirect(url_for("index"))
Loading

0 comments on commit 025589e

Please sign in to comment.