Skip to content
Myr

Merge pull request #3183 from singingwolfboy/pre-commit

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Baumgold · committed by GitHub · parents 819368a, 025589e · Browse files · 65 files+3791 added−3456 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Pre-commit: Black

Diff stats

65 files+3791 added−3456 removed

  • tests:+2485 added−2403 removed
  • other:+1306 added−1053 removed

65 files+3791 added−3456 removed

modified:examples/javascript/js_example/views.py+6 added-6 removed
1 unmodified line
23from js_example import app456@app.route('/', defaults={'js': 'plain'})7@app.route('/<any(plain, jquery, fetch):js>')6@app.route("/", defaults={"js": "plain"})7@app.route("/<any(plain, jquery, fetch):js>")8def index(js):9 return render_template('{0}.html'.format(js), js=js)9 return render_template("{0}.html".format(js), js=js)101112@app.route('/add', methods=['POST'])12@app.route("/add", methods=["POST"])13def add():14 a = request.form.get('a', 0, type=float)15 b = request.form.get('b', 0, type=float)14 a = request.form.get("a", 0, type=float)15 b = request.form.get("b", 0, type=float)16 return jsonify(result=a + b)
modified:examples/javascript/tests/conftest.py+1 added-1 removed
1 unmodified line
23from js_example import app456@pytest.fixture(name='app')6@pytest.fixture(name="app")7def fixture_app():8 app.testing = True9 yield app10 app.testing = False
5 unmodified lines
modified:examples/javascript/tests/test_js_example.py+14 added-14 removed
1 unmodified line
23from flask import template_rendered456@pytest.mark.parametrize(('path', 'template_name'), (7 ('/', 'plain.html'),8 ('/plain', 'plain.html'),9 ('/fetch', 'fetch.html'),10 ('/jquery', 'jquery.html'),11))6@pytest.mark.parametrize(7 ("path", "template_name"),8 (9 ("/", "plain.html"),10 ("/plain", "plain.html"),11 ("/fetch", "fetch.html"),12 ("/jquery", "jquery.html"),13 ),14)15def test_index(app, client, path, template_name):16 def check(sender, template, context):17 assert template.name == template_name1819 with template_rendered.connected_to(check, app):20 client.get(path)212220@pytest.mark.parametrize(('a', 'b', 'result'), (21 (2, 3, 5),22 (2.5, 3, 5.5),23 (2, None, 2),24 (2, 'b', 2),25))23@pytest.mark.parametrize(24 ("a", "b", "result"), ((2, 3, 5), (2.5, 3, 5.5), (2, None, 2), (2, "b", 2))25)26def test_add(client, a, b, result):27 response = client.post('/add', data={'a': a, 'b': b})28 assert response.get_json()['result'] == result27 response = client.post("/add", data={"a": a, "b": b})28 assert response.get_json()["result"] == result
modified:examples/javascript/setup.py+10 added-18 removed
1import io23from setuptools import find_packages, setup45with io.open('README.rst', 'rt', encoding='utf8') as f:5with io.open("README.rst", "rt", encoding="utf8") as f:6 readme = f.read()78setup(9 name='js_example',10 version='1.0.0',11 url='http://flask.pocoo.org/docs/patterns/jquery/',12 license='BSD',13 maintainer='Pallets team',14 maintainer_email='contact@palletsprojects.com',15 description='Demonstrates making Ajax requests to Flask.',9 name="js_example",10 version="1.0.0",11 url="http://flask.pocoo.org/docs/patterns/jquery/",12 license="BSD",13 maintainer="Pallets team",14 maintainer_email="contact@palletsprojects.com",15 description="Demonstrates making Ajax requests to Flask.",16 long_description=readme,17 packages=find_packages(),18 include_package_data=True,19 zip_safe=False,20 install_requires=[21 'flask',22 ],23 extras_require={24 'test': [25 'pytest',26 'coverage',27 'blinker',28 ],29 },20 install_requires=["flask"],21 extras_require={"test": ["pytest", "coverage", "blinker"]},22)
modified:examples/tutorial/flaskr/__init__.py+8 added-6 removed
6 unmodified lines
7 """Create and configure an instance of the Flask application."""8 app = Flask(__name__, instance_relative_config=True)9 app.config.from_mapping(10 # a default secret that should be overridden by instance config11 SECRET_KEY='dev',11 SECRET_KEY="dev",12 # store the database in the instance folder13 DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),13 DATABASE=os.path.join(app.instance_path, "flaskr.sqlite"),14 )1516 if test_config is None:17 # load the instance config, if it exists, when not testing18 app.config.from_pyfile('config.py', silent=True)18 app.config.from_pyfile("config.py", silent=True)19 else:20 # load the test config if passed in21 app.config.update(test_config)22
2 unmodified lines
25 os.makedirs(app.instance_path)26 except OSError:27 pass2829 @app.route('/hello')29 @app.route("/hello")30 def hello():31 return 'Hello, World!'31 return "Hello, World!"3233 # register the database commands34 from flaskr import db3536 db.init_app(app)3738 # apply the blueprints to the app39 from flaskr import auth, blog4041 app.register_blueprint(auth.bp)42 app.register_blueprint(blog.bp)4344 # make url_for('index') == url_for('blog.index')45 # in another app, you might define a separate main index here with46 # app.route, while giving the blog blueprint a url_prefix, but for47 # the tutorial the blog will be the main index46 app.add_url_rule('/', endpoint='index')48 app.add_url_rule("/", endpoint="index")4950 return app
modified:examples/tutorial/flaskr/auth.py+43 added-34 removed
1import functools23from flask import (4 Blueprint, flash, g, redirect, render_template, request, session, url_for4 Blueprint,5 flash,6 g,7 redirect,8 render_template,9 request,10 session,11 url_for,12)13from werkzeug.security import check_password_hash, generate_password_hash1415from flaskr.db import get_db1610bp = Blueprint('auth', __name__, url_prefix='/auth')17bp = Blueprint("auth", __name__, url_prefix="/auth")181920def login_required(view):21 """View decorator that redirects anonymous users to the login page."""2223 @functools.wraps(view)24 def wrapped_view(**kwargs):25 if g.user is None:18 return redirect(url_for('auth.login'))26 return redirect(url_for("auth.login"))2728 return view(**kwargs)2930 return wrapped_view
2 unmodified lines
33@bp.before_app_request34def load_logged_in_user():35 """If a user id is stored in the session, load the user object from36 the database into ``g.user``."""29 user_id = session.get('user_id')37 user_id = session.get("user_id")3839 if user_id is None:40 g.user = None41 else:34 g.user = get_db().execute(35 'SELECT * FROM user WHERE id = ?', (user_id,)36 ).fetchone()42 g.user = (43 get_db().execute("SELECT * FROM user WHERE id = ?", (user_id,)).fetchone()44 )454639@bp.route('/register', methods=('GET', 'POST'))47@bp.route("/register", methods=("GET", "POST"))48def register():49 """Register a new user.5051 Validates that the username is not already taken. Hashes the52 password for security.53 """46 if request.method == 'POST':47 username = request.form['username']48 password = request.form['password']54 if request.method == "POST":55 username = request.form["username"]56 password = request.form["password"]57 db = get_db()58 error = None5960 if not username:53 error = 'Username is required.'61 error = "Username is required."62 elif not password:55 error = 'Password is required.'56 elif db.execute(57 'SELECT id FROM user WHERE username = ?', (username,)58 ).fetchone() is not None:59 error = 'User {0} is already registered.'.format(username)63 error = "Password is required."64 elif (65 db.execute("SELECT id FROM user WHERE username = ?", (username,)).fetchone()66 is not None67 ):68 error = "User {0} is already registered.".format(username)6970 if error is None:71 # the name is available, store it in the database and go to72 # the login page73 db.execute(65 'INSERT INTO user (username, password) VALUES (?, ?)',66 (username, generate_password_hash(password))74 "INSERT INTO user (username, password) VALUES (?, ?)",75 (username, generate_password_hash(password)),76 )77 db.commit()69 return redirect(url_for('auth.login'))78 return redirect(url_for("auth.login"))7980 flash(error)8173 return render_template('auth/register.html')82 return render_template("auth/register.html")838476@bp.route('/login', methods=('GET', 'POST'))85@bp.route("/login", methods=("GET", "POST"))86def login():87 """Log in a registered user by adding the user id to the session."""79 if request.method == 'POST':80 username = request.form['username']81 password = request.form['password']88 if request.method == "POST":89 username = request.form["username"]90 password = request.form["password"]91 db = get_db()92 error = None93 user = db.execute(85 'SELECT * FROM user WHERE username = ?', (username,)94 "SELECT * FROM user WHERE username = ?", (username,)95 ).fetchone()9697 if user is None:89 error = 'Incorrect username.'90 elif not check_password_hash(user['password'], password):91 error = 'Incorrect password.'98 error = "Incorrect username."99 elif not check_password_hash(user["password"], password):100 error = "Incorrect password."101102 if error is None:103 # store the user id in a new session and return to the index104 session.clear()96 session['user_id'] = user['id']97 return redirect(url_for('index'))105 session["user_id"] = user["id"]106 return redirect(url_for("index"))107108 flash(error)109101 return render_template('auth/login.html')110 return render_template("auth/login.html")111112104@bp.route('/logout')113@bp.route("/logout")114def logout():115 """Clear the current session, including the stored user id."""116 session.clear()108 return redirect(url_for('index'))117 return redirect(url_for("index"))
modified:examples/tutorial/flaskr/blog.py+38 added-38 removed
1from flask import (2 Blueprint, flash, g, redirect, render_template, request, url_for1from flask import Blueprint, flash, g, redirect, render_template, request, url_for3)2from werkzeug.exceptions import abort34from flaskr.auth import login_required5from flaskr.db import get_db69bp = Blueprint('blog', __name__)7bp = Blueprint("blog", __name__)8912@bp.route('/')10@bp.route("/")11def index():12 """Show all the posts, most recent first."""13 db = get_db()14 posts = db.execute(17 'SELECT p.id, title, body, created, author_id, username'18 ' FROM post p JOIN user u ON p.author_id = u.id'19 ' ORDER BY created DESC'15 "SELECT p.id, title, body, created, author_id, username"16 " FROM post p JOIN user u ON p.author_id = u.id"17 " ORDER BY created DESC"18 ).fetchall()21 return render_template('blog/index.html', posts=posts)19 return render_template("blog/index.html", posts=posts)202122def get_post(id, check_author=True):23 """Get a post and its author by id.
6 unmodified lines
30 :return: the post with author information31 :raise 404: if a post with the given id doesn't exist32 :raise 403: if the current user isn't the author33 """36 post = get_db().execute(37 'SELECT p.id, title, body, created, author_id, username'38 ' FROM post p JOIN user u ON p.author_id = u.id'39 ' WHERE p.id = ?',40 (id,)41 ).fetchone()34 post = (35 get_db()36 .execute(37 "SELECT p.id, title, body, created, author_id, username"38 " FROM post p JOIN user u ON p.author_id = u.id"39 " WHERE p.id = ?",40 (id,),41 )42 .fetchone()43 )4445 if post is None:46 abort(404, "Post id {0} doesn't exist.".format(id))4746 if check_author and post['author_id'] != g.user['id']:48 if check_author and post["author_id"] != g.user["id"]:49 abort(403)5051 return post525352@bp.route('/create', methods=('GET', 'POST'))54@bp.route("/create", methods=("GET", "POST"))55@login_required56def create():57 """Create a new post for the current user."""56 if request.method == 'POST':57 title = request.form['title']58 body = request.form['body']58 if request.method == "POST":59 title = request.form["title"]60 body = request.form["body"]61 error = None6263 if not title:62 error = 'Title is required.'64 error = "Title is required."6566 if error is not None:67 flash(error)68 else:69 db = get_db()70 db.execute(69 'INSERT INTO post (title, body, author_id)'70 ' VALUES (?, ?, ?)',71 (title, body, g.user['id'])71 "INSERT INTO post (title, body, author_id)" " VALUES (?, ?, ?)",72 (title, body, g.user["id"]),73 )74 db.commit()74 return redirect(url_for('blog.index'))75 return redirect(url_for("blog.index"))7676 return render_template('blog/create.html')77 return render_template("blog/create.html")787979@bp.route('/<int:id>/update', methods=('GET', 'POST'))80@bp.route("/<int:id>/update", methods=("GET", "POST"))81@login_required82def update(id):83 """Update a post if the current user is the author."""84 post = get_post(id)8585 if request.method == 'POST':86 title = request.form['title']87 body = request.form['body']86 if request.method == "POST":87 title = request.form["title"]88 body = request.form["body"]89 error = None9091 if not title:91 error = 'Title is required.'92 error = "Title is required."9394 if error is not None:95 flash(error)96 else:97 db = get_db()98 db.execute(98 'UPDATE post SET title = ?, body = ? WHERE id = ?',99 (title, body, id)99 "UPDATE post SET title = ?, body = ? WHERE id = ?", (title, body, id)100 )101 db.commit()102 return redirect(url_for('blog.index'))102 return redirect(url_for("blog.index"))103104 return render_template('blog/update.html', post=post)104 return render_template("blog/update.html", post=post)105106107@bp.route('/<int:id>/delete', methods=('POST',))107@bp.route("/<int:id>/delete", methods=("POST",))108@login_required109def delete(id):110 """Delete a post.111
1 unmodified line
113 author of the post.114 """115 get_post(id)116 db = get_db()117 db.execute('DELETE FROM post WHERE id = ?', (id,))117 db.execute("DELETE FROM post WHERE id = ?", (id,))118 db.commit()119 return redirect(url_for('blog.index'))119 return redirect(url_for("blog.index"))
modified:examples/tutorial/flaskr/db.py+7 added-8 removed
8 unmodified lines
9 """Connect to the application's configured database. The connection10 is unique for each request and will be reused if this is called11 again.12 """13 if 'db' not in g:13 if "db" not in g:14 g.db = sqlite3.connect(15 current_app.config['DATABASE'],16 detect_types=sqlite3.PARSE_DECLTYPES15 current_app.config["DATABASE"], detect_types=sqlite3.PARSE_DECLTYPES16 )17 g.db.row_factory = sqlite3.Row1819 return g.db
2 unmodified lines
22def close_db(e=None):23 """If this request connected to the database, close the24 connection.25 """27 db = g.pop('db', None)26 db = g.pop("db", None)2728 if db is not None:29 db.close()30
1 unmodified line
32def init_db():33 """Clear existing data and create new tables."""34 db = get_db()3537 with current_app.open_resource('schema.sql') as f:38 db.executescript(f.read().decode('utf8'))36 with current_app.open_resource("schema.sql") as f:37 db.executescript(f.read().decode("utf8"))383941@click.command('init-db')40@click.command("init-db")41@with_appcontext42def init_db_command():43 """Clear existing data and create new tables."""44 init_db()46 click.echo('Initialized the database.')45 click.echo("Initialized the database.")464748def init_app(app):49 """Register database functions with the Flask app. This is called by
4 unmodified lines
modified:examples/tutorial/tests/conftest.py+6 added-10 removed
4 unmodified lines
5from flaskr import create_app6from flaskr.db import get_db, init_db78# read in SQL for populating test data9with open(os.path.join(os.path.dirname(__file__), 'data.sql'), 'rb') as f:10 _data_sql = f.read().decode('utf8')9with open(os.path.join(os.path.dirname(__file__), "data.sql"), "rb") as f:10 _data_sql = f.read().decode("utf8")111213@pytest.fixture14def app():15 """Create and configure a new app instance for each test."""16 # create a temporary file to isolate the database for each test17 db_fd, db_path = tempfile.mkstemp()18 # create the app with common test config19 app = create_app({20 'TESTING': True,21 'DATABASE': db_path,22 })19 app = create_app({"TESTING": True, "DATABASE": db_path})2021 # create the database and load test data22 with app.app_context():23 init_db()
21 unmodified lines
45class AuthActions(object):46 def __init__(self, client):47 self._client = client4852 def login(self, username='test', password='test'):49 def login(self, username="test", password="test"):50 return self._client.post(54 '/auth/login',55 data={'username': username, 'password': password}51 "/auth/login", data={"username": username, "password": password}52 )5354 def logout(self):59 return self._client.get('/auth/logout')55 return self._client.get("/auth/logout")565758@pytest.fixture59def auth(client):
1 unmodified line
modified:examples/tutorial/tests/test_auth.py+26 added-25 removed
3 unmodified lines
456def test_register(client, app):7 # test that viewing the page renders without template errors8 assert client.get('/auth/register').status_code == 2008 assert client.get("/auth/register").status_code == 200910 # test that successful registration redirects to the login page11 response = client.post(12 '/auth/register', data={'username': 'a', 'password': 'a'}13 )14 assert 'http://localhost/auth/login' == response.headers['Location']11 response = client.post("/auth/register", data={"username": "a", "password": "a"})12 assert "http://localhost/auth/login" == response.headers["Location"]1314 # test that the user was inserted into the database15 with app.app_context():18 assert get_db().execute(19 "select * from user where username = 'a'",20 ).fetchone() is not None16 assert (17 get_db().execute("select * from user where username = 'a'").fetchone()18 is not None19 )202123@pytest.mark.parametrize(('username', 'password', 'message'), (24 ('', '', b'Username is required.'),25 ('a', '', b'Password is required.'),26 ('test', 'test', b'already registered'),27))22@pytest.mark.parametrize(23 ("username", "password", "message"),24 (25 ("", "", b"Username is required."),26 ("a", "", b"Password is required."),27 ("test", "test", b"already registered"),28 ),29)30def test_register_validate_input(client, username, password, message):31 response = client.post(30 '/auth/register',31 data={'username': username, 'password': password}32 "/auth/register", data={"username": username, "password": password}33 )34 assert message in response.data353637def test_login(client, auth):38 # test that viewing the page renders without template errors38 assert client.get('/auth/login').status_code == 20039 assert client.get("/auth/login").status_code == 2004041 # test that successful login redirects to the index page42 response = auth.login()42 assert response.headers['Location'] == 'http://localhost/'43 assert response.headers["Location"] == "http://localhost/"4445 # login request set the user_id in the session46 # check that the user is loaded from the session47 with client:47 client.get('/')48 assert session['user_id'] == 149 assert g.user['username'] == 'test'48 client.get("/")49 assert session["user_id"] == 150 assert g.user["username"] == "test"515252@pytest.mark.parametrize(('username', 'password', 'message'), (53 ('a', 'test', b'Incorrect username.'),54 ('test', 'a', b'Incorrect password.'),55))53@pytest.mark.parametrize(54 ("username", "password", "message"),55 (("a", "test", b"Incorrect username."), ("test", "a", b"Incorrect password.")),56)57def test_login_validate_input(auth, username, password, message):58 response = auth.login(username, password)59 assert message in response.data60
2 unmodified lines
63 auth.login()6465 with client:66 auth.logout()66 assert 'user_id' not in session67 assert "user_id" not in session
modified:examples/tutorial/tests/test_blog.py+25 added-35 removed
1 unmodified line
2from flaskr.db import get_db345def test_index(client, auth):6 response = client.get('/')6 response = client.get("/")7 assert b"Log In" in response.data8 assert b"Register" in response.data910 auth.login()11 response = client.get('/')12 assert b'test title' in response.data13 assert b'by test on 2018-01-01' in response.data14 assert b'test\nbody' in response.data11 response = client.get("/")12 assert b"test title" in response.data13 assert b"by test on 2018-01-01" in response.data14 assert b"test\nbody" in response.data15 assert b'href="/1/update"' in response.data161718@pytest.mark.parametrize('path', (19 '/create',20 '/1/update',21 '/1/delete',22))18@pytest.mark.parametrize("path", ("/create", "/1/update", "/1/delete"))19def test_login_required(client, path):20 response = client.post(path)25 assert response.headers['Location'] == 'http://localhost/auth/login'21 assert response.headers["Location"] == "http://localhost/auth/login"222324def test_author_required(app, client, auth):25 # change the post author to another user26 with app.app_context():27 db = get_db()32 db.execute('UPDATE post SET author_id = 2 WHERE id = 1')28 db.execute("UPDATE post SET author_id = 2 WHERE id = 1")29 db.commit()3031 auth.login()32 # current user can't modify other user's post37 assert client.post('/1/update').status_code == 40338 assert client.post('/1/delete').status_code == 40333 assert client.post("/1/update").status_code == 40334 assert client.post("/1/delete").status_code == 40335 # current user doesn't see edit link40 assert b'href="/1/update"' not in client.get('/').data36 assert b'href="/1/update"' not in client.get("/").data373843@pytest.mark.parametrize('path', (44 '/2/update',45 '/2/delete',46))39@pytest.mark.parametrize("path", ("/2/update", "/2/delete"))40def test_exists_required(client, auth, path):41 auth.login()42 assert client.post(path).status_code == 404434445def test_create(client, auth, app):46 auth.login()54 assert client.get('/create').status_code == 20055 client.post('/create', data={'title': 'created', 'body': ''})47 assert client.get("/create").status_code == 20048 client.post("/create", data={"title": "created", "body": ""})4950 with app.app_context():51 db = get_db()59 count = db.execute('SELECT COUNT(id) FROM post').fetchone()[0]52 count = db.execute("SELECT COUNT(id) FROM post").fetchone()[0]53 assert count == 2545556def test_update(client, auth, app):57 auth.login()65 assert client.get('/1/update').status_code == 20066 client.post('/1/update', data={'title': 'updated', 'body': ''})58 assert client.get("/1/update").status_code == 20059 client.post("/1/update", data={"title": "updated", "body": ""})6061 with app.app_context():62 db = get_db()70 post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()71 assert post['title'] == 'updated'63 post = db.execute("SELECT * FROM post WHERE id = 1").fetchone()64 assert post["title"] == "updated"656674@pytest.mark.parametrize('path', (75 '/create',76 '/1/update',77))67@pytest.mark.parametrize("path", ("/create", "/1/update"))68def test_create_update_validate(client, auth, path):69 auth.login()80 response = client.post(path, data={'title': '', 'body': ''})81 assert b'Title is required.' in response.data70 response = client.post(path, data={"title": "", "body": ""})71 assert b"Title is required." in response.data727374def test_delete(client, auth, app):75 auth.login()86 response = client.post('/1/delete')87 assert response.headers['Location'] == 'http://localhost/'76 response = client.post("/1/delete")77 assert response.headers["Location"] == "http://localhost/"7879 with app.app_context():80 db = get_db()91 post = db.execute('SELECT * FROM post WHERE id = 1').fetchone()81 post = db.execute("SELECT * FROM post WHERE id = 1").fetchone()82 assert post is None
modified:examples/tutorial/tests/test_db.py+5 added-5 removed
8 unmodified lines
9 db = get_db()10 assert db is get_db()1112 with pytest.raises(sqlite3.ProgrammingError) as e:13 db.execute('SELECT 1')13 db.execute("SELECT 1")1415 assert 'closed' in str(e)15 assert "closed" in str(e)161718def test_init_db_command(runner, monkeypatch):19 class Recorder(object):
1 unmodified line
2122 def fake_init_db():23 Recorder.called = True2425 monkeypatch.setattr('flaskr.db.init_db', fake_init_db)26 result = runner.invoke(args=['init-db'])27 assert 'Initialized' in result.output25 monkeypatch.setattr("flaskr.db.init_db", fake_init_db)26 result = runner.invoke(args=["init-db"])27 assert "Initialized" in result.output28 assert Recorder.called
modified:examples/tutorial/tests/test_factory.py+3 added-3 removed
2 unmodified lines
34def test_config():5 """Test create_app without passing test config."""6 assert not create_app().testing7 assert create_app({'TESTING': True}).testing7 assert create_app({"TESTING": True}).testing8910def test_hello(client):11 response = client.get('/hello')12 assert response.data == b'Hello, World!'11 response = client.get("/hello")12 assert response.data == b"Hello, World!"
modified:examples/tutorial/setup.py+10 added-17 removed
1import io23from setuptools import find_packages, setup45with io.open('README.rst', 'rt', encoding='utf8') as f:5with io.open("README.rst", "rt", encoding="utf8") as f:6 readme = f.read()78setup(9 name='flaskr',10 version='1.0.0',11 url='http://flask.pocoo.org/docs/tutorial/',12 license='BSD',13 maintainer='Pallets team',14 maintainer_email='contact@palletsprojects.com',15 description='The basic blog app built in the Flask tutorial.',9 name="flaskr",10 version="1.0.0",11 url="http://flask.pocoo.org/docs/tutorial/",12 license="BSD",13 maintainer="Pallets team",14 maintainer_email="contact@palletsprojects.com",15 description="The basic blog app built in the Flask tutorial.",16 long_description=readme,17 packages=find_packages(),18 include_package_data=True,19 zip_safe=False,20 install_requires=[21 'flask',22 ],23 extras_require={24 'test': [25 'pytest',26 'coverage',27 ],28 },20 install_requires=["flask"],21 extras_require={"test": ["pytest", "coverage"]},22)
modified:flask/json/__init__.py+57 added-49 removed
21 unmodified lines
222324# Figure out if simplejson escapes slashes. This behavior was changed25# from one version to another without reason.26_slash_escape = '\\/' not in _json.dumps('/')26_slash_escape = "\\/" not in _json.dumps("/")272829__all__ = ['dump', 'dumps', 'load', 'loads', 'htmlsafe_dump',30 'htmlsafe_dumps', 'JSONDecoder', 'JSONEncoder',31 'jsonify']29__all__ = [30 "dump",31 "dumps",32 "load",33 "loads",34 "htmlsafe_dump",35 "htmlsafe_dumps",36 "JSONDecoder",37 "JSONEncoder",38 "jsonify",39]404142def _wrap_reader_for_text(fp, encoding):43 if isinstance(fp.read(0), bytes):
2 unmodified lines
464748def _wrap_writer_for_text(fp, encoding):49 try:42 fp.write('')50 fp.write("")51 except TypeError:52 fp = io.TextIOWrapper(fp, encoding)53 return fp54
28 unmodified lines
83 if isinstance(o, date):84 return http_date(o.timetuple())85 if isinstance(o, uuid.UUID):86 return str(o)79 if hasattr(o, '__html__'):87 if hasattr(o, "__html__"):88 return text_type(o.__html__())89 return _json.JSONEncoder.default(self, o)9091
9 unmodified lines
101 """Inject default arguments for dump functions."""102 if current_app:103 bp = current_app.blueprints.get(request.blueprint) if request else None104 kwargs.setdefault(97 'cls',98 bp.json_encoder if bp and bp.json_encoder99 else current_app.json_encoder105 "cls",106 bp.json_encoder if bp and bp.json_encoder else current_app.json_encoder,107 )108102 if not current_app.config['JSON_AS_ASCII']:103 kwargs.setdefault('ensure_ascii', False)109 if not current_app.config["JSON_AS_ASCII"]:110 kwargs.setdefault("ensure_ascii", False)111105 kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS'])112 kwargs.setdefault("sort_keys", current_app.config["JSON_SORT_KEYS"])113 else:107 kwargs.setdefault('sort_keys', True)108 kwargs.setdefault('cls', JSONEncoder)114 kwargs.setdefault("sort_keys", True)115 kwargs.setdefault("cls", JSONEncoder)116117118def _load_arg_defaults(kwargs):119 """Inject default arguments for load functions."""120 if current_app:121 bp = current_app.blueprints.get(request.blueprint) if request else None122 kwargs.setdefault(116 'cls',117 bp.json_decoder if bp and bp.json_decoder118 else current_app.json_decoder123 "cls",124 bp.json_decoder if bp and bp.json_decoder else current_app.json_decoder,125 )126 else:121 kwargs.setdefault('cls', JSONDecoder)127 kwargs.setdefault("cls", JSONDecoder)128129130def detect_encoding(data):131 """Detect which UTF codec was used to encode the given bytes.
7 unmodified lines
139 """140 head = data[:4]141142 if head[:3] == codecs.BOM_UTF8:137 return 'utf-8-sig'143 return "utf-8-sig"144139 if b'\x00' not in head:140 return 'utf-8'145 if b"\x00" not in head:146 return "utf-8"147148 if head in (codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE):143 return 'utf-32'149 return "utf-32"150151 if head[:2] in (codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE):146 return 'utf-16'152 return "utf-16"153154 if len(head) == 4:149 if head[:3] == b'\x00\x00\x00':150 return 'utf-32-be'155 if head[:3] == b"\x00\x00\x00":156 return "utf-32-be"157152 if head[::2] == b'\x00\x00':153 return 'utf-16-be'158 if head[::2] == b"\x00\x00":159 return "utf-16-be"160155 if head[1:] == b'\x00\x00\x00':156 return 'utf-32-le'161 if head[1:] == b"\x00\x00\x00":162 return "utf-32-le"163158 if head[1::2] == b'\x00\x00':159 return 'utf-16-le'164 if head[1::2] == b"\x00\x00":165 return "utf-16-le"166167 if len(head) == 2:162 return 'utf-16-be' if head.startswith(b'\x00') else 'utf-16-le'168 return "utf-16-be" if head.startswith(b"\x00") else "utf-16-le"169164 return 'utf-8'170 return "utf-8"171172173def dumps(obj, **kwargs):174 """Serialize ``obj`` to a JSON formatted ``str`` by using the application's
5 unmodified lines
180 default is controlled by the ``JSON_AS_ASCII`` configuration variable181 and can be overridden by the simplejson ``ensure_ascii`` parameter.182 """183 _dump_arg_defaults(kwargs)178 encoding = kwargs.pop('encoding', None)184 encoding = kwargs.pop("encoding", None)185 rv = _json.dumps(obj, **kwargs)186 if encoding is not None and isinstance(rv, text_type):187 rv = rv.encode(encoding)188 return rv
1 unmodified line
190191def dump(obj, fp, **kwargs):192 """Like :func:`dumps` but writes into a file object."""193 _dump_arg_defaults(kwargs)188 encoding = kwargs.pop('encoding', None)194 encoding = kwargs.pop("encoding", None)195 if encoding is not None:196 fp = _wrap_writer_for_text(fp, encoding)197 _json.dump(obj, fp, **kwargs)198
4 unmodified lines
203 application on the stack.204 """205 _load_arg_defaults(kwargs)206 if isinstance(s, bytes):201 encoding = kwargs.pop('encoding', None)207 encoding = kwargs.pop("encoding", None)208 if encoding is None:209 encoding = detect_encoding(s)210 s = s.decode(encoding)211 return _json.loads(s, **kwargs)
3 unmodified lines
215 """Like :func:`loads` but reads from a file object.216 """217 _load_arg_defaults(kwargs)218 if not PY2:213 fp = _wrap_reader_for_text(fp, kwargs.pop('encoding', None) or 'utf-8')219 fp = _wrap_reader_for_text(fp, kwargs.pop("encoding", None) or "utf-8")220 return _json.load(fp, **kwargs)221222223def htmlsafe_dumps(obj, **kwargs):
20 unmodified lines
244 hold true when using this function in HTML attributes that are double245 quoted. Always single quote attributes if you use the ``|tojson``246 filter. Alternatively use ``|tojson|forceescape``.247 """242 rv = dumps(obj, **kwargs) \243 .replace(u'<', u'\\u003c') \244 .replace(u'>', u'\\u003e') \245 .replace(u'&', u'\\u0026') \246 .replace(u"'", u'\\u0027')248 rv = (249 dumps(obj, **kwargs)250 .replace(u"<", u"\\u003c")251 .replace(u">", u"\\u003e")252 .replace(u"&", u"\\u0026")253 .replace(u"'", u"\\u0027")254 )255 if not _slash_escape:248 rv = rv.replace('\\/', '/')256 rv = rv.replace("\\/", "/")257 return rv258259260def htmlsafe_dump(obj, fp, **kwargs):
50 unmodified lines
311 .. versionadded:: 0.2312 """313314 indent = None307 separators = (',', ':')315 separators = (",", ":")316309 if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug:317 if current_app.config["JSONIFY_PRETTYPRINT_REGULAR"] or current_app.debug:318 indent = 2311 separators = (', ', ': ')319 separators = (", ", ": ")320321 if args and kwargs:314 raise TypeError('jsonify() behavior undefined when passed both args and kwargs')322 raise TypeError("jsonify() behavior undefined when passed both args and kwargs")323 elif len(args) == 1: # single args are passed directly to dumps()324 data = args[0]325 else:326 data = args or kwargs327328 return current_app.response_class(321 dumps(data, indent=indent, separators=separators) + '\n',322 mimetype=current_app.config['JSONIFY_MIMETYPE']329 dumps(data, indent=indent, separators=separators) + "\n",330 mimetype=current_app.config["JSONIFY_MIMETYPE"],331 )332333334def tojson_filter(obj, **kwargs):
1 unmodified line
modified:flask/json/tag.py+19 added-13 removed
54 unmodified lines
5556class JSONTag(object):57 """Base class for defining type tags for :class:`TaggedJSONSerializer`."""5859 __slots__ = ('serializer',)59 __slots__ = ("serializer",)6061 #: The tag to mark the serialized object with. If ``None``, this tag is62 #: only used as an intermediate step during tagging.63 key = None
29 unmodified lines
93 when deserializing.94 """9596 __slots__ = ()97 key = ' di'97 key = " di"9899 def check(self, value):100 return (101 isinstance(value, dict)
2 unmodified lines
104 )105106 def to_json(self, value):107 key = next(iter(value))108 return {key + '__': self.serializer.tag(value[key])}108 return {key + "__": self.serializer.tag(value[key])}109110 def to_python(self, value):111 key = next(iter(value))112 return {key[:-2]: value[key]}
14 unmodified lines
127128129class TagTuple(JSONTag):130 __slots__ = ()131 key = ' t'131 key = " t"132133 def check(self, value):134 return isinstance(value, tuple)135
17 unmodified lines
153154155class TagBytes(JSONTag):156 __slots__ = ()157 key = ' b'157 key = " b"158159 def check(self, value):160 return isinstance(value, bytes)161162 def to_json(self, value):163 return b64encode(value).decode('ascii')163 return b64encode(value).decode("ascii")164165 def to_python(self, value):166 return b64decode(value)167
3 unmodified lines
171 having a ``__html__`` method to the result of that method. Always172 deserializes to an instance of :class:`~flask.Markup`."""173174 __slots__ = ()175 key = ' m'175 key = " m"176177 def check(self, value):178 return callable(getattr(value, '__html__', None))178 return callable(getattr(value, "__html__", None))179180 def to_json(self, value):181 return text_type(value.__html__())182
2 unmodified lines
185186187class TagUUID(JSONTag):188 __slots__ = ()189 key = ' u'189 key = " u"190191 def check(self, value):192 return isinstance(value, UUID)193
5 unmodified lines
199200201class TagDateTime(JSONTag):202 __slots__ = ()203 key = ' d'203 key = " d"204205 def check(self, value):206 return isinstance(value, datetime)207
18 unmodified lines
226 * :class:`~uuid.UUID`227 * :class:`~datetime.datetime`228 """229230 __slots__ = ('tags', 'order')230 __slots__ = ("tags", "order")231232 #: Tag classes to bind when creating the serializer. Other tags can be233 #: added later using :meth:`~register`.234 default_tags = [235 TagDict, PassDict, TagTuple, PassList, TagBytes, TagMarkup, TagUUID,235 TagDict,236 PassDict,237 TagTuple,238 PassList,239 TagBytes,240 TagMarkup,241 TagUUID,242 TagDateTime,243 ]244245 def __init__(self):
52 unmodified lines
298 return self.tags[key].to_python(value[key])299300 def dumps(self, value):301 """Tag the value and dump it to a compact JSON string."""296 return dumps(self.tag(value), separators=(',', ':'))302 return dumps(self.tag(value), separators=(",", ":"))303304 def loads(self, value):305 """Load data from a JSON string and deserialized any tagged objects."""306 return loads(value, object_hook=self.untag)
modified:flask/__init__.py+39 added-12 removed
8 unmodified lines
9 :copyright: © 2010 by the Pallets team.10 :license: BSD, see LICENSE for more details.11"""1213__version__ = '1.1.dev'13__version__ = "1.1.dev"1415# utilities we import from Werkzeug and Jinja2 that are unused16# in the module but are exported as public interface.17from werkzeug.exceptions import abort
1 unmodified line
19from jinja2 import Markup, escape2021from .app import Flask, Request, Response22from .config import Config23from .helpers import url_for, flash, send_file, send_from_directory, \24 get_flashed_messages, get_template_attribute, make_response, safe_join, \25 stream_with_context26from .globals import current_app, g, request, session, _request_ctx_stack, \27 _app_ctx_stack28from .ctx import has_request_context, has_app_context, \29 after_this_request, copy_current_request_context23from .helpers import (24 url_for,25 flash,26 send_file,27 send_from_directory,28 get_flashed_messages,29 get_template_attribute,30 make_response,31 safe_join,32 stream_with_context,33)34from .globals import (35 current_app,36 g,37 request,38 session,39 _request_ctx_stack,40 _app_ctx_stack,41)42from .ctx import (43 has_request_context,44 has_app_context,45 after_this_request,46 copy_current_request_context,47)48from .blueprints import Blueprint49from .templating import render_template, render_template_string5051# the signals34from .signals import signals_available, template_rendered, request_started, \35 request_finished, got_request_exception, request_tearing_down, \36 appcontext_tearing_down, appcontext_pushed, \37 appcontext_popped, message_flashed, before_render_template52from .signals import (53 signals_available,54 template_rendered,55 request_started,56 request_finished,57 got_request_exception,58 request_tearing_down,59 appcontext_tearing_down,60 appcontext_pushed,61 appcontext_popped,62 message_flashed,63 before_render_template,64)6566# We're not exposing the actual json module but a convenient wrapper around67# it.68from . import json
4 unmodified lines
modified:flask/__main__.py+2 added-1 removed
7 unmodified lines
8 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112if __name__ == '__main__':12if __name__ == "__main__":13 from .cli import main1415 main(as_module=True)
modified:flask/_compat.py+10 added-6 removed
48 unmodified lines
49 from inspect import getargspec50 from cStringIO import StringIO51 import collections as collections_abc5253 exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')53 exec("def reraise(tp, value, tb=None):\n raise tp, value, tb")5455 def implements_to_string(cls):56 cls.__unicode__ = cls.__str__57 cls.__str__ = lambda x: x.__unicode__().encode('utf-8')57 cls.__str__ = lambda x: x.__unicode__().encode("utf-8")58 return cls596061def with_metaclass(meta, *bases):
3 unmodified lines
65 # itself with the actual metaclass.66 class metaclass(type):67 def __new__(cls, name, this_bases, d):68 return meta(name, bases, d)69 return type.__new__(metaclass, 'temporary_class', (), {})6970 return type.__new__(metaclass, "temporary_class", (), {})717273# Certain versions of pypy have a bug where clearing the exception stack74# breaks the __exit__ function in a very peculiar way. The second level of75# exception blocks is necessary because pypy seems to forget to check if an76# exception happened until the next bytecode instruction?
4 unmodified lines
81# versions.82#83# Ubuntu 14.04 has PyPy 2.2.1, which does exhibit this bug.84BROKEN_PYPY_CTXMGR_EXIT = False84if hasattr(sys, 'pypy_version_info'):85if hasattr(sys, "pypy_version_info"):8687 class _Mgr(object):88 def __enter__(self):89 return self9091 def __exit__(self, *args):89 if hasattr(sys, 'exc_clear'):92 if hasattr(sys, "exc_clear"):93 # Python 3 (PyPy3) doesn't have exc_clear94 sys.exc_clear()9596 try:97 try:98 with _Mgr():99 raise AssertionError()
10 unmodified lines
110except ImportError:111 # Backwards compatibility as proposed in PEP 0519:112 # https://www.python.org/dev/peps/pep-0519/#backwards-compatibility113 def fspath(path):110 return path.__fspath__() if hasattr(path, '__fspath__') else path114 return path.__fspath__() if hasattr(path, "__fspath__") else path
modified:flask/app.py+245 added-183 removed
16 unmodified lines
17from itertools import chain18from threading import Lock1920from werkzeug.datastructures import Headers, ImmutableDict21from werkzeug.exceptions import BadRequest, BadRequestKeyError, HTTPException, \22 InternalServerError, MethodNotAllowed, default_exceptions23from werkzeug.routing import BuildError, Map, RequestRedirect, \24 RoutingException, Rule21from werkzeug.exceptions import (22 BadRequest,23 BadRequestKeyError,24 HTTPException,25 InternalServerError,26 MethodNotAllowed,27 default_exceptions,28)29from werkzeug.routing import BuildError, Map, RequestRedirect, RoutingException, Rule3031from . import cli, json32from ._compat import integer_types, reraise, string_types, text_type33from .config import Config, ConfigAttribute34from .ctx import AppContext, RequestContext, _AppCtxGlobals35from .globals import _request_ctx_stack, g, request, session36from .helpers import (37 _PackageBoundObject,33 _endpoint_from_view_func, find_package, get_env, get_debug_flag,34 get_flashed_messages, locked_cached_property, url_for, get_load_dotenv38 _endpoint_from_view_func,39 find_package,40 get_env,41 get_debug_flag,42 get_flashed_messages,43 locked_cached_property,44 url_for,45 get_load_dotenv,46)47from .logging import create_logger48from .sessions import SecureCookieSessionInterface38from .signals import appcontext_tearing_down, got_request_exception, \39 request_finished, request_started, request_tearing_down40from .templating import DispatchingJinjaLoader, Environment, \41 _default_template_ctx_processor49from .signals import (50 appcontext_tearing_down,51 got_request_exception,52 request_finished,53 request_started,54 request_tearing_down,55)56from .templating import (57 DispatchingJinjaLoader,58 Environment,59 _default_template_ctx_processor,60)61from .wrappers import Request, Response6263# a singleton sentinel value for parameter defaults64_sentinel = object()
8 unmodified lines
73def setupmethod(f):74 """Wraps a method so that it performs a check in debug mode if the75 first request was already handled.76 """7778 def wrapper_func(self, *args, **kwargs):79 if self.debug and self._got_first_request:60 raise AssertionError('A setup function was called after the '61 'first request was handled. This usually indicates a bug '62 'in the application where a module was not imported '63 'and decorators or other functionality was called too late.\n'64 'To fix this make sure to import all your view modules, '65 'database models and everything related at a central place '66 'before the application starts serving requests.')80 raise AssertionError(81 "A setup function was called after the "82 "first request was handled. This usually indicates a bug "83 "in the application where a module was not imported "84 "and decorators or other functionality was called too late.\n"85 "To fix this make sure to import all your view modules, "86 "database models and everything related at a central place "87 "before the application starts serving requests."88 )89 return f(self, *args, **kwargs)9091 return update_wrapper(wrapper_func, f)929394class Flask(_PackageBoundObject):
144 unmodified lines
239 #: default it's implicitly enabled.240 #:241 #: This attribute can also be configured from the config with the242 #: ``TESTING`` configuration key. Defaults to ``False``.220 testing = ConfigAttribute('TESTING')243 testing = ConfigAttribute("TESTING")244245 #: If a secret key is set, cryptographic components can use this to246 #: sign cookies and other things. Set this to a complex random value247 #: when you want to use the secure cookie for instance.248 #:249 #: This attribute can also be configured from the config with the250 #: :data:`SECRET_KEY` configuration key. Defaults to ``None``.228 secret_key = ConfigAttribute('SECRET_KEY')251 secret_key = ConfigAttribute("SECRET_KEY")252253 #: The secure cookie uses this for the name of the session cookie.254 #:255 #: This attribute can also be configured from the config with the256 #: ``SESSION_COOKIE_NAME`` configuration key. Defaults to ``'session'``234 session_cookie_name = ConfigAttribute('SESSION_COOKIE_NAME')257 session_cookie_name = ConfigAttribute("SESSION_COOKIE_NAME")258259 #: A :class:`~datetime.timedelta` which is used to set the expiration260 #: date of a permanent session. The default is 31 days which makes a261 #: permanent session survive for roughly one month.262 #:263 #: This attribute can also be configured from the config with the264 #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to265 #: ``timedelta(days=31)``243 permanent_session_lifetime = ConfigAttribute('PERMANENT_SESSION_LIFETIME',244 get_converter=_make_timedelta)266 permanent_session_lifetime = ConfigAttribute(267 "PERMANENT_SESSION_LIFETIME", get_converter=_make_timedelta268 )269270 #: A :class:`~datetime.timedelta` which is used as default cache_timeout271 #: for the :func:`send_file` functions. The default is 12 hours.272 #:273 #: This attribute can also be configured from the config with the274 #: ``SEND_FILE_MAX_AGE_DEFAULT`` configuration key. This configuration275 #: variable can also be set with an integer value used as seconds.276 #: Defaults to ``timedelta(hours=12)``253 send_file_max_age_default = ConfigAttribute('SEND_FILE_MAX_AGE_DEFAULT',254 get_converter=_make_timedelta)277 send_file_max_age_default = ConfigAttribute(278 "SEND_FILE_MAX_AGE_DEFAULT", get_converter=_make_timedelta279 )280281 #: Enable this if you want to use the X-Sendfile feature. Keep in282 #: mind that the server has to support this. This only affects files283 #: sent with the :func:`send_file` method.
1 unmodified line
285 #: .. versionadded:: 0.2286 #:287 #: This attribute can also be configured from the config with the288 #: ``USE_X_SENDFILE`` configuration key. Defaults to ``False``.264 use_x_sendfile = ConfigAttribute('USE_X_SENDFILE')289 use_x_sendfile = ConfigAttribute("USE_X_SENDFILE")290291 #: The JSON encoder class to use. Defaults to :class:`~flask.json.JSONEncoder`.292 #:293 #: .. versionadded:: 0.10
5 unmodified lines
299 json_decoder = json.JSONDecoder300301 #: Options that are passed directly to the Jinja2 environment.302 jinja_options = ImmutableDict(278 extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']303 extensions=["jinja2.ext.autoescape", "jinja2.ext.with_"]304 )305306 #: Default configuration parameters.282 default_config = ImmutableDict({283 'ENV': None,284 'DEBUG': None,285 'TESTING': False,286 'PROPAGATE_EXCEPTIONS': None,287 'PRESERVE_CONTEXT_ON_EXCEPTION': None,288 'SECRET_KEY': None,289 'PERMANENT_SESSION_LIFETIME': timedelta(days=31),290 'USE_X_SENDFILE': False,291 'SERVER_NAME': None,292 'APPLICATION_ROOT': '/',293 'SESSION_COOKIE_NAME': 'session',294 'SESSION_COOKIE_DOMAIN': None,295 'SESSION_COOKIE_PATH': None,296 'SESSION_COOKIE_HTTPONLY': True,297 'SESSION_COOKIE_SECURE': False,298 'SESSION_COOKIE_SAMESITE': None,299 'SESSION_REFRESH_EACH_REQUEST': True,300 'MAX_CONTENT_LENGTH': None,301 'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12),302 'TRAP_BAD_REQUEST_ERRORS': None,303 'TRAP_HTTP_EXCEPTIONS': False,304 'EXPLAIN_TEMPLATE_LOADING': False,305 'PREFERRED_URL_SCHEME': 'http',306 'JSON_AS_ASCII': True,307 'JSON_SORT_KEYS': True,308 'JSONIFY_PRETTYPRINT_REGULAR': False,309 'JSONIFY_MIMETYPE': 'application/json',310 'TEMPLATES_AUTO_RELOAD': None,311 'MAX_COOKIE_SIZE': 4093,312 })307 default_config = ImmutableDict(308 {309 "ENV": None,310 "DEBUG": None,311 "TESTING": False,312 "PROPAGATE_EXCEPTIONS": None,313 "PRESERVE_CONTEXT_ON_EXCEPTION": None,314 "SECRET_KEY": None,315 "PERMANENT_SESSION_LIFETIME": timedelta(days=31),316 "USE_X_SENDFILE": False,317 "SERVER_NAME": None,318 "APPLICATION_ROOT": "/",319 "SESSION_COOKIE_NAME": "session",320 "SESSION_COOKIE_DOMAIN": None,321 "SESSION_COOKIE_PATH": None,322 "SESSION_COOKIE_HTTPONLY": True,323 "SESSION_COOKIE_SECURE": False,324 "SESSION_COOKIE_SAMESITE": None,325 "SESSION_REFRESH_EACH_REQUEST": True,326 "MAX_CONTENT_LENGTH": None,327 "SEND_FILE_MAX_AGE_DEFAULT": timedelta(hours=12),328 "TRAP_BAD_REQUEST_ERRORS": None,329 "TRAP_HTTP_EXCEPTIONS": False,330 "EXPLAIN_TEMPLATE_LOADING": False,331 "PREFERRED_URL_SCHEME": "http",332 "JSON_AS_ASCII": True,333 "JSON_SORT_KEYS": True,334 "JSONIFY_PRETTYPRINT_REGULAR": False,335 "JSONIFY_MIMETYPE": "application/json",336 "TEMPLATES_AUTO_RELOAD": None,337 "MAX_COOKIE_SIZE": 4093,338 }339 )340341 #: The rule object to use for URL rules created. This is used by342 #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.343 #:
37 unmodified lines
381 def __init__(382 self,383 import_name,384 static_url_path=None,358 static_folder='static',385 static_folder="static",386 static_host=None,387 host_matching=False,388 subdomain_matching=False,362 template_folder='templates',389 template_folder="templates",390 instance_path=None,391 instance_relative_config=False,365 root_path=None392 root_path=None,393 ):394 _PackageBoundObject.__init__(368 self,369 import_name,370 template_folder=template_folder,371 root_path=root_path395 self, import_name, template_folder=template_folder, root_path=root_path396 )397398 if static_url_path is not None:399 self.static_url_path = static_url_path
4 unmodified lines
404 if instance_path is None:405 instance_path = self.auto_find_instance_path()406 elif not os.path.isabs(instance_path):407 raise ValueError(384 'If an instance path is provided it must be absolute.'385 ' A relative path was given instead.'408 "If an instance path is provided it must be absolute."409 " A relative path was given instead."410 )411412 #: Holds the path to the instance folder.413 #:
99 unmodified lines
513 #: name of the blueprint this function is active for, ``None`` for all514 #: requests. Each returns a dictionary that the template context is515 #: updated with. To register a function here, use the516 #: :meth:`context_processor` decorator.493 self.template_context_processors = {494 None: [_default_template_ctx_processor]495 }517 self.template_context_processors = {None: [_default_template_ctx_processor]}518519 #: A list of shell context processor functions that should be run520 #: when a shell context is created.521 #:
54 unmodified lines
576 # Note we do this without checking if static_folder exists.577 # For one, it might be created while the server is running (e.g. during578 # development). Also, Google App Engine stores static files somewhere579 if self.has_static_folder:558 assert bool(static_host) == host_matching, 'Invalid static_host/host_matching combination'580 assert (581 bool(static_host) == host_matching582 ), "Invalid static_host/host_matching combination"583 self.add_url_rule(560 self.static_url_path + '/<path:filename>',561 endpoint='static',584 self.static_url_path + "/<path:filename>",585 endpoint="static",586 host=static_host,563 view_func=self.send_static_file587 view_func=self.send_static_file,588 )589590 #: The click command line context for this application. Commands591 #: registered here show up in the :command:`flask` command once the
12 unmodified lines
604 to change the value.605606 .. versionadded:: 0.8607 """584 if self.import_name == '__main__':585 fn = getattr(sys.modules['__main__'], '__file__', None)608 if self.import_name == "__main__":609 fn = getattr(sys.modules["__main__"], "__file__", None)610 if fn is None:587 return '__main__'611 return "__main__"612 return os.path.splitext(os.path.basename(fn))[0]613 return self.import_name614615 @property
2 unmodified lines
618 value in case it's set, otherwise a sensible default is returned.619620 .. versionadded:: 0.7621 """598 rv = self.config['PROPAGATE_EXCEPTIONS']622 rv = self.config["PROPAGATE_EXCEPTIONS"]623 if rv is not None:624 return rv625 return self.testing or self.debug626
4 unmodified lines
631 is returned.632633 .. versionadded:: 0.7634 """611 rv = self.config['PRESERVE_CONTEXT_ON_EXCEPTION']635 rv = self.config["PRESERVE_CONTEXT_ON_EXCEPTION"]636 if rv is not None:637 return rv638 return self.debug639
46 unmodified lines
686 root_path = self.root_path687 if instance_relative:688 root_path = self.instance_path689 defaults = dict(self.default_config)666 defaults['ENV'] = get_env()667 defaults['DEBUG'] = get_debug_flag()690 defaults["ENV"] = get_env()691 defaults["DEBUG"] = get_debug_flag()692 return self.config_class(root_path, defaults)693694 def auto_find_instance_path(self):695 """Tries to locate the instance path if it was not provided to the
4 unmodified lines
700 .. versionadded:: 0.8701 """702 prefix, package_path = find_package(self.import_name)703 if prefix is None:680 return os.path.join(package_path, 'instance')681 return os.path.join(prefix, 'var', self.name + '-instance')704 return os.path.join(package_path, "instance")705 return os.path.join(prefix, "var", self.name + "-instance")706683 def open_instance_resource(self, resource, mode='rb'):707 def open_instance_resource(self, resource, mode="rb"):708 """Opens a resource from the application's instance folder709 (:attr:`instance_path`). Otherwise works like710 :meth:`open_resource`. Instance resources can also be opened for711 writing.
14 unmodified lines
726 .. versionadded:: 1.0727 This property was added but the underlying config and behavior728 already existed.729 """706 rv = self.config['TEMPLATES_AUTO_RELOAD']730 rv = self.config["TEMPLATES_AUTO_RELOAD"]731 return rv if rv is not None else self.debug732733 def _set_templates_auto_reload(self, value):710 self.config['TEMPLATES_AUTO_RELOAD'] = value734 self.config["TEMPLATES_AUTO_RELOAD"] = value735736 templates_auto_reload = property(737 _get_templates_auto_reload, _set_templates_auto_reload738 )
11 unmodified lines
750 ``TEMPLATES_AUTO_RELOAD`` configuration option.751 """752 options = dict(self.jinja_options)753730 if 'autoescape' not in options:731 options['autoescape'] = self.select_jinja_autoescape754 if "autoescape" not in options:755 options["autoescape"] = self.select_jinja_autoescape756733 if 'auto_reload' not in options:734 options['auto_reload'] = self.templates_auto_reload757 if "auto_reload" not in options:758 options["auto_reload"] = self.templates_auto_reload759760 rv = self.jinja_environment(self, **options)761 rv.globals.update(762 url_for=url_for,
3 unmodified lines
766 # context processor for efficiency reasons but for imported767 # templates we also want the proxies in there.768 request=request,769 session=session,746 g=g770 g=g,771 )748 rv.filters['tojson'] = json.tojson_filter772 rv.filters["tojson"] = json.tojson_filter773 return rv774775 def create_global_jinja_loader(self):776 """Creates the loader for the Jinja2 environment. Can be used to
15 unmodified lines
792 .. versionadded:: 0.5793 """794 if filename is None:795 return True772 return filename.endswith(('.html', '.htm', '.xml', '.xhtml'))796 return filename.endswith((".html", ".htm", ".xml", ".xhtml"))797798 def update_template_context(self, context):799 """Update the template context with some commonly used variables.800 This injects request, session, config and g into the template
25 unmodified lines
826 processors.827828 .. versionadded:: 0.11829 """806 rv = {'app': self, 'g': g}830 rv = {"app": self, "g": g}831 for processor in self.shell_context_processors:832 rv.update(processor())833 return rv834
5 unmodified lines
840 #:841 #: **Do not enable development when deploying in production.**842 #:843 #: Default: ``'production'``820 env = ConfigAttribute('ENV')844 env = ConfigAttribute("ENV")845846 def _get_debug(self):823 return self.config['DEBUG']847 return self.config["DEBUG"]848849 def _set_debug(self, value):826 self.config['DEBUG'] = value850 self.config["DEBUG"] = value851 self.jinja_env.auto_reload = self.templates_auto_reload852853 #: Whether debug mode is enabled. When using ``flask run`` to start854 #: the development server, an interactive debugger will be shown for
9 unmodified lines
864 #: ``False`` otherwise.865 debug = property(_get_debug, _set_debug)866 del _get_debug, _set_debug867844 def run(self, host=None, port=None, debug=None,845 load_dotenv=True, **options):868 def run(self, host=None, port=None, debug=None, load_dotenv=True, **options):869 """Runs the application on a local development server.870871 Do not use ``run()`` in a production setting. It is not intended to872 meet security and performance requirements for a production server.
51 unmodified lines
924 variable.925 """926 # Change this into a no-op if the server is invoked from the927 # command line. Have a look at cli.py for more information.905 if os.environ.get('FLASK_RUN_FROM_CLI') == 'true':928 if os.environ.get("FLASK_RUN_FROM_CLI") == "true":929 from .debughelpers import explain_ignored_app_run930931 explain_ignored_app_run()932 return933934 if get_load_dotenv(load_dotenv):935 cli.load_dotenv()936937 # if set, let env vars override previous values914 if 'FLASK_ENV' in os.environ:938 if "FLASK_ENV" in os.environ:939 self.env = get_env()940 self.debug = get_debug_flag()917 elif 'FLASK_DEBUG' in os.environ:941 elif "FLASK_DEBUG" in os.environ:942 self.debug = get_debug_flag()943944 # debug passed to method overrides all other sources945 if debug is not None:946 self.debug = bool(debug)947924 _host = '127.0.0.1'948 _host = "127.0.0.1"949 _port = 5000926 server_name = self.config.get('SERVER_NAME')950 server_name = self.config.get("SERVER_NAME")951 sn_host, sn_port = None, None952953 if server_name:930 sn_host, _, sn_port = server_name.partition(':')954 sn_host, _, sn_port = server_name.partition(":")955956 host = host or sn_host or _host957 port = int(port or sn_port or _port)958935 options.setdefault('use_reloader', self.debug)936 options.setdefault('use_debugger', self.debug)937 options.setdefault('threaded', True)959 options.setdefault("use_reloader", self.debug)960 options.setdefault("use_debugger", self.debug)961 options.setdefault("threaded", True)962963 cli.show_server_banner(self.env, self.debug, self.name, False)964965 from werkzeug.serving import run_simple
91 unmodified lines
10571058 :param request: an instance of :attr:`request_class`.1059 """10601061 warnings.warn(1037 warnings.warn(DeprecationWarning(1038 '"open_session" is deprecated and will be removed in 1.1. Use'1039 ' "session_interface.open_session" instead.'1040 ))1062 DeprecationWarning(1063 '"open_session" is deprecated and will be removed in 1.1. Use'1064 ' "session_interface.open_session" instead.'1065 )1066 )1067 return self.session_interface.open_session(self, request)10681069 def save_session(self, session, response):1070 """Saves the session if it needs updates. For the default
9 unmodified lines
1080 object)1081 :param response: an instance of :attr:`response_class`1082 """10831084 warnings.warn(1058 warnings.warn(DeprecationWarning(1059 '"save_session" is deprecated and will be removed in 1.1. Use'1060 ' "session_interface.save_session" instead.'1061 ))1085 DeprecationWarning(1086 '"save_session" is deprecated and will be removed in 1.1. Use'1087 ' "session_interface.save_session" instead.'1088 )1089 )1090 return self.session_interface.save_session(self, session, response)10911092 def make_null_session(self):1093 """Creates a new instance of a missing session. Instead of overriding
5 unmodified lines
10991100 .. versionadded:: 0.71101 """11021103 warnings.warn(1075 warnings.warn(DeprecationWarning(1076 '"make_null_session" is deprecated and will be removed in 1.1. Use'1077 ' "session_interface.make_null_session" instead.'1078 ))1104 DeprecationWarning(1105 '"make_null_session" is deprecated and will be removed in 1.1. Use'1106 ' "session_interface.make_null_session" instead.'1107 )1108 )1109 return self.session_interface.make_null_session(self)11101111 @setupmethod1112 def register_blueprint(self, blueprint, **options):
18 unmodified lines
1131 first_registration = False11321133 if blueprint.name in self.blueprints:1134 assert self.blueprints[blueprint.name] is blueprint, (1105 'A name collision occurred between blueprints %r and %r. Both'1135 "A name collision occurred between blueprints %r and %r. Both"1136 ' share the same name "%s". Blueprints that are created on the'1107 ' fly need unique names.' % (1108 blueprint, self.blueprints[blueprint.name], blueprint.name1109 )1137 " fly need unique names."1138 % (blueprint, self.blueprints[blueprint.name], blueprint.name)1139 )1140 else:1141 self.blueprints[blueprint.name] = blueprint1142 self._blueprint_order.append(blueprint)
8 unmodified lines
1151 """1152 return iter(self._blueprint_order)11531154 @setupmethod1126 def add_url_rule(self, rule, endpoint=None, view_func=None,1127 provide_automatic_options=None, **options):1155 def add_url_rule(1156 self,1157 rule,1158 endpoint=None,1159 view_func=None,1160 provide_automatic_options=None,1161 **options1162 ):1163 """Connects a URL rule. Works exactly like the :meth:`route`1164 decorator. If a view_func is provided it will be registered with the1165 endpoint.1166
46 unmodified lines
1213 added and handled by the standard request handling.1214 """1215 if endpoint is None:1216 endpoint = _endpoint_from_view_func(view_func)1182 options['endpoint'] = endpoint1183 methods = options.pop('methods', None)1217 options["endpoint"] = endpoint1218 methods = options.pop("methods", None)12191220 # if the methods are not given and the view_func object knows its1221 # methods we can use that instead. If neither exists, we go with1222 # a tuple of only ``GET`` as default.1223 if methods is None:1189 methods = getattr(view_func, 'methods', None) or ('GET',)1224 methods = getattr(view_func, "methods", None) or ("GET",)1225 if isinstance(methods, string_types):1191 raise TypeError('Allowed methods have to be iterables of strings, '1192 'for example: @app.route(..., methods=["POST"])')1226 raise TypeError(1227 "Allowed methods have to be iterables of strings, "1228 'for example: @app.route(..., methods=["POST"])'1229 )1230 methods = set(item.upper() for item in methods)12311232 # Methods that should always be added1196 required_methods = set(getattr(view_func, 'required_methods', ()))1233 required_methods = set(getattr(view_func, "required_methods", ()))12341235 # starting with Flask 0.8 the view_func object can disable and1236 # force-enable the automatic options handling.1237 if provide_automatic_options is None:1201 provide_automatic_options = getattr(view_func,1202 'provide_automatic_options', None)1238 provide_automatic_options = getattr(1239 view_func, "provide_automatic_options", None1240 )12411242 if provide_automatic_options is None:1205 if 'OPTIONS' not in methods:1243 if "OPTIONS" not in methods:1244 provide_automatic_options = True1207 required_methods.add('OPTIONS')1245 required_methods.add("OPTIONS")1246 else:1247 provide_automatic_options = False12481249 # Add the required methods now.
5 unmodified lines
1255 self.url_map.add(rule)1256 if view_func is not None:1257 old_func = self.view_functions.get(endpoint)1258 if old_func is not None and old_func != view_func:1221 raise AssertionError('View function mapping is overwriting an '1222 'existing endpoint function: %s' % endpoint)1259 raise AssertionError(1260 "View function mapping is overwriting an "1261 "existing endpoint function: %s" % endpoint1262 )1263 self.view_functions[endpoint] = view_func12641265 def route(self, rule, **options):1266 """A decorator that is used to register a view function for a
18 unmodified lines
1285 just listens for ``GET`` (and implicitly ``HEAD``).1286 Starting with Flask 0.6, ``OPTIONS`` is implicitly1287 added and handled by the standard request handling.1288 """12891290 def decorator(f):1250 endpoint = options.pop('endpoint', None)1291 endpoint = options.pop("endpoint", None)1292 self.add_url_rule(rule, endpoint, f, **options)1293 return f12941295 return decorator12961297 @setupmethod1298 def endpoint(self, endpoint):
5 unmodified lines
1304 return "example"13051306 :param endpoint: the name of the endpoint1307 """13081309 def decorator(f):1310 self.view_functions[endpoint] = f1311 return f13121313 return decorator13141315 @staticmethod1316 def _get_exc_class_and_code(exc_class_or_code):
39 unmodified lines
13561357 :param code_or_exception: the code as integer for the handler, or1358 an arbitrary exception1359 """13601361 def decorator(f):1362 self._register_error_handler(None, code_or_exception, f)1363 return f13641365 return decorator13661367 @setupmethod1368 def register_error_handler(self, code_or_exception, f):
13 unmodified lines
1382 :type f: callable1383 """1384 if isinstance(code_or_exception, HTTPException): # old broken behavior1385 raise ValueError(1340 'Tried to register a handler for an exception instance {0!r}.'1341 ' Handlers can only be registered for exception classes or'1342 ' HTTP error codes.'.format(code_or_exception)1386 "Tried to register a handler for an exception instance {0!r}."1387 " Handlers can only be registered for exception classes or"1388 " HTTP error codes.".format(code_or_exception)1389 )13901391 try:1392 exc_class, code = self._get_exc_class_and_code(code_or_exception)
18 unmodified lines
14111412 :param name: the optional name of the filter, otherwise the1413 function name will be used.1414 """14151416 def decorator(f):1417 self.add_template_filter(f, name=name)1418 return f14191420 return decorator14211422 @setupmethod1423 def add_template_filter(self, f, name=None):
24 unmodified lines
14481449 :param name: the optional name of the test, otherwise the1450 function name will be used.1451 """14521453 def decorator(f):1454 self.add_template_test(f, name=name)1455 return f14561457 return decorator14581459 @setupmethod1460 def add_template_test(self, f, name=None):
21 unmodified lines
14821483 :param name: the optional name of the global function, otherwise the1484 function name will be used.1485 """14861487 def decorator(f):1488 self.add_template_global(f, name=name)1489 return f14901491 return decorator14921493 @setupmethod1494 def add_template_global(self, f, name=None):
169 unmodified lines
1664 """1665 exc_class, code = self._get_exc_class_and_code(type(e))16661667 for name, c in (1616 (request.blueprint, code), (None, code),1617 (request.blueprint, None), (None, None)1668 (request.blueprint, code),1669 (None, code),1670 (request.blueprint, None),1671 (None, None),1672 ):1673 handler_map = self.error_handler_spec.setdefault(name, {}).get(c)16741675 if not handler_map:
54 unmodified lines
1730 Bad request errors are not trapped by default in debug mode.17311732 .. versionadded:: 0.81733 """1680 if self.config['TRAP_HTTP_EXCEPTIONS']:1734 if self.config["TRAP_HTTP_EXCEPTIONS"]:1735 return True17361683 trap_bad_request = self.config['TRAP_BAD_REQUEST_ERRORS']1737 trap_bad_request = self.config["TRAP_BAD_REQUEST_ERRORS"]17381739 # if unset, trap key errors in debug mode1740 if (1687 trap_bad_request is None and self.debug1741 trap_bad_request is None1742 and self.debug1743 and isinstance(e, BadRequestKeyError)1744 ):1745 return True1746
80 unmodified lines
1827 :attr:`logger`.18281829 .. versionadded:: 0.81830 """1776 self.logger.error('Exception on %s [%s]' % (1777 request.path,1778 request.method1779 ), exc_info=exc_info)1831 self.logger.error(1832 "Exception on %s [%s]" % (request.path, request.method), exc_info=exc_info1833 )18341835 def raise_routing_exception(self, request):1836 """Exceptions that are recording during routing are reraised with1837 this method. During debug we are not reraising redirect requests
1 unmodified line
1839 a different error instead to help debug situations.18401841 :internal:1842 """1789 if not self.debug \1790 or not isinstance(request.routing_exception, RequestRedirect) \1791 or request.method in ('GET', 'HEAD', 'OPTIONS'):1843 if (1844 not self.debug1845 or not isinstance(request.routing_exception, RequestRedirect)1846 or request.method in ("GET", "HEAD", "OPTIONS")1847 ):1848 raise request.routing_exception18491850 from .debughelpers import FormDataRoutingRedirect18511852 raise FormDataRoutingRedirect(request)18531854 def dispatch_request(self):1855 """Does the request dispatching. Matches the URL and returns the
10 unmodified lines
1866 self.raise_routing_exception(req)1867 rule = req.url_rule1868 # if we provide automatic options for this URL and the1869 # request came with the OPTIONS method, reply automatically1813 if getattr(rule, 'provide_automatic_options', False) \1814 and req.method == 'OPTIONS':1870 if (1871 getattr(rule, "provide_automatic_options", False)1872 and req.method == "OPTIONS"1873 ):1874 return self.make_default_options_response()1875 # otherwise dispatch to the handler for that endpoint1876 return self.view_functions[rule.endpoint](**req.view_args)1877
33 unmodified lines
1911 request_finished.send(self, response=response)1912 except Exception:1913 if not from_error_handler:1914 raise1856 self.logger.exception('Request finalizing failed with an '1857 'error while handling an error')1915 self.logger.exception(1916 "Request finalizing failed with an " "error while handling an error"1917 )1918 return response19191920 def try_trigger_before_first_request_functions(self):1921 """Called before each request and will ensure that it triggers
18 unmodified lines
19401941 .. versionadded:: 0.71942 """1943 adapter = _request_ctx_stack.top.url_adapter1884 if hasattr(adapter, 'allowed_methods'):1944 if hasattr(adapter, "allowed_methods"):1945 methods = adapter.allowed_methods()1946 else:1947 # fallback for Werkzeug < 0.71948 methods = []1949 try:1890 adapter.match(method='--')1950 adapter.match(method="--")1951 except MethodNotAllowed as e:1952 methods = e.valid_methods1953 except HTTPException as e:1954 pass
68 unmodified lines
2023 rv, status = rv2024 # other sized tuples are not allowed2025 else:2026 raise TypeError(1967 'The view function did not return a valid response tuple.'1968 ' The tuple must have the form (body, status, headers),'1969 ' (body, status), or (body, headers).'2027 "The view function did not return a valid response tuple."2028 " The tuple must have the form (body, status, headers),"2029 " (body, status), or (body, headers)."2030 )20312032 # the body must not be None2033 if rv is None:2034 raise TypeError(1975 'The view function did not return a valid response. The'1976 ' function either returned None or ended without a return'1977 ' statement.'2035 "The view function did not return a valid response. The"2036 " function either returned None or ended without a return"2037 " statement."2038 )20392040 # make sure the body is an instance of the response class2041 if not isinstance(rv, self.response_class):
9 unmodified lines
2051 try:2052 rv = self.response_class.force_type(rv, request.environ)2053 except TypeError as e:2054 new_error = TypeError(1995 '{e}\nThe view function did not return a valid'1996 ' response. The return type must be a string, tuple,'1997 ' Response instance, or WSGI callable, but it was a'1998 ' {rv.__class__.__name__}.'.format(e=e, rv=rv)2055 "{e}\nThe view function did not return a valid"2056 " response. The return type must be a string, tuple,"2057 " Response instance, or WSGI callable, but it was a"2058 " {rv.__class__.__name__}.".format(e=e, rv=rv)2059 )2060 reraise(TypeError, new_error, sys.exc_info()[2])20612062 # prefer the status if it was provided
27 unmodified lines
2090 if request is not None:2091 # If subdomain matching is disabled (the default), use the2092 # default subdomain in all cases. This should be the default2093 # in Werkzeug but it currently does not have that feature.2094 subdomain = (2034 subdomain = ((self.url_map.default_subdomain or None)2035 if not self.subdomain_matching else None)2095 (self.url_map.default_subdomain or None)2096 if not self.subdomain_matching2097 else None2098 )2099 return self.url_map.bind_to_environ(2100 request.environ,2038 server_name=self.config['SERVER_NAME'],2039 subdomain=subdomain)2101 server_name=self.config["SERVER_NAME"],2102 subdomain=subdomain,2103 )2104 # We need at the very least the server name to be set for this2105 # to work.2042 if self.config['SERVER_NAME'] is not None:2106 if self.config["SERVER_NAME"] is not None:2107 return self.url_map.bind(2044 self.config['SERVER_NAME'],2045 script_name=self.config['APPLICATION_ROOT'],2046 url_scheme=self.config['PREFERRED_URL_SCHEME'])2108 self.config["SERVER_NAME"],2109 script_name=self.config["APPLICATION_ROOT"],2110 url_scheme=self.config["PREFERRED_URL_SCHEME"],2111 )21122113 def inject_url_defaults(self, endpoint, values):2114 """Injects the URL defaults for the given endpoint directly into2115 the values dictionary passed. This is used internally and
1 unmodified line
21172118 .. versionadded:: 0.72119 """2120 funcs = self.url_default_functions.get(None, ())2056 if '.' in endpoint:2057 bp = endpoint.rsplit('.', 1)[0]2121 if "." in endpoint:2122 bp = endpoint.rsplit(".", 1)[0]2123 funcs = chain(funcs, self.url_default_functions.get(bp, ()))2124 for func in funcs:2125 func(endpoint, values)2126
264 unmodified lines
2391 wrapped to applying middleware."""2392 return self.wsgi_app(environ, start_response)23932394 def __repr__(self):2330 return '<%s %r>' % (2331 self.__class__.__name__,2332 self.name,2333 )2395 return "<%s %r>" % (self.__class__.__name__, self.name)
modified:flask/blueprints.py+113 added-54 removed
37 unmodified lines
38 #: multiple times on it, this attribute can be used to figure39 #: out if the blueprint was registered in the past already.40 self.first_registration = first_registration4142 subdomain = self.options.get('subdomain')42 subdomain = self.options.get("subdomain")43 if subdomain is None:44 subdomain = self.blueprint.subdomain4546 #: The subdomain that the blueprint should be active for, ``None``47 #: otherwise.48 self.subdomain = subdomain4950 url_prefix = self.options.get('url_prefix')50 url_prefix = self.options.get("url_prefix")51 if url_prefix is None:52 url_prefix = self.blueprint.url_prefix53 #: The prefix that should be used for all URLs defined on the54 #: blueprint.
1 unmodified line
5657 #: A dictionary with URL defaults that is added to each and every58 #: URL that was defined with the blueprint.59 self.url_defaults = dict(self.blueprint.url_values_defaults)60 self.url_defaults.update(self.options.get('url_defaults', ()))60 self.url_defaults.update(self.options.get("url_defaults", ()))6162 def add_url_rule(self, rule, endpoint=None, view_func=None, **options):63 """A helper method to register a rule (and optionally a view function)64 to the application. The endpoint is automatically prefixed with the65 blueprint's name.66 """67 if self.url_prefix is not None:68 if rule:69 rule = '/'.join((70 self.url_prefix.rstrip('/'), rule.lstrip('/')))69 rule = "/".join((self.url_prefix.rstrip("/"), rule.lstrip("/")))70 else:71 rule = self.url_prefix73 options.setdefault('subdomain', self.subdomain)72 options.setdefault("subdomain", self.subdomain)73 if endpoint is None:74 endpoint = _endpoint_from_view_func(view_func)75 defaults = self.url_defaults77 if 'defaults' in options:78 defaults = dict(defaults, **options.pop('defaults'))79 self.app.add_url_rule(rule, '%s.%s' % (self.blueprint.name, endpoint),80 view_func, defaults=defaults, **options)76 if "defaults" in options:77 defaults = dict(defaults, **options.pop("defaults"))78 self.app.add_url_rule(79 rule,80 "%s.%s" % (self.blueprint.name, endpoint),81 view_func,82 defaults=defaults,83 **options84 )858687class Blueprint(_PackageBoundObject):88 """Represents a blueprint. A blueprint is an object that records
29 unmodified lines
118 #: Absolute path to the package on the filesystem. Used to look up119 #: resources contained in the package.120 root_path = None121118 def __init__(self, name, import_name, static_folder=None,119 static_url_path=None, template_folder=None,120 url_prefix=None, subdomain=None, url_defaults=None,121 root_path=None):122 _PackageBoundObject.__init__(self, import_name, template_folder,123 root_path=root_path)122 def __init__(123 self,124 name,125 import_name,126 static_folder=None,127 static_url_path=None,128 template_folder=None,129 url_prefix=None,130 subdomain=None,131 url_defaults=None,132 root_path=None,133 ):134 _PackageBoundObject.__init__(135 self, import_name, template_folder, root_path=root_path136 )137 self.name = name138 self.url_prefix = url_prefix139 self.subdomain = subdomain140 self.static_folder = static_folder
10 unmodified lines
151 method.152 """153 if self._got_registered_once and self.warn_on_modifications:154 from warnings import warn142 warn(Warning('The blueprint was already registered once '143 'but is getting modified now. These changes '144 'will not show up.'))155156 warn(157 Warning(158 "The blueprint was already registered once "159 "but is getting modified now. These changes "160 "will not show up."161 )162 )163 self.deferred_functions.append(func)164165 def record_once(self, func):166 """Works like :meth:`record` but wraps the function in another167 function that will ensure the function is only called once. If the168 blueprint is registered a second time on the application, the169 function passed is not called.170 """171172 def wrapper(state):173 if state.first_registration:174 func(state)175176 return self.record(update_wrapper(wrapper, func))177178 def make_setup_state(self, app, options, first_registration=False):179 """Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`
18 unmodified lines
198 state = self.make_setup_state(app, options, first_registration)199200 if self.has_static_folder:201 state.add_url_rule(182 self.static_url_path + '/<path:filename>',183 view_func=self.send_static_file, endpoint='static'202 self.static_url_path + "/<path:filename>",203 view_func=self.send_static_file,204 endpoint="static",205 )206207 for deferred in self.deferred_functions:208 deferred(state)
1 unmodified line
210 def route(self, rule, **options):211 """Like :meth:`Flask.route` but for a blueprint. The endpoint for the212 :func:`url_for` function is prefixed with the name of the blueprint.213 """214215 def decorator(f):216 endpoint = options.pop("endpoint", f.__name__)217 self.add_url_rule(rule, endpoint, f, **options)218 return f219220 return decorator221222 def add_url_rule(self, rule, endpoint=None, view_func=None, **options):223 """Like :meth:`Flask.add_url_rule` but for a blueprint. The endpoint for224 the :func:`url_for` function is prefixed with the name of the blueprint.225 """226 if endpoint:204 assert '.' not in endpoint, "Blueprint endpoints should not contain dots"205 if view_func and hasattr(view_func, '__name__'):206 assert '.' not in view_func.__name__, "Blueprint view function name should not contain dots"207 self.record(lambda s:208 s.add_url_rule(rule, endpoint, view_func, **options))227 assert "." not in endpoint, "Blueprint endpoints should not contain dots"228 if view_func and hasattr(view_func, "__name__"):229 assert (230 "." not in view_func.__name__231 ), "Blueprint view function name should not contain dots"232 self.record(lambda s: s.add_url_rule(rule, endpoint, view_func, **options))233234 def endpoint(self, endpoint):235 """Like :meth:`Flask.endpoint` but for a blueprint. This does not236 prefix the endpoint with the blueprint name, this has to be done237 explicitly by the user of this method. If the endpoint is prefixed238 with a `.` it will be registered to the current blueprint, otherwise239 it's an application independent endpoint.240 """241242 def decorator(f):243 def register_endpoint(state):244 state.app.view_functions[endpoint] = f245246 self.record_once(register_endpoint)247 return f248249 return decorator250251 def app_template_filter(self, name=None):252 """Register a custom template filter, available application wide. Like
1 unmodified line
254255 :param name: the optional name of the filter, otherwise the256 function name will be used.257 """258259 def decorator(f):260 self.add_app_template_filter(f, name=name)261 return f262263 return decorator264265 def add_app_template_filter(self, f, name=None):266 """Register a custom template filter, available application wide. Like
2 unmodified lines
269270 :param name: the optional name of the filter, otherwise the271 function name will be used.272 """273274 def register_template(state):275 state.app.jinja_env.filters[name or f.__name__] = f276277 self.record_once(register_template)278279 def app_template_test(self, name=None):280 """Register a custom template test, available application wide. Like
3 unmodified lines
284285 :param name: the optional name of the test, otherwise the286 function name will be used.287 """288289 def decorator(f):290 self.add_app_template_test(f, name=name)291 return f292293 return decorator294295 def add_app_template_test(self, f, name=None):296 """Register a custom template test, available application wide. Like
4 unmodified lines
301302 :param name: the optional name of the test, otherwise the303 function name will be used.304 """305306 def register_template(state):307 state.app.jinja_env.tests[name or f.__name__] = f308309 self.record_once(register_template)310311 def app_template_global(self, name=None):312 """Register a custom template global, available application wide. Like
3 unmodified lines
316317 :param name: the optional name of the global, otherwise the318 function name will be used.319 """320321 def decorator(f):322 self.add_app_template_global(f, name=name)323 return f324325 return decorator326327 def add_app_template_global(self, f, name=None):328 """Register a custom template global, available application wide. Like
4 unmodified lines
333334 :param name: the optional name of the global, otherwise the335 function name will be used.336 """337338 def register_template(state):339 state.app.jinja_env.globals[name or f.__name__] = f340341 self.record_once(register_template)342343 def before_request(self, f):344 """Like :meth:`Flask.before_request` but for a blueprint. This function345 is only executed before each request that is handled by a function of346 that blueprint.347 """309 self.record_once(lambda s: s.app.before_request_funcs310 .setdefault(self.name, []).append(f))348 self.record_once(349 lambda s: s.app.before_request_funcs.setdefault(self.name, []).append(f)350 )351 return f352353 def before_app_request(self, f):354 """Like :meth:`Flask.before_request`. Such a function is executed355 before each request, even if outside of a blueprint.356 """317 self.record_once(lambda s: s.app.before_request_funcs318 .setdefault(None, []).append(f))357 self.record_once(358 lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)359 )360 return f361362 def before_app_first_request(self, f):363 """Like :meth:`Flask.before_first_request`. Such a function is
6 unmodified lines
370 """Like :meth:`Flask.after_request` but for a blueprint. This function371 is only executed after each request that is handled by a function of372 that blueprint.373 """333 self.record_once(lambda s: s.app.after_request_funcs334 .setdefault(self.name, []).append(f))374 self.record_once(375 lambda s: s.app.after_request_funcs.setdefault(self.name, []).append(f)376 )377 return f378379 def after_app_request(self, f):380 """Like :meth:`Flask.after_request` but for a blueprint. Such a function381 is executed after each request, even if outside of the blueprint.382 """341 self.record_once(lambda s: s.app.after_request_funcs342 .setdefault(None, []).append(f))383 self.record_once(384 lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)385 )386 return f387388 def teardown_request(self, f):389 """Like :meth:`Flask.teardown_request` but for a blueprint. This
1 unmodified line
391 function of that blueprint. Teardown request functions are executed392 when the request context is popped, even when no actual request was393 performed.394 """352 self.record_once(lambda s: s.app.teardown_request_funcs353 .setdefault(self.name, []).append(f))395 self.record_once(396 lambda s: s.app.teardown_request_funcs.setdefault(self.name, []).append(f)397 )398 return f399400 def teardown_app_request(self, f):401 """Like :meth:`Flask.teardown_request` but for a blueprint. Such a402 function is executed when tearing down each request, even if outside of403 the blueprint.404 """361 self.record_once(lambda s: s.app.teardown_request_funcs362 .setdefault(None, []).append(f))405 self.record_once(406 lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)407 )408 return f409410 def context_processor(self, f):411 """Like :meth:`Flask.context_processor` but for a blueprint. This412 function is only executed for requests handled by a blueprint.413 """369 self.record_once(lambda s: s.app.template_context_processors370 .setdefault(self.name, []).append(f))414 self.record_once(415 lambda s: s.app.template_context_processors.setdefault(416 self.name, []417 ).append(f)418 )419 return f420421 def app_context_processor(self, f):422 """Like :meth:`Flask.context_processor` but for a blueprint. Such a423 function is executed each request, even if outside of the blueprint.424 """377 self.record_once(lambda s: s.app.template_context_processors378 .setdefault(None, []).append(f))425 self.record_once(426 lambda s: s.app.template_context_processors.setdefault(None, []).append(f)427 )428 return f429430 def app_errorhandler(self, code):431 """Like :meth:`Flask.errorhandler` but for a blueprint. This432 handler is used for all requests, even if outside of the blueprint.433 """434435 def decorator(f):436 self.record_once(lambda s: s.app.errorhandler(code)(f))437 return f438439 return decorator440441 def url_value_preprocessor(self, f):442 """Registers a function as URL value preprocessor for this443 blueprint. It's called before the view functions are called and444 can modify the url values provided.445 """395 self.record_once(lambda s: s.app.url_value_preprocessors396 .setdefault(self.name, []).append(f))446 self.record_once(447 lambda s: s.app.url_value_preprocessors.setdefault(self.name, []).append(f)448 )449 return f450451 def url_defaults(self, f):452 """Callback function for URL defaults for this blueprint. It's called453 with the endpoint and values and should update the values passed454 in place.455 """404 self.record_once(lambda s: s.app.url_default_functions405 .setdefault(self.name, []).append(f))456 self.record_once(457 lambda s: s.app.url_default_functions.setdefault(self.name, []).append(f)458 )459 return f460461 def app_url_value_preprocessor(self, f):462 """Same as :meth:`url_value_preprocessor` but application wide.463 """411 self.record_once(lambda s: s.app.url_value_preprocessors412 .setdefault(None, []).append(f))464 self.record_once(465 lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)466 )467 return f468469 def app_url_defaults(self, f):470 """Same as :meth:`url_defaults` but application wide.471 """418 self.record_once(lambda s: s.app.url_default_functions419 .setdefault(None, []).append(f))472 self.record_once(473 lambda s: s.app.url_default_functions.setdefault(None, []).append(f)474 )475 return f476477 def errorhandler(self, code_or_exception):478 """Registers an error handler that becomes active for this blueprint
5 unmodified lines
484485 Otherwise works as the :meth:`~flask.Flask.errorhandler` decorator486 of the :class:`~flask.Flask` object.487 """488489 def decorator(f):434 self.record_once(lambda s: s.app._register_error_handler(435 self.name, code_or_exception, f))490 self.record_once(491 lambda s: s.app._register_error_handler(self.name, code_or_exception, f)492 )493 return f494495 return decorator496497 def register_error_handler(self, code_or_exception, f):498 """Non-decorator version of the :meth:`errorhandler` error attach
2 unmodified lines
501 for error handlers limited to this blueprint.502503 .. versionadded:: 0.11504 """447 self.record_once(lambda s: s.app._register_error_handler(448 self.name, code_or_exception, f))505 self.record_once(506 lambda s: s.app._register_error_handler(self.name, code_or_exception, f)507 )
modified:flask/cli.py+180 added-159 removed
46 unmodified lines
47 """48 from . import Flask4950 # Search for the most common names first.51 for attr_name in ('app', 'application'):51 for attr_name in ("app", "application"):52 app = getattr(module, attr_name, None)5354 if isinstance(app, Flask):55 return app5657 # Otherwise find the only object that is a Flask instance.58 matches = [59 v for v in itervalues(module.__dict__) if isinstance(v, Flask)60 ]58 matches = [v for v in itervalues(module.__dict__) if isinstance(v, Flask)]5960 if len(matches) == 1:61 return matches[0]62 elif len(matches) > 1:63 raise NoAppException(64 'Detected multiple Flask applications in module "{module}". Use '65 '"FLASK_APP={module}:name" to specify the correct '68 'one.'.format(module=module.__name__)66 "one.".format(module=module.__name__)67 )6869 # Search for app factory functions.72 for attr_name in ('create_app', 'make_app'):70 for attr_name in ("create_app", "make_app"):71 app_factory = getattr(module, attr_name, None)7273 if inspect.isfunction(app_factory):74 try:
5 unmodified lines
80 if not _called_with_wrong_args(app_factory):81 raise82 raise NoAppException(83 'Detected factory "{factory}" in module "{module}", but '86 'could not call it without arguments. Use '87 '"FLASK_APP=\'{module}:{factory}(args)\'" to specify '88 'arguments.'.format(89 factory=attr_name, module=module.__name__90 )84 "could not call it without arguments. Use "85 "\"FLASK_APP='{module}:{factory}(args)'\" to specify "86 "arguments.".format(factory=attr_name, module=module.__name__)87 )8889 raise NoAppException(90 'Failed to find Flask application or factory in module "{module}". '95 'Use "FLASK_APP={module}:name to specify one.'.format(96 module=module.__name__97 )91 'Use "FLASK_APP={module}:name to specify one.'.format(module=module.__name__)92 )939495def call_factory(script_info, app_factory, arguments=()):
4 unmodified lines
100 args_spec = getargspec(app_factory)101 arg_names = args_spec.args102 arg_defaults = args_spec.defaults103110 if 'script_info' in arg_names:104 if "script_info" in arg_names:105 return app_factory(*arguments, script_info=script_info)106 elif arguments:107 return app_factory(*arguments)108 elif not arguments and len(arg_names) == 1 and arg_defaults is None:
32 unmodified lines
141 ``script_info`` argument and calls the function with the appropriate142 arguments.143 """144 from flask import Flask151 match = re.match(r'^ *([^ ()]+) *(?:\((.*?) *,? *\))? *$', app_name)145146 match = re.match(r"^ *([^ ()]+) *(?:\((.*?) *,? *\))? *$", app_name)147148 if not match:149 raise NoAppException(150 '"{name}" is not a valid variable name or function '156 'expression.'.format(name=app_name)151 "expression.".format(name=app_name)152 )153154 name, args = match.groups()155
4 unmodified lines
160161 if inspect.isfunction(attr):162 if args:163 try:169 args = ast.literal_eval('({args},)'.format(args=args))170 except (ValueError, SyntaxError)as e:164 args = ast.literal_eval("({args},)".format(args=args))165 except (ValueError, SyntaxError) as e:166 raise NoAppException(172 'Could not parse the arguments in '167 "Could not parse the arguments in "168 '"{app_name}".'.format(e=e, app_name=app_name)169 )170 else:171 args = ()
5 unmodified lines
177 raise178179 raise NoAppException(180 '{e}\nThe factory "{app_name}" in module "{module}" could not '186 'be called with the specified arguments.'.format(181 "be called with the specified arguments.".format(182 e=e, app_name=app_name, module=module.__name__183 )184 )185 else:
2 unmodified lines
188 if isinstance(app, Flask):189 return app190191 raise NoAppException(197 'A valid Flask application was not obtained from '198 '"{module}:{app_name}".'.format(199 module=module.__name__, app_name=app_name200 )192 "A valid Flask application was not obtained from "193 '"{module}:{app_name}".'.format(module=module.__name__, app_name=app_name)194 )195196197def prepare_import(path):
2 unmodified lines
200 """201 path = os.path.realpath(path)202203 fname, ext = os.path.splitext(path)211 if ext == '.py':204 if ext == ".py":205 path = fname206214 if os.path.basename(path) == '__init__':207 if os.path.basename(path) == "__init__":208 path = os.path.dirname(path)209210 module_name = []211
1 unmodified line
213 while True:214 path, name = os.path.split(path)215 module_name.append(name)216224 if not os.path.exists(os.path.join(path, '__init__.py')):217 if not os.path.exists(os.path.join(path, "__init__.py")):218 break219220 if sys.path[0] != path:221 sys.path.insert(0, path)222230 return '.'.join(module_name[::-1])223 return ".".join(module_name[::-1])224225226def locate_app(script_info, module_name, app_name, raise_if_not_found=True):227 __traceback_hide__ = True
5 unmodified lines
233 # Determine this by checking whether the trace has a depth > 1.234 if sys.exc_info()[-1].tb_next:235 raise NoAppException(236 'While importing "{name}", an ImportError was raised:'244 '\n\n{tb}'.format(name=module_name, tb=traceback.format_exc())237 "\n\n{tb}".format(name=module_name, tb=traceback.format_exc())238 )239 elif raise_if_not_found:247 raise NoAppException(248 'Could not import "{name}".'.format(name=module_name)249 )240 raise NoAppException('Could not import "{name}".'.format(name=module_name))241 else:242 return243244 module = sys.modules[module_name]
7 unmodified lines
252def get_version(ctx, param, value):253 if not value or ctx.resilient_parsing:254 return255 import werkzeug265 message = (266 'Python %(python)s\n'267 'Flask %(flask)s\n'268 'Werkzeug %(werkzeug)s'256257 message = "Python %(python)s\n" "Flask %(flask)s\n" "Werkzeug %(werkzeug)s"258 click.echo(259 message260 % {261 "python": platform.python_version(),262 "flask": __version__,263 "werkzeug": werkzeug.__version__,264 },265 color=ctx.color,266 )270 click.echo(message % {271 'python': platform.python_version(),272 'flask': __version__,273 'werkzeug': werkzeug.__version__,274 }, color=ctx.color)267 ctx.exit()268269270version_option = click.Option(279 ['--version'],280 help='Show the flask version',271 ["--version"],272 help="Show the flask version",273 expose_value=False,274 callback=get_version,275 is_flag=True,284 is_eager=True276 is_eager=True,277)278279280class DispatchingApp(object):
20 unmodified lines
301 try:302 self._load_unlocked()303 except Exception:304 self._bg_loading_exc_info = sys.exc_info()305306 t = Thread(target=_load_app, args=())307 t.start()308309 def _flush_bg_loading_exception(self):
30 unmodified lines
340 :class:`FlaskGroup` but you can also manually create it and pass it341 onwards as click object.342 """343351 def __init__(self, app_import_path=None, create_app=None,352 set_debug_flag=True):344 def __init__(self, app_import_path=None, create_app=None, set_debug_flag=True):345 #: Optionally the import path for the Flask application.354 self.app_import_path = app_import_path or os.environ.get('FLASK_APP')346 self.app_import_path = app_import_path or os.environ.get("FLASK_APP")347 #: Optionally a function that is passed the script info to create348 #: the instance of the application.349 self.create_app = create_app350 #: A dictionary with arbitrary data that can be associated with
17 unmodified lines
368 if self.create_app is not None:369 app = call_factory(self, self.create_app)370 else:371 if self.app_import_path:380 path, name = (re.split(r':(?![\\/])', self.app_import_path, 1) + [None])[:2]372 path, name = (373 re.split(r":(?![\\/])", self.app_import_path, 1) + [None]374 )[:2]375 import_name = prepare_import(path)376 app = locate_app(self, import_name, name)377 else:384 for path in ('wsgi.py', 'app.py'):378 for path in ("wsgi.py", "app.py"):379 import_name = prepare_import(path)386 app = locate_app(self, import_name, None,387 raise_if_not_found=False)380 app = locate_app(self, import_name, None, raise_if_not_found=False)381382 if app:383 break384385 if not app:386 raise NoAppException(394 'Could not locate a Flask application. You did not provide '387 "Could not locate a Flask application. You did not provide "388 'the "FLASK_APP" environment variable, and a "wsgi.py" or '389 '"app.py" module was not found in the current directory.'390 )391
14 unmodified lines
406 script's application context. If callbacks are registered directly407 to the ``app.cli`` object then they are wrapped with this function408 by default unless it's disabled.409 """410411 @click.pass_context412 def decorator(__ctx, *args, **kwargs):413 with __ctx.ensure_object(ScriptInfo).load_app().app_context():414 return __ctx.invoke(f, *args, **kwargs)415416 return update_wrapper(decorator, f)417418419class AppGroup(click.Group):
8 unmodified lines
428 """This works exactly like the method of the same name on a regular429 :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`430 unless it's disabled by passing ``with_appcontext=False``.431 """437 wrap_for_ctx = kwargs.pop('with_appcontext', True)432 wrap_for_ctx = kwargs.pop("with_appcontext", True)433434 def decorator(f):435 if wrap_for_ctx:436 f = with_appcontext(f)437 return click.Group.command(self, *args, **kwargs)(f)438439 return decorator440441 def group(self, *args, **kwargs):442 """This works exactly like the method of the same name on a regular443 :class:`click.Group` but it defaults the group class to444 :class:`AppGroup`.445 """449 kwargs.setdefault('cls', AppGroup)446 kwargs.setdefault("cls", AppGroup)447 return click.Group.group(self, *args, **kwargs)448449450class FlaskGroup(AppGroup):
20 unmodified lines
471 If installed, python-dotenv will be used to load environment variables472 from :file:`.env` and :file:`.flaskenv` files.473 """474478 def __init__(self, add_default_commands=True, create_app=None,479 add_version_option=True, load_dotenv=True,480 set_debug_flag=True, **extra):481 params = list(extra.pop('params', None) or ())475 def __init__(476 self,477 add_default_commands=True,478 create_app=None,479 add_version_option=True,480 load_dotenv=True,481 set_debug_flag=True,482 **extra483 ):484 params = list(extra.pop("params", None) or ())485486 if add_version_option:487 params.append(version_option)488
17 unmodified lines
506 except ImportError:507 self._loaded_plugin_commands = True508 return509507 for ep in pkg_resources.iter_entry_points('flask.commands'):510 for ep in pkg_resources.iter_entry_points("flask.commands"):511 self.add_command(ep.load(), ep.name)512 self._loaded_plugin_commands = True513514 def get_command(self, ctx, name):
41 unmodified lines
556 # Set a global flag that indicates that we were invoked from the557 # command line interface. This is detected by Flask.run to make the558 # call into a no-op. This is necessary to avoid ugly errors when the559 # script that is loaded here also attempts to start a server.557 os.environ['FLASK_RUN_FROM_CLI'] = 'true'560 os.environ["FLASK_RUN_FROM_CLI"] = "true"561562 if get_load_dotenv(self.load_dotenv):563 load_dotenv()564562 obj = kwargs.get('obj')565 obj = kwargs.get("obj")566567 if obj is None:565 obj = ScriptInfo(create_app=self.create_app,566 set_debug_flag=self.set_debug_flag)568 obj = ScriptInfo(569 create_app=self.create_app, set_debug_flag=self.set_debug_flag570 )571568 kwargs['obj'] = obj569 kwargs.setdefault('auto_envvar_prefix', 'FLASK')572 kwargs["obj"] = obj573 kwargs.setdefault("auto_envvar_prefix", "FLASK")574 return super(FlaskGroup, self).main(*args, **kwargs)575576577def _path_is_ancestor(path, other):578 """Take ``other`` and remove the length of ``path`` from it. Then join it579 to ``path``. If it is the original value, ``path`` is an ancestor of580 ``other``."""577 return os.path.join(path, other[len(path):].lstrip(os.sep)) == other581 return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other582583584def load_dotenv(path=None):585 """Load "dotenv" files in order of precedence to set environment variables.
14 unmodified lines
600601 .. versionadded:: 1.0602 """603 if dotenv is None:600 if path or os.path.isfile('.env') or os.path.isfile('.flaskenv'):604 if path or os.path.isfile(".env") or os.path.isfile(".flaskenv"):605 click.secho(602 ' * Tip: There are .env or .flaskenv files present.'606 " * Tip: There are .env or .flaskenv files present."607 ' Do "pip install python-dotenv" to use them.',604 fg='yellow')608 fg="yellow",609 )610 return611612 if path is not None:613 return dotenv.load_dotenv(path)614615 new_dir = None616612 for name in ('.env', '.flaskenv'):617 for name in (".env", ".flaskenv"):618 path = dotenv.find_dotenv(name, usecwd=True)619620 if not path:621 continue
12 unmodified lines
634def show_server_banner(env, debug, app_import_path, eager_loading):635 """Show extra startup messages the first time the server is run,636 ignoring the reloader.637 """633 if os.environ.get('WERKZEUG_RUN_MAIN') == 'true':638 if os.environ.get("WERKZEUG_RUN_MAIN") == "true":639 return640641 if app_import_path is not None:642 message = ' * Serving Flask app "{0}"'.format(app_import_path)643644 if not eager_loading:640 message += ' (lazy loading)'645 message += " (lazy loading)"646647 click.echo(message)648644 click.echo(' * Environment: {0}'.format(env))649 click.echo(" * Environment: {0}".format(env))650646 if env == 'production':651 if env == "production":652 click.secho(648 ' WARNING: Do not use the development server in a production'649 ' environment.', fg='red')650 click.secho(' Use a production WSGI server instead.', dim=True)653 " WARNING: Do not use the development server in a production"654 " environment.",655 fg="red",656 )657 click.secho(" Use a production WSGI server instead.", dim=True)658659 if debug is not None:653 click.echo(' * Debug mode: {0}'.format('on' if debug else 'off'))660 click.echo(" * Debug mode: {0}".format("on" if debug else "off"))661662663class CertParamType(click.ParamType):664 """Click option type for the ``--cert`` option. Allows either an665 existing file, the string ``'adhoc'``, or an import for a666 :class:`~ssl.SSLContext` object.667 """668662 name = 'path'669 name = "path"670671 def __init__(self):665 self.path_type = click.Path(666 exists=True, dir_okay=False, resolve_path=True)672 self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)673674 def convert(self, value, param, ctx):675 try:676 return self.path_type(value, param, ctx)677 except click.BadParameter:678 value = click.STRING(value, param, ctx).lower()679674 if value == 'adhoc':680 if value == "adhoc":681 try:682 import OpenSSL683 except ImportError:684 raise click.BadParameter(679 'Using ad-hoc certificates requires pyOpenSSL.',680 ctx, param)685 "Using ad-hoc certificates requires pyOpenSSL.", ctx, param686 )687688 return value689690 obj = import_string(value, silent=True)
11 unmodified lines
702def _validate_key(ctx, param, value):703 """The ``--key`` option must be specified when ``--cert`` is a file.704 Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.705 """700 cert = ctx.params.get('cert')701 is_adhoc = cert == 'adhoc'706 cert = ctx.params.get("cert")707 is_adhoc = cert == "adhoc"708709 if sys.version_info < (2, 7, 9):710 is_context = cert and not isinstance(cert, (text_type, bytes))711 else:
1 unmodified line
713714 if value is not None:715 if is_adhoc:716 raise click.BadParameter(711 'When "--cert" is "adhoc", "--key" is not used.',712 ctx, param)717 'When "--cert" is "adhoc", "--key" is not used.', ctx, param718 )719720 if is_context:721 raise click.BadParameter(716 'When "--cert" is an SSLContext object, "--key is not used.',717 ctx, param)722 'When "--cert" is an SSLContext object, "--key is not used.', ctx, param723 )724725 if not cert:720 raise click.BadParameter(721 '"--cert" must also be specified.',722 ctx, param)726 raise click.BadParameter('"--cert" must also be specified.', ctx, param)727724 ctx.params['cert'] = cert, value728 ctx.params["cert"] = cert, value729730 else:731 if cert and not (is_adhoc or is_context):728 raise click.BadParameter(729 'Required when using "--cert".',730 ctx, param)732 raise click.BadParameter('Required when using "--cert".', ctx, param)733734 return value735736735@click.command('run', short_help='Run a development server.')736@click.option('--host', '-h', default='127.0.0.1',737 help='The interface to bind to.')738@click.option('--port', '-p', default=5000,739 help='The port to bind to.')740@click.option('--cert', type=CertParamType(),741 help='Specify a certificate file to use HTTPS.')742@click.option('--key',743 type=click.Path(exists=True, dir_okay=False, resolve_path=True),744 callback=_validate_key, expose_value=False,745 help='The key file to use when specifying a certificate.')746@click.option('--reload/--no-reload', default=None,747 help='Enable or disable the reloader. By default the reloader '748 'is active if debug is enabled.')749@click.option('--debugger/--no-debugger', default=None,750 help='Enable or disable the debugger. By default the debugger '751 'is active if debug is enabled.')752@click.option('--eager-loading/--lazy-loader', default=None,753 help='Enable or disable eager loading. By default eager '754 'loading is enabled if the reloader is disabled.')755@click.option('--with-threads/--without-threads', default=True,756 help='Enable or disable multithreading.')737@click.command("run", short_help="Run a development server.")738@click.option("--host", "-h", default="127.0.0.1", help="The interface to bind to.")739@click.option("--port", "-p", default=5000, help="The port to bind to.")740@click.option(741 "--cert", type=CertParamType(), help="Specify a certificate file to use HTTPS."742)743@click.option(744 "--key",745 type=click.Path(exists=True, dir_okay=False, resolve_path=True),746 callback=_validate_key,747 expose_value=False,748 help="The key file to use when specifying a certificate.",749)750@click.option(751 "--reload/--no-reload",752 default=None,753 help="Enable or disable the reloader. By default the reloader "754 "is active if debug is enabled.",755)756@click.option(757 "--debugger/--no-debugger",758 default=None,759 help="Enable or disable the debugger. By default the debugger "760 "is active if debug is enabled.",761)762@click.option(763 "--eager-loading/--lazy-loader",764 default=None,765 help="Enable or disable eager loading. By default eager "766 "loading is enabled if the reloader is disabled.",767)768@click.option(769 "--with-threads/--without-threads",770 default=True,771 help="Enable or disable multithreading.",772)773@pass_script_info758def run_command(info, host, port, reload, debugger, eager_loading,759 with_threads, cert):774def run_command(info, host, port, reload, debugger, eager_loading, with_threads, cert):775 """Run a local development server.776777 This server is for development purposes only. It does not provide778 the stability, security, or performance of production WSGI servers.
15 unmodified lines
794 show_server_banner(get_env(), debug, info.app_import_path, eager_loading)795 app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)796797 from werkzeug.serving import run_simple783 run_simple(host, port, app, use_reloader=reload, use_debugger=debugger,784 threaded=with_threads, ssl_context=cert)798799 run_simple(800 host,801 port,802 app,803 use_reloader=reload,804 use_debugger=debugger,805 threaded=with_threads,806 ssl_context=cert,807 )808787@click.command('shell', short_help='Run a shell in the app context.')809810@click.command("shell", short_help="Run a shell in the app context.")811@with_appcontext812def shell_command():813 """Run an interactive Python shell in the context of a given814 Flask application. The application will populate the default
3 unmodified lines
818 without having to manually configure the application.819 """820 import code821 from flask.globals import _app_ctx_stack822823 app = _app_ctx_stack.top.app800 banner = 'Python %s on %s\nApp: %s [%s]\nInstance: %s' % (824 banner = "Python %s on %s\nApp: %s [%s]\nInstance: %s" % (825 sys.version,826 sys.platform,827 app.import_name,828 app.env,
2 unmodified lines
831 ctx = {}832833 # Support the regular Python interpreter startup script if someone834 # is using it.811 startup = os.environ.get('PYTHONSTARTUP')835 startup = os.environ.get("PYTHONSTARTUP")836 if startup and os.path.isfile(startup):813 with open(startup, 'r') as f:814 eval(compile(f.read(), startup, 'exec'), ctx)837 with open(startup, "r") as f:838 eval(compile(f.read(), startup, "exec"), ctx)839840 ctx.update(app.make_shell_context())841842 code.interact(banner=banner, local=ctx)843844821@click.command('routes', short_help='Show the routes for the app.')845@click.command("routes", short_help="Show the routes for the app.")846@click.option(823 '--sort', '-s',824 type=click.Choice(('endpoint', 'methods', 'rule', 'match')),825 default='endpoint',847 "--sort",848 "-s",849 type=click.Choice(("endpoint", "methods", "rule", "match")),850 default="endpoint",851 help=(852 'Method to sort routes by. "match" is the order that Flask will match '828 'routes when dispatching a request.'829 )853 "routes when dispatching a request."854 ),855)831@click.option(832 '--all-methods',833 is_flag=True,834 help="Show HEAD and OPTIONS methods."835)856@click.option("--all-methods", is_flag=True, help="Show HEAD and OPTIONS methods.")857@with_appcontext858def routes_command(sort, all_methods):859 """Show all registered routes with endpoints and methods."""860861 rules = list(current_app.url_map.iter_rules())862 if not rules:842 click.echo('No routes were registered.')863 click.echo("No routes were registered.")864 return865845 ignored_methods = set(() if all_methods else ('HEAD', 'OPTIONS'))866 ignored_methods = set(() if all_methods else ("HEAD", "OPTIONS"))867847 if sort in ('endpoint', 'rule'):868 if sort in ("endpoint", "rule"):869 rules = sorted(rules, key=attrgetter(sort))849 elif sort == 'methods':870 elif sort == "methods":871 rules = sorted(rules, key=lambda rule: sorted(rule.methods))872852 rule_methods = [853 ', '.join(sorted(rule.methods - ignored_methods)) for rule in rules854 ]873 rule_methods = [", ".join(sorted(rule.methods - ignored_methods)) for rule in rules]874856 headers = ('Endpoint', 'Methods', 'Rule')875 headers = ("Endpoint", "Methods", "Rule")876 widths = (877 max(len(rule.endpoint) for rule in rules),878 max(len(methods) for methods in rule_methods),879 max(len(rule.rule) for rule in rules),880 )881 widths = [max(len(h), w) for h, w in zip(headers, widths)]863 row = '{{0:<{0}}} {{1:<{1}}} {{2:<{2}}}'.format(*widths)882 row = "{{0:<{0}}} {{1:<{1}}} {{2:<{2}}}".format(*widths)883884 click.echo(row.format(*headers).strip())866 click.echo(row.format(*('-' * width for width in widths)))885 click.echo(row.format(*("-" * width for width in widths)))886887 for rule, methods in zip(rules, rule_methods):888 click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())889890872cli = FlaskGroup(help="""\891cli = FlaskGroup(892 help="""\893A general utility script for Flask applications.894895Provides commands from Flask, extensions, and the application. Loads the896application defined in the FLASK_APP environment variable, or from a wsgi.py
4 unmodified lines
901 {prefix}{cmd} FLASK_APP=hello.py902 {prefix}{cmd} FLASK_ENV=development903 {prefix}flask run904""".format(885 cmd='export' if os.name == 'posix' else 'set',886 prefix='$ ' if os.name == 'posix' else '> '887))905 cmd="export" if os.name == "posix" else "set",906 prefix="$ " if os.name == "posix" else "> ",907 )908)909910911def main(as_module=False):912 args = sys.argv[1:]913914 if as_module:894 this_module = 'flask'915 this_module = "flask"916917 if sys.version_info < (2, 7):897 this_module += '.cli'918 this_module += ".cli"919899 name = 'python -m ' + this_module920 name = "python -m " + this_module921922 # Python rewrites "python -m flask" to the path to the file in argv.923 # Restore the original command so that the reloader works.903 sys.argv = ['-m', this_module] + args924 sys.argv = ["-m", this_module] + args925 else:926 name = None927928 cli.main(args=args, prog_name=name)929930910if __name__ == '__main__':931if __name__ == "__main__":932 main(as_module=True)
modified:flask/config.py+16 added-17 removed
99 unmodified lines
100 rv = os.environ.get(variable_name)101 if not rv:102 if silent:103 return False104 raise RuntimeError('The environment variable %r is not set '105 'and as such configuration could not be '106 'loaded. Set this variable and make it '107 'point to a configuration file' %108 variable_name)104 raise RuntimeError(105 "The environment variable %r is not set "106 "and as such configuration could not be "107 "loaded. Set this variable and make it "108 "point to a configuration file" % variable_name109 )110 return self.from_pyfile(rv, silent=silent)111112 def from_pyfile(self, filename, silent=False):113 """Updates the values in the config from a Python file. This function
9 unmodified lines
123 .. versionadded:: 0.7124 `silent` parameter.125 """126 filename = os.path.join(self.root_path, filename)126 d = types.ModuleType('config')127 d = types.ModuleType("config")128 d.__file__ = filename129 try:129 with open(filename, mode='rb') as config_file:130 exec(compile(config_file.read(), filename, 'exec'), d.__dict__)130 with open(filename, mode="rb") as config_file:131 exec(compile(config_file.read(), filename, "exec"), d.__dict__)132 except IOError as e:132 if silent and e.errno in (133 errno.ENOENT, errno.EISDIR, errno.ENOTDIR134 ):133 if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):134 return False136 e.strerror = 'Unable to load configuration file (%s)' % e.strerror135 e.strerror = "Unable to load configuration file (%s)" % e.strerror136 raise137 self.from_object(d)138 return True139
55 unmodified lines
195 obj = json.loads(json_file.read())196 except IOError as e:197 if silent and e.errno in (errno.ENOENT, errno.EISDIR):198 return False200 e.strerror = 'Unable to load configuration file (%s)' % e.strerror199 e.strerror = "Unable to load configuration file (%s)" % e.strerror200 raise201 return self.from_mapping(obj)202203 def from_mapping(self, *mapping, **kwargs):
3 unmodified lines
207 .. versionadded:: 0.11208 """209 mappings = []210 if len(mapping) == 1:212 if hasattr(mapping[0], 'items'):211 if hasattr(mapping[0], "items"):212 mappings.append(mapping[0].items())213 else:214 mappings.append(mapping[0])215 elif len(mapping) > 1:216 raise TypeError(218 'expected at most 1 positional argument, got %d' % len(mapping)217 "expected at most 1 positional argument, got %d" % len(mapping)218 )219 mappings.append(kwargs.items())220 for mapping in mappings:221 for (key, value) in mapping:
33 unmodified lines
255 for k, v in iteritems(self):256 if not k.startswith(namespace):257 continue258 if trim_namespace:260 key = k[len(namespace):]259 key = k[len(namespace) :]260 else:261 key = k262 if lowercase:263 key = key.lower()264 rv[key] = v265 return rv266267 def __repr__(self):269 return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self))268 return "<%s %s>" % (self.__class__.__name__, dict.__repr__(self))
modified:flask/ctx.py+28 added-23 removed
87 unmodified lines
8889 def __repr__(self):90 top = _app_ctx_stack.top91 if top is not None:92 return '<flask.g of %r>' % top.app.name92 return "<flask.g of %r>" % top.app.name93 return object.__repr__(self)949596def after_this_request(f):
46 unmodified lines
143 .. versionadded:: 0.10144 """145 top = _request_ctx_stack.top146 if top is None:147 raise RuntimeError('This decorator can only be used at local scopes '148 'when a request context is on the stack. For instance within '149 'view functions.')147 raise RuntimeError(148 "This decorator can only be used at local scopes "149 "when a request context is on the stack. For instance within "150 "view functions."151 )152 reqctx = top.copy()153154 def wrapper(*args, **kwargs):155 with reqctx:156 return f(*args, **kwargs)157158 return update_wrapper(wrapper, f)159160161def has_request_context():
58 unmodified lines
220221 def push(self):222 """Binds the app context to the current context."""223 self._refcnt += 1220 if hasattr(sys, 'exc_clear'):224 if hasattr(sys, "exc_clear"):225 sys.exc_clear()226 _app_ctx_stack.push(self)227 appcontext_pushed.send(self.app)228
6 unmodified lines
235 exc = sys.exc_info()[1]236 self.app.do_teardown_appcontext(exc)237 finally:238 rv = _app_ctx_stack.pop()235 assert rv is self, 'Popped wrong app context. (%r instead of %r)' \236 % (rv, self)239 assert rv is self, "Popped wrong app context. (%r instead of %r)" % (rv, self)240 appcontext_popped.send(self.app)241242 def __enter__(self):243 self.push()
72 unmodified lines
316 self.match_request()317318 def _get_g(self):319 return _app_ctx_stack.top.g320321 def _set_g(self, value):322 _app_ctx_stack.top.g = value323324 g = property(_get_g, _set_g)325 del _get_g, _set_g326327 def copy(self):
8 unmodified lines
336 .. versionchanged:: 1.1337 The current session object is used instead of reloading the original338 data. This prevents `flask.session` pointing to an out-of-date object.339 """335 return self.__class__(self.app,340 return self.__class__(341 self.app,342 environ=self.request.environ,343 request=self.request,338 session=self.session344 session=self.session,345 )346347 def match_request(self):348 """Can be overridden by a subclass to hook into the matching349 of the request.350 """351 try:346 url_rule, self.request.view_args = \347 self.url_adapter.match(return_rule=True)352 url_rule, self.request.view_args = self.url_adapter.match(return_rule=True)353 self.request.url_rule = url_rule354 except HTTPException as e:355 self.request.routing_exception = e356
20 unmodified lines
377 self._implicit_app_ctx_stack.append(app_ctx)378 else:379 self._implicit_app_ctx_stack.append(None)380376 if hasattr(sys, 'exc_clear'):381 if hasattr(sys, "exc_clear"):382 sys.exc_clear()383384 _request_ctx_stack.push(self)385
2 unmodified lines
388 # Only open a new session if this is the first time the request was389 # pushed, otherwise stream_with_context loses the session.390 if self.session is None:391 session_interface = self.app.session_interface387 self.session = session_interface.open_session(388 self.app, self.request389 )392 self.session = session_interface.open_session(self.app, self.request)393394 if self.session is None:395 self.session = session_interface.make_null_session(self.app)396
19 unmodified lines
416 # If this interpreter supports clearing the exception information417 # we do that now. This will only go into effect on Python 2.x,418 # on 3.x it disappears automatically at the end of the exception419 # stack.417 if hasattr(sys, 'exc_clear'):420 if hasattr(sys, "exc_clear"):421 sys.exc_clear()422420 request_close = getattr(self.request, 'close', None)423 request_close = getattr(self.request, "close", None)424 if request_close is not None:425 request_close()426 clear_request = True427 finally:
1 unmodified line
429430 # get rid of circular dependencies at the end of the request431 # so that we don't require the GC to be active.432 if clear_request:430 rv.request.environ['werkzeug.request'] = None433 rv.request.environ["werkzeug.request"] = None434435 # Get rid of the app as well if necessary.436 if app_ctx is not None:437 app_ctx.pop(exc)438436 assert rv is self, 'Popped wrong request context. ' \437 '(%r instead of %r)' % (rv, self)439 assert (440 rv is self441 ), "Popped wrong request context. " "(%r instead of %r)" % (rv, self)442443 def auto_pop(self, exc):440 if self.request.environ.get('flask._preserve_context') or \441 (exc is not None and self.app.preserve_context_on_exception):444 if self.request.environ.get("flask._preserve_context") or (445 exc is not None and self.app.preserve_context_on_exception446 ):447 self.preserved = True448 self._preserved_exc = exc449 else:450 self.pop(exc)
13 unmodified lines
464 if BROKEN_PYPY_CTXMGR_EXIT and exc_type is not None:465 reraise(exc_type, exc_value, tb)466467 def __repr__(self):463 return '<%s \'%s\' [%s] of %s>' % (468 return "<%s '%s' [%s] of %s>" % (469 self.__class__.__name__,470 self.request.url,471 self.request.method,472 self.app.name,
1 unmodified line
modified:flask/debughelpers.py+65 added-50 removed
30 unmodified lines
31 """3233 def __init__(self, request, key):34 form_matches = request.form.getlist(key)35 buf = ['You tried to access the file "%s" in the request.files '36 'dictionary but it does not exist. The mimetype for the request '37 'is "%s" instead of "multipart/form-data" which means that no '38 'file contents were transmitted. To fix this error you should '39 'provide enctype="multipart/form-data" in your form.' %40 (key, request.mimetype)]35 buf = [36 'You tried to access the file "%s" in the request.files '37 "dictionary but it does not exist. The mimetype for the request "38 'is "%s" instead of "multipart/form-data" which means that no '39 "file contents were transmitted. To fix this error you should "40 'provide enctype="multipart/form-data" in your form.'41 % (key, request.mimetype)42 ]43 if form_matches:42 buf.append('\n\nThe browser instead transmitted some file names. '43 'This was submitted: %s' % ', '.join('"%s"' % x44 for x in form_matches))45 self.msg = ''.join(buf)44 buf.append(45 "\n\nThe browser instead transmitted some file names. "46 "This was submitted: %s" % ", ".join('"%s"' % x for x in form_matches)47 )48 self.msg = "".join(buf)4950 def __str__(self):51 return self.msg52
5 unmodified lines
58 """5960 def __init__(self, request):61 exc = request.routing_exception62 buf = [59 buf = ['A request was sent to this URL (%s) but a redirect was '60 'issued automatically by the routing system to "%s".'61 % (request.url, exc.new_url)]63 "A request was sent to this URL (%s) but a redirect was "64 'issued automatically by the routing system to "%s".'65 % (request.url, exc.new_url)66 ]6768 # In case just a slash was appended we can be extra helpful64 if request.base_url + '/' == exc.new_url.split('?')[0]:65 buf.append(' The URL was defined with a trailing slash so '66 'Flask will automatically redirect to the URL '67 'with the trailing slash if it was accessed '68 'without one.')69 if request.base_url + "/" == exc.new_url.split("?")[0]:70 buf.append(71 " The URL was defined with a trailing slash so "72 "Flask will automatically redirect to the URL "73 "with the trailing slash if it was accessed "74 "without one."75 )7670 buf.append(' Make sure to directly send your %s-request to this URL '71 'since we can\'t make browsers or HTTP clients redirect '72 'with form data reliably or without user interaction.' %73 request.method)74 buf.append('\n\nNote: this exception is only raised in debug mode')75 AssertionError.__init__(self, ''.join(buf).encode('utf-8'))77 buf.append(78 " Make sure to directly send your %s-request to this URL "79 "since we can't make browsers or HTTP clients redirect "80 "with form data reliably or without user interaction." % request.method81 )82 buf.append("\n\nNote: this exception is only raised in debug mode")83 AssertionError.__init__(self, "".join(buf).encode("utf-8"))848586def attach_enctype_error_multidict(request):87 """Since Flask 0.8 we're monkeypatching the files object in case a88 request is detected that does not use multipart form data but the files89 object is accessed.90 """91 oldcls = request.files.__class__9293 class newcls(oldcls):94 def __getitem__(self, key):95 try:96 return oldcls.__getitem__(self, key)97 except KeyError:98 if key not in request.form:99 raise100 raise DebugFilesKeyError(request, key)101102 newcls.__name__ = oldcls.__name__103 newcls.__module__ = oldcls.__module__104 request.files.__class__ = newcls105106107def _dump_loader_info(loader):98 yield 'class: %s.%s' % (type(loader).__module__, type(loader).__name__)108 yield "class: %s.%s" % (type(loader).__module__, type(loader).__name__)109 for key, value in sorted(loader.__dict__.items()):100 if key.startswith('_'):110 if key.startswith("_"):111 continue112 if isinstance(value, (tuple, list)):113 if not all(isinstance(x, (str, text_type)) for x in value):114 continue105 yield '%s:' % key115 yield "%s:" % key116 for item in value:107 yield ' - %s' % item117 yield " - %s" % item118 continue119 elif not isinstance(value, (str, text_type, int, float, bool)):120 continue111 yield '%s: %r' % (key, value)121 yield "%s: %r" % (key, value)122123124def explain_template_loading_attempts(app, template, attempts):125 """This should help developers understand what failed"""
7 unmodified lines
133 for idx, (loader, srcobj, triple) in enumerate(attempts):134 if isinstance(srcobj, Flask):135 src_info = 'application "%s"' % srcobj.import_name136 elif isinstance(srcobj, Blueprint):127 src_info = 'blueprint "%s" (%s)' % (srcobj.name,128 srcobj.import_name)137 src_info = 'blueprint "%s" (%s)' % (srcobj.name, srcobj.import_name)138 else:139 src_info = repr(srcobj)140132 info.append('% 5d: trying loader of %s' % (133 idx + 1, src_info))141 info.append("% 5d: trying loader of %s" % (idx + 1, src_info))142143 for line in _dump_loader_info(loader):136 info.append(' %s' % line)144 info.append(" %s" % line)145146 if triple is None:139 detail = 'no match'147 detail = "no match"148 else:141 detail = 'found (%r)' % (triple[1] or '<string>')149 detail = "found (%r)" % (triple[1] or "<string>")150 total_found += 1143 info.append(' -> %s' % detail)151 info.append(" -> %s" % detail)152153 seems_fishy = False154 if total_found == 0:147 info.append('Error: the template could not be found.')155 info.append("Error: the template could not be found.")156 seems_fishy = True157 elif total_found > 1:150 info.append('Warning: multiple loaders returned a match for the template.')158 info.append("Warning: multiple loaders returned a match for the template.")159 seems_fishy = True160161 if blueprint is not None and seems_fishy:154 info.append(' The template was looked up from an endpoint that '155 'belongs to the blueprint "%s".' % blueprint)156 info.append(' Maybe you did not place a template in the right folder?')157 info.append(' See http://flask.pocoo.org/docs/blueprints/#templates')162 info.append(163 " The template was looked up from an endpoint that "164 'belongs to the blueprint "%s".' % blueprint165 )166 info.append(" Maybe you did not place a template in the right folder?")167 info.append(" See http://flask.pocoo.org/docs/blueprints/#templates")168159 app.logger.info('\n'.join(info))169 app.logger.info("\n".join(info))170171172def explain_ignored_app_run():163 if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':164 warn(Warning('Silently ignoring app.run() because the '165 'application is run from the flask command line '166 'executable. Consider putting app.run() behind an '167 'if __name__ == "__main__" guard to silence this '168 'warning.'), stacklevel=3)173 if os.environ.get("WERKZEUG_RUN_MAIN") != "true":174 warn(175 Warning(176 "Silently ignoring app.run() because the "177 "application is run from the flask command line "178 "executable. Consider putting app.run() behind an "179 'if __name__ == "__main__" guard to silence this '180 "warning."181 ),182 stacklevel=3,183 )
modified:flask/globals.py+7 added-7 removed
12 unmodified lines
13from functools import partial14from werkzeug.local import LocalStack, LocalProxy151617_request_ctx_err_msg = '''\17_request_ctx_err_msg = """\18Working outside of request context.1920This typically means that you attempted to use functionality that needed21an active HTTP request. Consult the documentation on testing for22information about how to avoid this problem.\23'''24_app_ctx_err_msg = '''\23"""24_app_ctx_err_msg = """\25Working outside of application context.2627This typically means that you attempted to use functionality that needed28to interface with the current application object in some way. To solve29this, set up an application context with app.app_context(). See the30documentation for more information.\31'''31"""323334def _lookup_req_object(name):35 top = _request_ctx_stack.top
19 unmodified lines
55# context locals56_request_ctx_stack = LocalStack()57_app_ctx_stack = LocalStack()58current_app = LocalProxy(_find_app)59request = LocalProxy(partial(_lookup_req_object, 'request'))60session = LocalProxy(partial(_lookup_req_object, 'session'))61g = LocalProxy(partial(_lookup_app_object, 'g'))59request = LocalProxy(partial(_lookup_req_object, "request"))60session = LocalProxy(partial(_lookup_req_object, "session"))61g = LocalProxy(partial(_lookup_app_object, "g"))
modified:flask/helpers.py+160 added-129 removed
22 unmodified lines
23from functools import update_wrapper2425from werkzeug.urls import url_quote26from werkzeug.datastructures import Headers, Range27from werkzeug.exceptions import BadRequest, NotFound, \28 RequestedRangeNotSatisfiable27from werkzeug.exceptions import BadRequest, NotFound, RequestedRangeNotSatisfiable2829from werkzeug.wsgi import wrap_file30from jinja2 import FileSystemLoader3132from .signals import message_flashed34from .globals import session, _request_ctx_stack, _app_ctx_stack, \35 current_app, request33from .globals import session, _request_ctx_stack, _app_ctx_stack, current_app, request34from ._compat import string_types, text_type, PY2, fspath3536# sentinel37_missing = object()
1 unmodified line
3940# what separators does this operating system provide that are not a slash?41# this is used by the send_from_directory function to ensure that nobody is42# able to access files from outside the filesystem.45_os_alt_seps = list(sep for sep in [os.path.sep, os.path.altsep]46 if sep not in (None, '/'))43_os_alt_seps = list(44 sep for sep in [os.path.sep, os.path.altsep] if sep not in (None, "/")45)464748def get_env():49 """Get the environment the app is running in, indicated by the50 :envvar:`FLASK_ENV` environment variable. The default is51 ``'production'``.52 """54 return os.environ.get('FLASK_ENV') or 'production'53 return os.environ.get("FLASK_ENV") or "production"545556def get_debug_flag():57 """Get whether debug mode should be enabled for the app, indicated58 by the :envvar:`FLASK_DEBUG` environment variable. The default is59 ``True`` if :func:`.get_env` returns ``'development'``, or ``False``60 otherwise.61 """63 val = os.environ.get('FLASK_DEBUG')62 val = os.environ.get("FLASK_DEBUG")6364 if not val:66 return get_env() == 'development'65 return get_env() == "development"6668 return val.lower() not in ('0', 'false', 'no')67 return val.lower() not in ("0", "false", "no")686970def get_load_dotenv(default=True):71 """Get whether the user has disabled loading dotenv files by setting
1 unmodified line
73 files.7475 :param default: What to return if the env var isn't set.76 """78 val = os.environ.get('FLASK_SKIP_DOTENV')77 val = os.environ.get("FLASK_SKIP_DOTENV")7879 if not val:80 return default8183 return val.lower() in ('0', 'false', 'no')82 return val.lower() in ("0", "false", "no")838485def _endpoint_from_view_func(view_func):86 """Internal helper that returns the default endpoint for a given87 function. This always is the function name.88 """90 assert view_func is not None, 'expected view func if endpoint ' \91 'is not provided.'89 assert view_func is not None, "expected view func if endpoint " "is not provided."90 return view_func.__name__919293def stream_with_context(generator_or_function):
32 unmodified lines
126 """127 try:128 gen = iter(generator_or_function)129 except TypeError:130131 def decorator(*args, **kwargs):132 gen = generator_or_function(*args, **kwargs)133 return stream_with_context(gen)134135 return update_wrapper(decorator, generator_or_function)136137 def generator():138 ctx = _request_ctx_stack.top139 if ctx is None:140 raise RuntimeError('Attempted to stream with context but '141 'there was no context in the first place to keep around.')140 raise RuntimeError(141 "Attempted to stream with context but "142 "there was no context in the first place to keep around."143 )144 with ctx:145 # Dummy sentinel. Has to be inside the context block or we're146 # not actually keeping the context around.147 yield None
5 unmodified lines
153 try:154 for item in gen:155 yield item156 finally:155 if hasattr(gen, 'close'):157 if hasattr(gen, "close"):158 gen.close()159160 # The trick is to start the generator. Then the code execution runs until161 # the first dummy None is yielded at which point the context was already
130 unmodified lines
292 reqctx = _request_ctx_stack.top293294 if appctx is None:295 raise RuntimeError(294 'Attempted to generate a URL without the application context being'295 ' pushed. This has to be executed when application context is'296 ' available.'296 "Attempted to generate a URL without the application context being"297 " pushed. This has to be executed when application context is"298 " available."299 )300301 # If request specific information is available we have some extra302 # features that support "relative" URLs.303 if reqctx is not None:304 url_adapter = reqctx.url_adapter305 blueprint_name = request.blueprint306305 if endpoint[:1] == '.':307 if endpoint[:1] == ".":308 if blueprint_name is not None:309 endpoint = blueprint_name + endpoint310 else:311 endpoint = endpoint[1:]312311 external = values.pop('_external', False)313 external = values.pop("_external", False)314315 # Otherwise go with the url adapter from the appctx and make316 # the URLs external by default.317 else:318 url_adapter = appctx.url_adapter319320 if url_adapter is None:321 raise RuntimeError(320 'Application was not able to create a URL adapter for request'321 ' independent URL generation. You might be able to fix this by'322 ' setting the SERVER_NAME config variable.'322 "Application was not able to create a URL adapter for request"323 " independent URL generation. You might be able to fix this by"324 " setting the SERVER_NAME config variable."325 )326325 external = values.pop('_external', True)327 external = values.pop("_external", True)328327 anchor = values.pop('_anchor', None)328 method = values.pop('_method', None)329 scheme = values.pop('_scheme', None)329 anchor = values.pop("_anchor", None)330 method = values.pop("_method", None)331 scheme = values.pop("_scheme", None)332 appctx.app.inject_url_defaults(endpoint, values)333334 # This is not the best way to deal with this but currently the335 # underlying Werkzeug router does not support overriding the scheme on336 # a per build call basis.337 old_scheme = None338 if scheme is not None:339 if not external:338 raise ValueError('When specifying _scheme, _external must be True')340 raise ValueError("When specifying _scheme, _external must be True")341 old_scheme = url_adapter.url_scheme342 url_adapter.url_scheme = scheme343344 try:345 try:344 rv = url_adapter.build(endpoint, values, method=method,345 force_external=external)346 rv = url_adapter.build(347 endpoint, values, method=method, force_external=external348 )349 finally:350 if old_scheme is not None:351 url_adapter.url_scheme = old_scheme352 except BuildError as error:353 # We need to inject the values again so that the app callback can354 # deal with that sort of stuff.352 values['_external'] = external353 values['_anchor'] = anchor354 values['_method'] = method355 values['_scheme'] = scheme355 values["_external"] = external356 values["_anchor"] = anchor357 values["_method"] = method358 values["_scheme"] = scheme359 return appctx.app.handle_url_build_error(error, endpoint, values)360361 if anchor is not None:359 rv += '#' + url_quote(anchor)362 rv += "#" + url_quote(anchor)363 return rv364365366def get_template_attribute(template_name, attribute):
14 unmodified lines
381382 :param template_name: the name of the template383 :param attribute: the name of the variable of macro to access384 """382 return getattr(current_app.jinja_env.get_template(template_name).module,383 attribute)385 return getattr(current_app.jinja_env.get_template(template_name).module, attribute)386387386def flash(message, category='message'):388def flash(message, category="message"):389 """Flashes a message to the next request. In order to remove the390 flashed message from the session and to display it to the user,391 the template has to call :func:`get_flashed_messages`.392
13 unmodified lines
406 #407 # This assumed that changes made to mutable structures in the session are408 # always in sync with the session object, which is not true for session409 # implementations that use external storage for keeping their keys/values.408 flashes = session.get('_flashes', [])410 flashes = session.get("_flashes", [])411 flashes.append((category, message))410 session['_flashes'] = flashes411 message_flashed.send(current_app._get_current_object(),412 message=message, category=category)412 session["_flashes"] = flashes413 message_flashed.send(414 current_app._get_current_object(), message=message, category=category415 )416417418def get_flashed_messages(with_categories=False, category_filter=[]):419 """Pulls all flashed messages from the session and returns them.
24 unmodified lines
444 :param category_filter: whitelist of categories to limit return values445 """446 flashes = _request_ctx_stack.top.flashes447 if flashes is None:445 _request_ctx_stack.top.flashes = flashes = session.pop('_flashes') \446 if '_flashes' in session else []448 _request_ctx_stack.top.flashes = flashes = (449 session.pop("_flashes") if "_flashes" in session else []450 )451 if category_filter:452 flashes = list(filter(lambda f: f[0] in category_filter, flashes))453 if not with_categories:454 return [x[1] for x in flashes]455 return flashes456457454def send_file(filename_or_fp, mimetype=None, as_attachment=False,455 attachment_filename=None, add_etags=True,456 cache_timeout=None, conditional=False, last_modified=None):458def send_file(459 filename_or_fp,460 mimetype=None,461 as_attachment=False,462 attachment_filename=None,463 add_etags=True,464 cache_timeout=None,465 conditional=False,466 last_modified=None,467):468 """Sends the contents of a file to the client. This will use the469 most efficient method available and configured. By default it will470 try to use the WSGI server's file_wrapper support. Alternatively471 you can set the application's :attr:`~Flask.use_x_sendfile` attribute
83 unmodified lines
555 """556 mtime = None557 fsize = None558548 if hasattr(filename_or_fp, '__fspath__'):559 if hasattr(filename_or_fp, "__fspath__"):560 filename_or_fp = fspath(filename_or_fp)561562 if isinstance(filename_or_fp, string_types):563 filename = filename_or_fp
7 unmodified lines
571 filename = None572573 if mimetype is None:574 if attachment_filename is not None:564 mimetype = mimetypes.guess_type(attachment_filename)[0] \565 or 'application/octet-stream'575 mimetype = (576 mimetypes.guess_type(attachment_filename)[0]577 or "application/octet-stream"578 )579580 if mimetype is None:581 raise ValueError(569 'Unable to infer MIME-type because no filename is available. '570 'Please set either `attachment_filename`, pass a filepath to '571 '`filename_or_fp` or set your own MIME-type via `mimetype`.'582 "Unable to infer MIME-type because no filename is available. "583 "Please set either `attachment_filename`, pass a filepath to "584 "`filename_or_fp` or set your own MIME-type via `mimetype`."585 )586587 headers = Headers()588 if as_attachment:589 if attachment_filename is None:577 raise TypeError('filename unavailable, required for '578 'sending as attachment')590 raise TypeError(591 "filename unavailable, required for " "sending as attachment"592 )593594 if not isinstance(attachment_filename, text_type):581 attachment_filename = attachment_filename.decode('utf-8')595 attachment_filename = attachment_filename.decode("utf-8")596597 try:584 attachment_filename = attachment_filename.encode('ascii')598 attachment_filename = attachment_filename.encode("ascii")599 except UnicodeEncodeError:600 filenames = {587 'filename': unicodedata.normalize(588 'NFKD', attachment_filename).encode('ascii', 'ignore'),589 'filename*': "UTF-8''%s" % url_quote(attachment_filename),601 "filename": unicodedata.normalize("NFKD", attachment_filename).encode(602 "ascii", "ignore"603 ),604 "filename*": "UTF-8''%s" % url_quote(attachment_filename),605 }606 else:592 filenames = {'filename': attachment_filename}607 filenames = {"filename": attachment_filename}608594 headers.add('Content-Disposition', 'attachment', **filenames)609 headers.add("Content-Disposition", "attachment", **filenames)610611 if current_app.use_x_sendfile and filename:612 if file is not None:613 file.close()599 headers['X-Sendfile'] = filename614 headers["X-Sendfile"] = filename615 fsize = os.path.getsize(filename)601 headers['Content-Length'] = fsize616 headers["Content-Length"] = fsize617 data = None618 else:619 if file is None:605 file = open(filename, 'rb')620 file = open(filename, "rb")621 mtime = os.path.getmtime(filename)622 fsize = os.path.getsize(filename)608 headers['Content-Length'] = fsize623 headers["Content-Length"] = fsize624 elif isinstance(file, io.BytesIO):625 try:626 fsize = file.getbuffer().nbytes627 except AttributeError:628 # Python 2 doesn't have getbuffer629 fsize = len(file.getvalue())615 headers['Content-Length'] = fsize630 headers["Content-Length"] = fsize631 data = wrap_file(request.environ, file)632618 rv = current_app.response_class(data, mimetype=mimetype, headers=headers,619 direct_passthrough=True)633 rv = current_app.response_class(634 data, mimetype=mimetype, headers=headers, direct_passthrough=True635 )636637 if last_modified is not None:638 rv.last_modified = last_modified639 elif mtime is not None:
9 unmodified lines
649 if add_etags and filename is not None:650 from warnings import warn651652 try:637 rv.set_etag('%s-%s-%s' % (638 os.path.getmtime(filename),639 os.path.getsize(filename),640 adler32(641 filename.encode('utf-8') if isinstance(filename, text_type)642 else filename643 ) & 0xffffffff644 ))653 rv.set_etag(654 "%s-%s-%s"655 % (656 os.path.getmtime(filename),657 os.path.getsize(filename),658 adler32(659 filename.encode("utf-8")660 if isinstance(filename, text_type)661 else filename662 )663 & 0xFFFFFFFF,664 )665 )666 except OSError:646 warn('Access %s failed, maybe it does not exist, so ignore etags in '647 'headers' % filename, stacklevel=2)667 warn(668 "Access %s failed, maybe it does not exist, so ignore etags in "669 "headers" % filename,670 stacklevel=2,671 )672673 if conditional:674 try:651 rv = rv.make_conditional(request, accept_ranges=True,652 complete_length=fsize)675 rv = rv.make_conditional(request, accept_ranges=True, complete_length=fsize)676 except RequestedRangeNotSatisfiable:677 if file is not None:678 file.close()679 raise680 # make sure we don't send x-sendfile for servers that681 # ignore the 304 status code for x-sendfile.682 if rv.status_code == 304:660 rv.headers.pop('x-sendfile', None)683 rv.headers.pop("x-sendfile", None)684 return rv685686687def safe_join(directory, *pathnames):
16 unmodified lines
704705 parts = [directory]706707 for filename in pathnames:685 if filename != '':708 if filename != "":709 filename = posixpath.normpath(filename)710711 if (712 any(sep in filename for sep in _os_alt_seps)713 or os.path.isabs(filename)691 or filename == '..'692 or filename.startswith('../')714 or filename == ".."715 or filename.startswith("../")716 ):717 raise NotFound()718719 parts.append(filename)
37 unmodified lines
757 if not os.path.isfile(filename):758 raise NotFound()759 except (TypeError, ValueError):760 raise BadRequest()738 options.setdefault('conditional', True)761 options.setdefault("conditional", True)762 return send_file(filename, **options)763764765def get_root_path(import_name):
3 unmodified lines
769 Not to be confused with the package path returned by :func:`find_package`.770 """771 # Module already imported and has a file attribute. Use that first.772 mod = sys.modules.get(import_name)750 if mod is not None and hasattr(mod, '__file__'):773 if mod is not None and hasattr(mod, "__file__"):774 return os.path.dirname(os.path.abspath(mod.__file__))775776 # Next attempt: check the loader.777 loader = pkgutil.get_loader(import_name)778779 # Loader does not exist or we're referring to an unloaded main module780 # or a main module without path (interactive sessions), go with the781 # current working directory.759 if loader is None or import_name == '__main__':782 if loader is None or import_name == "__main__":783 return os.getcwd()784785 # For .egg, zipimporter does not have get_filename until Python 2.7.786 # Some other loaders might exhibit the same behavior.764 if hasattr(loader, 'get_filename'):787 if hasattr(loader, "get_filename"):788 filepath = loader.get_filename(import_name)789 else:790 # Fall back to imports.791 __import__(import_name)792 mod = sys.modules[import_name]770 filepath = getattr(mod, '__file__', None)793 filepath = getattr(mod, "__file__", None)794795 # If we don't have a filepath it might be because we are a796 # namespace package. In this case we pick the root path from the797 # first module that is contained in our package.798 if filepath is None:776 raise RuntimeError('No root path can be found for the provided '777 'module "%s". This can happen because the '778 'module came from an import hook that does '779 'not provide file name information or because '780 'it\'s a namespace package. In this case '781 'the root path needs to be explicitly '782 'provided.' % import_name)799 raise RuntimeError(800 "No root path can be found for the provided "801 'module "%s". This can happen because the '802 "module came from an import hook that does "803 "not provide file name information or because "804 "it's a namespace package. In this case "805 "the root path needs to be explicitly "806 "provided." % import_name807 )808809 # filepath is import_name.py for a module, or __init__.py for a package.810 return os.path.dirname(os.path.abspath(filepath))811
3 unmodified lines
815 attempts to figure out if the given module is actually a package.816 """817 # If the loader can tell us if something is a package, we can818 # directly ask the loader.794 if hasattr(loader, 'is_package'):819 if hasattr(loader, "is_package"):820 return loader.is_package(mod_name)821 # importlib's namespace loaders do not have this functionality but822 # all the modules it loads are packages, so we can take advantage of823 # this information.799 elif (loader.__class__.__module__ == '_frozen_importlib' and800 loader.__class__.__name__ == 'NamespaceLoader'):824 elif (825 loader.__class__.__module__ == "_frozen_importlib"826 and loader.__class__.__name__ == "NamespaceLoader"827 ):828 return True829 # Otherwise we need to fail with an error that explains what went830 # wrong.831 raise AttributeError(805 ('%s.is_package() method is missing but is required by Flask of '806 'PEP 302 import hooks. If you do not use import hooks and '807 'you encounter this error please file a bug against Flask.') %808 loader.__class__.__name__)832 (833 "%s.is_package() method is missing but is required by Flask of "834 "PEP 302 import hooks. If you do not use import hooks and "835 "you encounter this error please file a bug against Flask."836 )837 % loader.__class__.__name__838 )839840841def find_package(import_name):842 """Finds a package and returns the prefix (or None if the package is
2 unmodified lines
845 have to be added to the pythonpath in order to make it possible to846 import the module. The prefix is the path below which a UNIX like847 folder structure exists (lib, share etc.).848 """819 root_mod_name = import_name.split('.')[0]849 root_mod_name = import_name.split(".")[0]850 loader = pkgutil.get_loader(root_mod_name)821 if loader is None or import_name == '__main__':851 if loader is None or import_name == "__main__":852 # import name is not found, or interactive/main module853 package_path = os.getcwd()854 else:855 # For .egg, zipimporter does not have get_filename until Python 2.7.826 if hasattr(loader, 'get_filename'):856 if hasattr(loader, "get_filename"):857 filename = loader.get_filename(root_mod_name)828 elif hasattr(loader, 'archive'):858 elif hasattr(loader, "archive"):859 # zipimporter's loader.archive points to the .egg or .zip860 # archive filename is dropped in call to dirname below.861 filename = loader.archive862 else:
7 unmodified lines
870871 # In case the root module is a package we need to chop of the872 # rightmost part. This needs to go through a helper function873 # because of python 3.3 namespace packages.844 if _matching_loader_thinks_module_is_package(845 loader, root_mod_name):874 if _matching_loader_thinks_module_is_package(loader, root_mod_name):875 package_path = os.path.dirname(package_path)876877 site_parent, site_folder = os.path.split(package_path)878 py_prefix = os.path.abspath(sys.prefix)879 if package_path.startswith(py_prefix):880 return py_prefix, package_path852 elif site_folder.lower() == 'site-packages':881 elif site_folder.lower() == "site-packages":882 parent, folder = os.path.split(site_parent)883 # Windows like installations855 if folder.lower() == 'lib':884 if folder.lower() == "lib":885 base_dir = parent886 # UNIX like installations858 elif os.path.basename(parent).lower() == 'lib':887 elif os.path.basename(parent).lower() == "lib":888 base_dir = os.path.dirname(parent)889 else:890 base_dir = site_parent891 return base_dir, package_path
57 unmodified lines
949 def _set_static_folder(self, value):950 self._static_folder = value951952 static_folder = property(924 _get_static_folder, _set_static_folder,925 doc='The absolute path to the configured static folder.'953 _get_static_folder,954 _set_static_folder,955 doc="The absolute path to the configured static folder.",956 )957 del _get_static_folder, _set_static_folder958959 def _get_static_url_path(self):960 if self._static_url_path is not None:961 return self._static_url_path962963 if self.static_folder is not None:934 return '/' + os.path.basename(self.static_folder)964 return "/" + os.path.basename(self.static_folder)965966 def _set_static_url_path(self, value):967 self._static_url_path = value968969 static_url_path = property(940 _get_static_url_path, _set_static_url_path,941 doc='The URL prefix that the static route will be registered for.'970 _get_static_url_path,971 _set_static_url_path,972 doc="The URL prefix that the static route will be registered for.",973 )974 del _get_static_url_path, _set_static_url_path975976 @property
11 unmodified lines
988989 .. versionadded:: 0.5990 """991 if self.template_folder is not None:961 return FileSystemLoader(os.path.join(self.root_path,962 self.template_folder))992 return FileSystemLoader(os.path.join(self.root_path, self.template_folder))993994 def get_send_file_max_age(self, filename):995 """Provides default cache_timeout for the :func:`send_file` functions.996
26 unmodified lines
10231024 .. versionadded:: 0.51025 """1026 if not self.has_static_folder:997 raise RuntimeError('No static folder for this object')1027 raise RuntimeError("No static folder for this object")1028 # Ensure get_send_file_max_age is called in all cases.1029 # Here, we ensure get_send_file_max_age is called for Blueprints.1030 cache_timeout = self.get_send_file_max_age(filename)1001 return send_from_directory(self.static_folder, filename,1002 cache_timeout=cache_timeout)1031 return send_from_directory(1032 self.static_folder, filename, cache_timeout=cache_timeout1033 )10341004 def open_resource(self, resource, mode='rb'):1035 def open_resource(self, resource, mode="rb"):1036 """Opens a resource from the application's resource folder. To see1037 how this works, consider the following folder structure::10381039 /myapplication.py
14 unmodified lines
1054 :param resource: the name of the resource. To access resources within1055 subfolders use forward slashes as separator.1056 :param mode: resource file opening mode, default is 'rb'.1057 """1027 if mode not in ('r', 'rb'):1028 raise ValueError('Resources can only be opened for reading')1058 if mode not in ("r", "rb"):1059 raise ValueError("Resources can only be opened for reading")1060 return open(os.path.join(self.root_path, resource), mode)106110621063def total_seconds(td):
18 unmodified lines
10821083 :return: True if string is an IP address1084 :rtype: bool1085 """1055 if PY2 and os.name == 'nt':1086 if PY2 and os.name == "nt":1087 try:1088 socket.inet_aton(value)1089 return True1090 except socket.error:
11 unmodified lines
modified:flask/logging.py+5 added-5 removed
25 unmodified lines
26 use this for the stream. If you are using file or dict configuration and27 can't import this directly, you can refer to it as28 ``ext://flask.logging.wsgi_errors_stream``.29 """30 return request.environ['wsgi.errors'] if request else sys.stderr30 return request.environ["wsgi.errors"] if request else sys.stderr313233def has_level_handler(logger):34 """Check if there is a handler in the logging chain that will handle the
16 unmodified lines
5152#: Log messages to :func:`~flask.logging.wsgi_errors_stream` with the format53#: ``[%(asctime)s] %(levelname)s in %(module)s: %(message)s``.54default_handler = logging.StreamHandler(wsgi_errors_stream)55default_handler.setFormatter(logging.Formatter(56 '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'57))55default_handler.setFormatter(56 logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s")57)585960def create_logger(app):61 """Get the ``'flask.app'`` logger and configure it if needed.
4 unmodified lines
66 If there is no handler for the logger's effective level, add a67 :class:`~logging.StreamHandler` for68 :func:`~flask.logging.wsgi_errors_stream` with a basic format.69 """70 logger = logging.getLogger('flask.app')70 logger = logging.getLogger("flask.app")7172 if app.debug and logger.level == logging.NOTSET:73 logger.setLevel(logging.DEBUG)74
4 unmodified lines
modified:flask/sessions.py+40 added-38 removed
25 unmodified lines
2627 @property28 def permanent(self):29 """This reflects the ``'_permanent'`` key in the dict."""30 return self.get('_permanent', False)30 return self.get("_permanent", False)3132 @permanent.setter33 def permanent(self, value):34 self['_permanent'] = bool(value)34 self["_permanent"] = bool(value)3536 #: Some implementations can detect whether a session is newly37 #: created, but that is not guaranteed. Use with caution. The mixin38 # default is hard-coded ``False``.
58 unmodified lines
97 but fail on setting.98 """99100 def _fail(self, *args, **kwargs):101 raise RuntimeError('The session is unavailable because no secret '102 'key was set. Set the secret_key on the '103 'application to something unique and secret.')104 __setitem__ = __delitem__ = clear = pop = popitem = \105 update = setdefault = _fail101 raise RuntimeError(102 "The session is unavailable because no secret "103 "key was set. Set the secret_key on the "104 "application to something unique and secret."105 )106107 __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail108 del _fail109110111class SessionInterface(object):
69 unmodified lines
181 Once detected (or if not set at all), ``SESSION_COOKIE_DOMAIN`` is182 updated to avoid re-running the logic.183 """184183 rv = app.config['SESSION_COOKIE_DOMAIN']185 rv = app.config["SESSION_COOKIE_DOMAIN"]186187 # set explicitly, or cached from SERVER_NAME detection188 # if False, return None189 if rv is not None:190 return rv if rv else None191190 rv = app.config['SERVER_NAME']192 rv = app.config["SERVER_NAME"]193194 # server name not set, cache False to return none next time195 if not rv:194 app.config['SESSION_COOKIE_DOMAIN'] = False196 app.config["SESSION_COOKIE_DOMAIN"] = False197 return None198199 # chop off the port which is usually not supported by browsers200 # remove any leading '.' since we'll add that later199 rv = rv.rsplit(':', 1)[0].lstrip('.')201 rv = rv.rsplit(":", 1)[0].lstrip(".")202201 if '.' not in rv:203 if "." not in rv:204 # Chrome doesn't allow names without a '.'205 # this should only come up with localhost206 # hack around this by not setting the name, and show a warning207 warnings.warn(208 '"{rv}" is not a valid cookie domain, it must contain a ".".'207 ' Add an entry to your hosts file, for example'209 " Add an entry to your hosts file, for example"210 ' "{rv}.localdomain", and use that instead.'.format(rv=rv)211 )210 app.config['SESSION_COOKIE_DOMAIN'] = False212 app.config["SESSION_COOKIE_DOMAIN"] = False213 return None214215 ip = is_ip(rv)216217 if ip:218 warnings.warn(217 'The session cookie domain is an IP address. This may not work'218 ' as intended in some browsers. Add an entry to your hosts'219 "The session cookie domain is an IP address. This may not work"220 " as intended in some browsers. Add an entry to your hosts"221 ' file, for example "localhost.localdomain", and use that'220 ' instead.'222 " instead."223 )224225 # if this is not an ip and app is mounted at the root, allow subdomain226 # matching by adding a '.' prefix225 if self.get_cookie_path(app) == '/' and not ip:226 rv = '.' + rv227 if self.get_cookie_path(app) == "/" and not ip:228 rv = "." + rv229228 app.config['SESSION_COOKIE_DOMAIN'] = rv230 app.config["SESSION_COOKIE_DOMAIN"] = rv231 return rv232233 def get_cookie_path(self, app):234 """Returns the path for which the cookie should be valid. The235 default implementation uses the value from the ``SESSION_COOKIE_PATH``236 config var if it's set, and falls back to ``APPLICATION_ROOT`` or237 uses ``/`` if it's ``None``.238 """237 return app.config['SESSION_COOKIE_PATH'] \238 or app.config['APPLICATION_ROOT']239 return app.config["SESSION_COOKIE_PATH"] or app.config["APPLICATION_ROOT"]240241 def get_cookie_httponly(self, app):242 """Returns True if the session cookie should be httponly. This243 currently just returns the value of the ``SESSION_COOKIE_HTTPONLY``244 config var.245 """245 return app.config['SESSION_COOKIE_HTTPONLY']246 return app.config["SESSION_COOKIE_HTTPONLY"]247248 def get_cookie_secure(self, app):249 """Returns True if the cookie should be secure. This currently250 just returns the value of the ``SESSION_COOKIE_SECURE`` setting.251 """251 return app.config['SESSION_COOKIE_SECURE']252 return app.config["SESSION_COOKIE_SECURE"]253254 def get_cookie_samesite(self, app):255 """Return ``'Strict'`` or ``'Lax'`` if the cookie should use the256 ``SameSite`` attribute. This currently just returns the value of257 the :data:`SESSION_COOKIE_SAMESITE` setting.258 """258 return app.config['SESSION_COOKIE_SAMESITE']259 return app.config["SESSION_COOKIE_SAMESITE"]260261 def get_expiration_time(self, app, session):262 """A helper method that returns an expiration date for the session263 or ``None`` if the session is linked to the browser session. The
15 unmodified lines
279 .. versionadded:: 0.11280 """281282 return session.modified or (282 session.permanent and app.config['SESSION_REFRESH_EACH_REQUEST']283 session.permanent and app.config["SESSION_REFRESH_EACH_REQUEST"]284 )285286 def open_session(self, app, request):287 """This method has to be implemented and must either return ``None``
18 unmodified lines
306class SecureCookieSessionInterface(SessionInterface):307 """The default session interface that stores sessions in signed cookies308 through the :mod:`itsdangerous` module.309 """310311 #: the salt that should be applied on top of the secret key for the312 #: signing of cookie based sessions.311 salt = 'cookie-session'313 salt = "cookie-session"314 #: the hash function to use for the signature. The default is sha1315 digest_method = staticmethod(hashlib.sha1)316 #: the name of the itsdangerous supported key derivation. The default317 #: is hmac.316 key_derivation = 'hmac'318 key_derivation = "hmac"319 #: A python serializer for the payload. The default is a compact320 #: JSON derived serializer with support for some extra Python types321 #: such as datetime objects or tuples.322 serializer = session_json_serializer
2 unmodified lines
325 def get_signing_serializer(self, app):326 if not app.secret_key:327 return None328 signer_kwargs = dict(327 key_derivation=self.key_derivation,328 digest_method=self.digest_method329 key_derivation=self.key_derivation, digest_method=self.digest_method330 )331 return URLSafeTimedSerializer(332 app.secret_key,330 return URLSafeTimedSerializer(app.secret_key, salt=self.salt,331 serializer=self.serializer,332 signer_kwargs=signer_kwargs)333 salt=self.salt,334 serializer=self.serializer,335 signer_kwargs=signer_kwargs,336 )337338 def open_session(self, app, request):339 s = self.get_signing_serializer(app)340 if s is None:
16 unmodified lines
357 # If the session is empty, return without setting the cookie.358 if not session:359 if session.modified:360 response.delete_cookie(357 app.session_cookie_name,358 domain=domain,359 path=path361 app.session_cookie_name, domain=domain, path=path362 )363364 return365366 # Add a "Vary: Cookie" header if the session was accessed at all.367 if session.accessed:366 response.vary.add('Cookie')368 response.vary.add("Cookie")369370 if not self.should_set_cookie(app, session):371 return372
9 unmodified lines
382 httponly=httponly,383 domain=domain,384 path=path,385 secure=secure,384 samesite=samesite386 samesite=samesite,387 )
modified:flask/signals.py+25 added-15 removed
11 unmodified lines
1213signals_available = False14try:15 from blinker import Namespace1617 signals_available = True18except ImportError:1920 class Namespace(object):21 def signal(self, name, doc=None):22 return _FakeSignal(name, doc)23
6 unmodified lines
3031 def __init__(self, name, doc=None):32 self.name = name33 self.__doc__ = doc3435 def _fail(self, *args, **kwargs):33 raise RuntimeError('signalling support is unavailable '34 'because the blinker library is '35 'not installed.')36 raise RuntimeError(37 "signalling support is unavailable "38 "because the blinker library is "39 "not installed."40 )4142 send = lambda *a, **kw: None37 connect = disconnect = has_receivers_for = receivers_for = \38 temporarily_connected_to = connected_to = _fail43 connect = (44 disconnect45 ) = (46 has_receivers_for47 ) = receivers_for = temporarily_connected_to = connected_to = _fail48 del _fail495051# The namespace for code signals. If you are not Flask code, do52# not put signals in here. Create your own namespace instead.53_signals = Namespace()545556# Core signals. For usage examples grep the source code or consult57# the API documentation in docs/api.rst as well as docs/signals.rst48template_rendered = _signals.signal('template-rendered')49before_render_template = _signals.signal('before-render-template')50request_started = _signals.signal('request-started')51request_finished = _signals.signal('request-finished')52request_tearing_down = _signals.signal('request-tearing-down')53got_request_exception = _signals.signal('got-request-exception')54appcontext_tearing_down = _signals.signal('appcontext-tearing-down')55appcontext_pushed = _signals.signal('appcontext-pushed')56appcontext_popped = _signals.signal('appcontext-popped')57message_flashed = _signals.signal('message-flashed')58template_rendered = _signals.signal("template-rendered")59before_render_template = _signals.signal("before-render-template")60request_started = _signals.signal("request-started")61request_finished = _signals.signal("request-finished")62request_tearing_down = _signals.signal("request-tearing-down")63got_request_exception = _signals.signal("got-request-exception")64appcontext_tearing_down = _signals.signal("appcontext-tearing-down")65appcontext_pushed = _signals.signal("appcontext-pushed")66appcontext_popped = _signals.signal("appcontext-popped")67message_flashed = _signals.signal("message-flashed")
modified:flask/templating.py+14 added-12 removed
7 unmodified lines
8 :copyright: © 2010 by the Pallets team.9 :license: BSD, see LICENSE for more details.10"""1112from jinja2 import BaseLoader, Environment as BaseEnvironment, \13 TemplateNotFound12from jinja2 import BaseLoader, Environment as BaseEnvironment, TemplateNotFound1314from .globals import _request_ctx_stack, _app_ctx_stack15from .signals import template_rendered, before_render_template16
5 unmodified lines
22 reqctx = _request_ctx_stack.top23 appctx = _app_ctx_stack.top24 rv = {}25 if appctx is not None:27 rv['g'] = appctx.g26 rv["g"] = appctx.g27 if reqctx is not None:29 rv['request'] = reqctx.request30 rv['session'] = reqctx.session28 rv["request"] = reqctx.request29 rv["session"] = reqctx.session30 return rv313233class Environment(BaseEnvironment):
2 unmodified lines
36 name of the blueprint to referenced templates if necessary.37 """3839 def __init__(self, app, **options):41 if 'loader' not in options:42 options['loader'] = app.create_global_jinja_loader()40 if "loader" not in options:41 options["loader"] = app.create_global_jinja_loader()42 BaseEnvironment.__init__(self, **options)43 self.app = app4445
5 unmodified lines
51 def __init__(self, app):52 self.app = app5354 def get_source(self, environment, template):56 if self.app.config['EXPLAIN_TEMPLATE_LOADING']:55 if self.app.config["EXPLAIN_TEMPLATE_LOADING"]:56 return self._get_source_explained(environment, template)57 return self._get_source_fast(environment, template)5859 def _get_source_explained(self, environment, template):
9 unmodified lines
69 rv = None70 attempts.append((loader, srcobj, rv))7172 from .debughelpers import explain_template_loading_attempts7374 explain_template_loading_attempts(self.app, template, attempts)7576 if trv is not None:77 return trv
52 unmodified lines
130 context of the template.131 """132 ctx = _app_ctx_stack.top133 ctx.app.update_template_context(context)134 return _render(134 return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list),135 context, ctx.app)135 ctx.app.jinja_env.get_or_select_template(template_name_or_list),136 context,137 ctx.app,138 )139140141def render_template_string(source, **context):142 """Renders a template from the given template source string
5 unmodified lines
148 context of the template.149 """150 ctx = _app_ctx_stack.top151 ctx.app.update_template_context(context)149 return _render(ctx.app.jinja_env.from_string(source),150 context, ctx.app)152 return _render(ctx.app.jinja_env.from_string(source), context, ctx.app)
modified:flask/testing.py+41 added-41 removed
20 unmodified lines
21from werkzeug.urls import url_parse222324def make_test_environ_builder(25 app, path='/', base_url=None, subdomain=None, url_scheme=None,26 *args, **kwargs25 app, path="/", base_url=None, subdomain=None, url_scheme=None, *args, **kwargs26):27 """Create a :class:`~werkzeug.test.EnvironBuilder`, taking some28 defaults from the application.29
14 unmodified lines
44 :param kwargs: other keyword arguments passed to45 :class:`~werkzeug.test.EnvironBuilder`.46 """4749 assert (50 not (base_url or subdomain or url_scheme)51 or (base_url is not None) != bool(subdomain or url_scheme)48 assert not (base_url or subdomain or url_scheme) or (base_url is not None) != bool(49 subdomain or url_scheme50 ), 'Cannot pass "subdomain" or "url_scheme" with "base_url".'5152 if base_url is None:55 http_host = app.config.get('SERVER_NAME') or 'localhost'56 app_root = app.config['APPLICATION_ROOT']53 http_host = app.config.get("SERVER_NAME") or "localhost"54 app_root = app.config["APPLICATION_ROOT"]5556 if subdomain:59 http_host = '{0}.{1}'.format(subdomain, http_host)57 http_host = "{0}.{1}".format(subdomain, http_host)5859 if url_scheme is None:62 url_scheme = app.config['PREFERRED_URL_SCHEME']60 url_scheme = app.config["PREFERRED_URL_SCHEME"]6162 url = url_parse(path)65 base_url = '{scheme}://{netloc}/{path}'.format(63 base_url = "{scheme}://{netloc}/{path}".format(64 scheme=url.scheme or url_scheme,65 netloc=url.netloc or http_host,68 path=app_root.lstrip('/')66 path=app_root.lstrip("/"),67 )68 path = url.path6970 if url.query:73 sep = b'?' if isinstance(url.query, bytes) else '?'71 sep = b"?" if isinstance(url.query, bytes) else "?"72 path += sep + url.query7376 if 'json' in kwargs:77 assert 'data' not in kwargs, (78 "Client cannot provide both 'json' and 'data'."79 )74 if "json" in kwargs:75 assert "data" not in kwargs, "Client cannot provide both 'json' and 'data'."7677 # push a context so flask.json can use app's json attributes78 with app.app_context():83 kwargs['data'] = json_dumps(kwargs.pop('json'))79 kwargs["data"] = json_dumps(kwargs.pop("json"))8085 if 'content_type' not in kwargs:86 kwargs['content_type'] = 'application/json'81 if "content_type" not in kwargs:82 kwargs["content_type"] = "application/json"8384 return EnvironBuilder(path, base_url, *args, **kwargs)8586
17 unmodified lines
104 def __init__(self, *args, **kwargs):105 super(FlaskClient, self).__init__(*args, **kwargs)106 self.environ_base = {107 "REMOTE_ADDR": "127.0.0.1",112 "HTTP_USER_AGENT": "werkzeug/" + werkzeug.__version__108 "HTTP_USER_AGENT": "werkzeug/" + werkzeug.__version__,109 }110111 @contextmanager112 def session_transaction(self, *args, **kwargs):
13 unmodified lines
126 :meth:`~flask.Flask.test_request_context` which are directly127 passed through.128 """129 if self.cookie_jar is None:134 raise RuntimeError('Session transactions only make sense '135 'with cookies enabled.')130 raise RuntimeError(131 "Session transactions only make sense " "with cookies enabled."132 )133 app = self.application137 environ_overrides = kwargs.setdefault('environ_overrides', {})134 environ_overrides = kwargs.setdefault("environ_overrides", {})135 self.cookie_jar.inject_wsgi(environ_overrides)136 outer_reqctx = _request_ctx_stack.top137 with app.test_request_context(*args, **kwargs) as c:138 session_interface = app.session_interface139 sess = session_interface.open_session(app, c.request)140 if sess is None:144 raise RuntimeError('Session backend did not open a session. '145 'Check the configuration')141 raise RuntimeError(142 "Session backend did not open a session. " "Check the configuration"143 )144145 # Since we have to open a new request context for the session146 # handling we want to make sure that we hide out own context147 # from the caller. By pushing the original request context
13 unmodified lines
161 headers = resp.get_wsgi_headers(c.request.environ)162 self.cookie_jar.extract_wsgi(c.request.environ, headers)163164 def open(self, *args, **kwargs):167 as_tuple = kwargs.pop('as_tuple', False)168 buffered = kwargs.pop('buffered', False)169 follow_redirects = kwargs.pop('follow_redirects', False)165 as_tuple = kwargs.pop("as_tuple", False)166 buffered = kwargs.pop("buffered", False)167 follow_redirects = kwargs.pop("follow_redirects", False)168169 if (172 not kwargs and len(args) == 1170 not kwargs171 and len(args) == 1172 and isinstance(args[0], (EnvironBuilder, dict))173 ):174 environ = self.environ_base.copy()175
1 unmodified line
177 environ.update(args[0].get_environ())178 else:179 environ.update(args[0])180182 environ['flask._preserve_context'] = self.preserve_context181 environ["flask._preserve_context"] = self.preserve_context182 else:184 kwargs.setdefault('environ_overrides', {}) \185 ['flask._preserve_context'] = self.preserve_context186 kwargs.setdefault('environ_base', self.environ_base)187 builder = make_test_environ_builder(188 self.application, *args, **kwargs189 )183 kwargs.setdefault("environ_overrides", {})[184 "flask._preserve_context"185 ] = self.preserve_context186 kwargs.setdefault("environ_base", self.environ_base)187 builder = make_test_environ_builder(self.application, *args, **kwargs)188189 try:190 environ = builder.get_environ()191 finally:192 builder.close()193194 return Client.open(197 self, environ,195 self,196 environ,197 as_tuple=as_tuple,198 buffered=buffered,200 follow_redirects=follow_redirects199 follow_redirects=follow_redirects,200 )201202 def __enter__(self):203 if self.preserve_context:205 raise RuntimeError('Cannot nest client invocations')204 raise RuntimeError("Cannot nest client invocations")205 self.preserve_context = True206 return self207208 def __exit__(self, exc_type, exc_value, tb):
11 unmodified lines
220 """A :class:`~click.testing.CliRunner` for testing a Flask app's221 CLI commands. Typically created using222 :meth:`~flask.Flask.test_cli_runner`. See :ref:`testing-cli`.223 """224225 def __init__(self, app, **kwargs):226 self.app = app227 super(FlaskCliRunner, self).__init__(**kwargs)228
14 unmodified lines
243 """244 if cli is None:245 cli = self.app.cli246247 if 'obj' not in kwargs:248 kwargs['obj'] = ScriptInfo(create_app=lambda: self.app)247 if "obj" not in kwargs:248 kwargs["obj"] = ScriptInfo(create_app=lambda: self.app)249250 return super(FlaskCliRunner, self).invoke(cli, args, **kwargs)
modified:flask/views.py+8 added-6 removed
11 unmodified lines
12from .globals import request13from ._compat import with_metaclass141516http_method_funcs = frozenset(['get', 'post', 'head', 'options',17 'delete', 'put', 'trace', 'patch'])16http_method_funcs = frozenset(17 ["get", "post", "head", "options", "delete", "put", "trace", "patch"]18)192021class View(object):22 """Alternative way to use view functions. A subclass has to implement
60 unmodified lines
8384 The arguments passed to :meth:`as_view` are forwarded to the85 constructor of the class.86 """8788 def view(*args, **kwargs):89 self = view.view_class(*class_args, **class_kwargs)90 return self.dispatch_request(*args, **kwargs)91
24 unmodified lines
116117 def __init__(cls, name, bases, d):118 super(MethodViewType, cls).__init__(name, bases, d)119118 if 'methods' not in d:120 if "methods" not in d:121 methods = set()122123 for key in http_method_funcs:124 if hasattr(cls, key):
27 unmodified lines
152 meth = getattr(self, request.method.lower(), None)153154 # If the request method is HEAD and we don't have a handler for it155 # retry with GET.154 if meth is None and request.method == 'HEAD':155 meth = getattr(self, 'get', None)156 if meth is None and request.method == "HEAD":157 meth = getattr(self, "get", None)158157 assert meth is not None, 'Unimplemented method %r' % request.method159 assert meth is not None, "Unimplemented method %r" % request.method160 return meth(*args, **kwargs)
modified:flask/wrappers.py+11 added-9 removed
32 unmodified lines
33 .. versionadded:: 0.1134 """35 mt = self.mimetype36 return (37 mt == 'application/json'38 or (mt.startswith('application/')) and mt.endswith('+json')37 mt == "application/json"38 or (mt.startswith("application/"))39 and mt.endswith("+json")40 )4142 @property43 def json(self):
59 unmodified lines
103104 .. versionadded:: 0.8105 """106 if current_app is not None and current_app.debug:106 raise BadRequest('Failed to decode JSON object: {0}'.format(e))107 raise BadRequest("Failed to decode JSON object: {0}".format(e))108109 raise BadRequest()110111
34 unmodified lines
146 @property147 def max_content_length(self):148 """Read-only view of the ``MAX_CONTENT_LENGTH`` config key."""149 if current_app:149 return current_app.config['MAX_CONTENT_LENGTH']150 return current_app.config["MAX_CONTENT_LENGTH"]151152 @property153 def endpoint(self):154 """The endpoint that matched the request. This in combination with
6 unmodified lines
161162 @property163 def blueprint(self):164 """The name of the current blueprint"""164 if self.url_rule and '.' in self.url_rule.endpoint:165 return self.url_rule.endpoint.rsplit('.', 1)[0]165 if self.url_rule and "." in self.url_rule.endpoint:166 return self.url_rule.endpoint.rsplit(".", 1)[0]167168 def _load_form_data(self):169 RequestBase._load_form_data(self)170
1 unmodified line
172 # subclass that raises a different error for key errors.173 if (174 current_app175 and current_app.debug175 and self.mimetype != 'multipart/form-data'176 and self.mimetype != "multipart/form-data"177 and not self.files178 ):179 from .debughelpers import attach_enctype_error_multidict180181 attach_enctype_error_multidict(self)182183184class Response(ResponseBase, JSONMixin):
13 unmodified lines
198199 Added :attr:`max_cookie_size`.200 """201200 default_mimetype = 'text/html'202 default_mimetype = "text/html"203204 def _get_data_for_json(self, cache):205 return self.get_data()206
4 unmodified lines
211 See :attr:`~werkzeug.wrappers.BaseResponse.max_cookie_size` in212 Werkzeug's docs.213 """214 if current_app:213 return current_app.config['MAX_COOKIE_SIZE']215 return current_app.config["MAX_COOKIE_SIZE"]216217 # return Werkzeug's default when not in an app context218 return super(Response, self).max_cookie_size
modified:scripts/make-release.py+36 added-38 removed
5 unmodified lines
6import sys7from datetime import date, datetime8from subprocess import PIPE, Popen910_date_strip_re = re.compile(r'(?<=\d)(st|nd|rd|th)')10_date_strip_re = re.compile(r"(?<=\d)(st|nd|rd|th)")111213def parse_changelog():14 with open('CHANGES.rst') as f:14 with open("CHANGES.rst") as f:15 lineiter = iter(f)16 for line in lineiter:17 match = re.search('^Version\s+(.*)', line.strip())17 match = re.search("^Version\s+(.*)", line.strip())1819 if match is None:20 continue2122 version = match.group(1).strip()2324 if next(lineiter).count('-') != len(match.group(0)):24 if next(lineiter).count("-") != len(match.group(0)):25 continue2627 while 1:28 change_info = next(lineiter).strip()
1 unmodified line
30 if change_info:31 break3233 match = re.search(34 r'released on (\w+\s+\d+\w+\s+\d+)(?:, codename (.*))?',34 r"released on (\w+\s+\d+\w+\s+\d+)(?:, codename (.*))?",35 change_info,36 flags=re.IGNORECASE36 flags=re.IGNORECASE,37 )3839 if match is None:40 continue
3 unmodified lines
444546def bump_version(version):47 try:48 parts = [int(i) for i in version.split('.')]48 parts = [int(i) for i in version.split(".")]49 except ValueError:50 fail('Current version is not numeric')50 fail("Current version is not numeric")5152 parts[-1] += 153 return '.'.join(map(str, parts))53 return ".".join(map(str, parts))545556def parse_date(string):57 string = _date_strip_re.sub('', string)58 return datetime.strptime(string, '%B %d %Y')57 string = _date_strip_re.sub("", string)58 return datetime.strptime(string, "%B %d %Y")596061def set_filename_version(filename, version_number, pattern):62 changed = []
5 unmodified lines
6869 with open(filename) as f:70 contents = re.sub(71 r"^(\s*%s\s*=\s*')(.+?)(')" % pattern,72 inject_version, f.read(),73 flags=re.DOTALL | re.MULTILINE72 inject_version,73 f.read(),74 flags=re.DOTALL | re.MULTILINE,75 )7677 if not changed:77 fail('Could not find %s in %s', pattern, filename)78 fail("Could not find %s in %s", pattern, filename)7979 with open(filename, 'w') as f:80 with open(filename, "w") as f:81 f.write(contents)828384def set_init_version(version):84 info('Setting __init__.py version to %s', version)85 set_filename_version('flask/__init__.py', version, '__version__')85 info("Setting __init__.py version to %s", version)86 set_filename_version("flask/__init__.py", version, "__version__")878889def build():89 cmd = [sys.executable, 'setup.py', 'sdist', 'bdist_wheel']90 cmd = [sys.executable, "setup.py", "sdist", "bdist_wheel"]91 Popen(cmd).wait()929394def fail(message, *args):94 print('Error:', message % args, file=sys.stderr)95 print("Error:", message % args, file=sys.stderr)96 sys.exit(1)979899def info(message, *args):100 print(message % args, file=sys.stderr)101102103def get_git_tags():103 return set(104 Popen(['git', 'tag'], stdout=PIPE).communicate()[0].splitlines()105 )104 return set(Popen(["git", "tag"], stdout=PIPE).communicate()[0].splitlines())105106107def git_is_clean():109 return Popen(['git', 'diff', '--quiet']).wait() == 0108 return Popen(["git", "diff", "--quiet"]).wait() == 0109110111def make_git_commit(message, *args):112 message = message % args114 Popen(['git', 'commit', '-am', message]).wait()113 Popen(["git", "commit", "-am", message]).wait()114115116def make_git_tag(tag):117 info('Tagging "%s"', tag)119 Popen(['git', 'tag', tag]).wait()118 Popen(["git", "tag", tag]).wait()119120121def main():123 os.chdir(os.path.join(os.path.dirname(__file__), '..'))122 os.chdir(os.path.join(os.path.dirname(__file__), ".."))123124 rv = parse_changelog()125126 if rv is None:128 fail('Could not parse changelog')127 fail("Could not parse changelog")128129 version, release_date, codename = rv131 dev_version = bump_version(version) + '.dev'130 dev_version = bump_version(version) + ".dev"131132 info(134 'Releasing %s (codename %s, release date %s)',135 version, codename, release_date.strftime('%d/%m/%Y')133 "Releasing %s (codename %s, release date %s)",134 version,135 codename,136 release_date.strftime("%d/%m/%Y"),137 )138 tags = get_git_tags()139140 if version in tags:141 fail('Version "%s" is already tagged', version)142143 if release_date.date() != date.today():143 fail(144 'Release date is not today (%s != %s)',145 release_date.date(), date.today()146 )144 fail("Release date is not today (%s != %s)", release_date.date(), date.today())145146 if not git_is_clean():149 fail('You have uncommitted changes in git')147 fail("You have uncommitted changes in git")148149 try:150 import wheel # noqa: F401151 except ImportError:154 fail('You need to install the wheel package.')152 fail("You need to install the wheel package.")153154 set_init_version(version)157 make_git_commit('Bump version number to %s', version)155 make_git_commit("Bump version number to %s", version)156 make_git_tag(version)157 build()158 set_init_version(dev_version)159160163if __name__ == '__main__':161if __name__ == "__main__":162 main()
modified:tests/test_apps/blueprintapp/apps/admin/__init__.py+11 added-7 removed
1from flask import Blueprint, render_template23admin = Blueprint('admin', __name__, url_prefix='/admin',4 template_folder='templates',5 static_folder='static')3admin = Blueprint(4 "admin",5 __name__,6 url_prefix="/admin",7 template_folder="templates",8 static_folder="static",9)10118@admin.route('/')12@admin.route("/")13def index():10 return render_template('admin/index.html')14 return render_template("admin/index.html")151613@admin.route('/index2')17@admin.route("/index2")18def index2():15 return render_template('./admin/index.html')19 return render_template("./admin/index.html")
modified:tests/test_apps/blueprintapp/apps/frontend/__init__.py+5 added-5 removed
1from flask import Blueprint, render_template23frontend = Blueprint('frontend', __name__, template_folder='templates')3frontend = Blueprint("frontend", __name__, template_folder="templates")456@frontend.route('/')6@frontend.route("/")7def index():8 return render_template('frontend/index.html')8 return render_template("frontend/index.html")91011@frontend.route('/missing')11@frontend.route("/missing")12def missing_template():13 return render_template('missing_template.html')13 return render_template("missing_template.html")
modified:tests/test_apps/blueprintapp/__init__.py+2 added-1 removed
1from flask import Flask23app = Flask(__name__)4app.config['DEBUG'] = True4app.config["DEBUG"] = True5from blueprintapp.apps.admin import admin6from blueprintapp.apps.frontend import frontend78app.register_blueprint(admin)9app.register_blueprint(frontend)
modified:tests/test_apps/cliapp/app.py+1 added-1 removed
1from __future__ import absolute_import, print_function23from flask import Flask45testapp = Flask('testapp')5testapp = Flask("testapp")
modified:tests/test_apps/cliapp/factory.py+3 added-3 removed
2 unmodified lines
3from flask import Flask456def create_app():7 return Flask('app')7 return Flask("app")8910def create_app2(foo, bar):11 return Flask('_'.join(['app2', foo, bar]))11 return Flask("_".join(["app2", foo, bar]))121314def create_app3(foo, script_info):15 return Flask('_'.join(['app3', foo, script_info.data['test']]))15 return Flask("_".join(["app3", foo, script_info.data["test"]]))161718def no_app():19 pass
modified:tests/test_apps/cliapp/importerrorapp.py+1 added-1 removed
2 unmodified lines
3from flask import Flask45raise ImportError()67testapp = Flask('testapp')7testapp = Flask("testapp")
modified:tests/test_apps/cliapp/multiapp.py+2 added-2 removed
1from __future__ import absolute_import, print_function23from flask import Flask45app1 = Flask('app1')6app2 = Flask('app2')5app1 = Flask("app1")6app2 = Flask("app2")
modified:tests/test_apps/helloworld/hello.py+2 added
1from flask import Flask23app = Flask(__name__)456@app.route("/")7def hello():8 return "Hello World!"
modified:tests/test_apps/subdomaintestmodule/__init__.py+1 added-1 removed
1from flask import Module234mod = Module(__name__, 'foo', subdomain='foo')4mod = Module(__name__, "foo", subdomain="foo")
modified:tests/conftest.py+33 added-27 removed
18 unmodified lines
19import flask20from flask import Flask as _Flask212223@pytest.fixture(scope='session', autouse=True)23@pytest.fixture(scope="session", autouse=True)24def _standard_os_environ():25 """Set up ``os.environ`` at the start of the test session to have26 standard values. Returns a list of operations that is used by27 :func:`._reset_os_environ` after each test.28 """29 mp = monkeypatch.MonkeyPatch()30 out = (31 (os.environ, 'FLASK_APP', monkeypatch.notset),32 (os.environ, 'FLASK_ENV', monkeypatch.notset),33 (os.environ, 'FLASK_DEBUG', monkeypatch.notset),34 (os.environ, 'FLASK_RUN_FROM_CLI', monkeypatch.notset),35 (os.environ, 'WERKZEUG_RUN_MAIN', monkeypatch.notset),31 (os.environ, "FLASK_APP", monkeypatch.notset),32 (os.environ, "FLASK_ENV", monkeypatch.notset),33 (os.environ, "FLASK_DEBUG", monkeypatch.notset),34 (os.environ, "FLASK_RUN_FROM_CLI", monkeypatch.notset),35 (os.environ, "WERKZEUG_RUN_MAIN", monkeypatch.notset),36 )3738 for _, key, value in out:39 if value is monkeypatch.notset:
14 unmodified lines
545556class Flask(_Flask):57 testing = True58 secret_key = 'test key'58 secret_key = "test key"596061@pytest.fixture62def app():63 app = Flask('flask_test', root_path=os.path.dirname(__file__))63 app = Flask("flask_test", root_path=os.path.dirname(__file__))64 return app656667@pytest.fixture
15 unmodified lines
8384@pytest.fixture85def test_apps(monkeypatch):86 monkeypatch.syspath_prepend(87 os.path.abspath(os.path.join(88 os.path.dirname(__file__), 'test_apps'))87 os.path.abspath(os.path.join(os.path.dirname(__file__), "test_apps"))88 )899091@pytest.fixture(autouse=True)
26 unmodified lines
118 def __init__(self, loader):119 self.loader = loader120121 def __getattr__(self, name):123 if name in ('archive', 'get_filename'):124 msg = 'Mocking a loader which does not have `%s.`' % name122 if name in ("archive", "get_filename"):123 msg = "Mocking a loader which does not have `%s.`" % name124 raise AttributeError(msg)125 return getattr(self.loader, name)126127 old_get_loader = pkgutil.get_loader128129 def get_loader(*args, **kwargs):130 return LimitedLoader(old_get_loader(*args, **kwargs))131133 monkeypatch.setattr(pkgutil, 'get_loader', get_loader)132 monkeypatch.setattr(pkgutil, "get_loader", get_loader)133134135@pytest.fixture136def modules_tmpdir(tmpdir, monkeypatch):137 """A tmpdir added to sys.path."""139 rv = tmpdir.mkdir('modules_tmpdir')138 rv = tmpdir.mkdir("modules_tmpdir")139 monkeypatch.syspath_prepend(str(rv))140 return rv141142143@pytest.fixture144def modules_tmpdir_prefix(modules_tmpdir, monkeypatch):146 monkeypatch.setattr(sys, 'prefix', str(modules_tmpdir))145 monkeypatch.setattr(sys, "prefix", str(modules_tmpdir))146 return modules_tmpdir147148149@pytest.fixture150def site_packages(modules_tmpdir, monkeypatch):151 """Create a fake site-packages."""153 rv = modules_tmpdir \154 .mkdir('lib') \155 .mkdir('python{x[0]}.{x[1]}'.format(x=sys.version_info)) \156 .mkdir('site-packages')152 rv = (153 modules_tmpdir.mkdir("lib")154 .mkdir("python{x[0]}.{x[1]}".format(x=sys.version_info))155 .mkdir("site-packages")156 )157 monkeypatch.syspath_prepend(str(rv))158 return rv159160
5 unmodified lines
166 def inner(name, base=modules_tmpdir):167 if not isinstance(name, str):168 raise ValueError(name)169 base.join(name).ensure_dir()170 base.join(name).join('__init__.py').ensure()170 base.join(name).join("__init__.py").ensure()171172 egg_setup = base.join('setup.py')173 egg_setup.write(textwrap.dedent("""172 egg_setup = base.join("setup.py")173 egg_setup.write(174 textwrap.dedent(175 """176 from setuptools import setup177 setup(name='{0}',178 version='1.0',179 packages=['site_egg'],180 zip_safe=True)179 """.format(name)))181 """.format(182 name183 )184 )185 )186187 import subprocess188189 subprocess.check_call(183 [sys.executable, 'setup.py', 'bdist_egg'],184 cwd=str(modules_tmpdir)190 [sys.executable, "setup.py", "bdist_egg"], cwd=str(modules_tmpdir)191 )186 egg_path, = modules_tmpdir.join('dist/').listdir()192 egg_path, = modules_tmpdir.join("dist/").listdir()193 monkeypatch.syspath_prepend(str(egg_path))194 return egg_path195196 return inner
10 unmodified lines
207@pytest.fixture(autouse=True)208def catch_deprecation_warnings(recwarn):209 yield210 gc.collect()205 assert not recwarn.list, '\n'.join(str(w.message) for w in recwarn.list)211 assert not recwarn.list, "\n".join(str(w.message) for w in recwarn.list)
modified:tests/test_appctx.py+43 added-43 removed
13 unmodified lines
14import flask151617def test_basic_url_generation(app):18 app.config['SERVER_NAME'] = 'localhost'19 app.config['PREFERRED_URL_SCHEME'] = 'https'18 app.config["SERVER_NAME"] = "localhost"19 app.config["PREFERRED_URL_SCHEME"] = "https"2021 @app.route('/')21 @app.route("/")22 def index():23 pass2425 with app.app_context():26 rv = flask.url_for('index')27 assert rv == 'https://localhost/'26 rv = flask.url_for("index")27 assert rv == "https://localhost/"282930def test_url_generation_requires_server_name(app):31 with app.app_context():32 with pytest.raises(RuntimeError):33 flask.url_for('index')33 flask.url_for("index")343536def test_url_generation_without_context_fails():37 with pytest.raises(RuntimeError):38 flask.url_for('index')38 flask.url_for("index")394041def test_request_context_means_app_context(app):42 with app.test_request_context():
27 unmodified lines
70 def cleanup(exception):71 cleanup_stuff.append(exception)7273 try:74 raise Exception('dummy')74 raise Exception("dummy")75 except Exception:76 pass7778 with app.app_context():
10 unmodified lines
89 cleanup_stuff.append(exception)9091 with app.app_context():92 try:93 raise Exception('dummy')93 raise Exception("dummy")94 except Exception:95 pass9697 assert cleanup_stuff == [None]9899100def test_app_tearing_down_with_handled_exception_by_app_handler(app, client):101 app.config['PROPAGATE_EXCEPTIONS'] = True101 app.config["PROPAGATE_EXCEPTIONS"] = True102 cleanup_stuff = []103104 @app.teardown_appcontext105 def cleanup(exception):106 cleanup_stuff.append(exception)107108 @app.route('/')108 @app.route("/")109 def index():110 raise Exception('dummy')110 raise Exception("dummy")111112 @app.errorhandler(Exception)113 def handler(f):114 return flask.jsonify(str(f))115116 with app.app_context():117 client.get('/')117 client.get("/")118119 assert cleanup_stuff == [None]120121122def test_app_tearing_down_with_unhandled_exception(app, client):123 app.config['PROPAGATE_EXCEPTIONS'] = True123 app.config["PROPAGATE_EXCEPTIONS"] = True124 cleanup_stuff = []125126 @app.teardown_appcontext127 def cleanup(exception):128 cleanup_stuff.append(exception)129130 @app.route('/')130 @app.route("/")131 def index():132 raise Exception('dummy')132 raise Exception("dummy")133134 with pytest.raises(Exception):135 with app.app_context():136 client.get('/')136 client.get("/")137138 assert len(cleanup_stuff) == 1139 assert isinstance(cleanup_stuff[0], Exception)140 assert str(cleanup_stuff[0]) == 'dummy'140 assert str(cleanup_stuff[0]) == "dummy"141142143def test_app_ctx_globals_methods(app, app_ctx):144 # get145 assert flask.g.get('foo') is None146 assert flask.g.get('foo', 'bar') == 'bar'145 assert flask.g.get("foo") is None146 assert flask.g.get("foo", "bar") == "bar"147 # __contains__148 assert 'foo' not in flask.g149 flask.g.foo = 'bar'150 assert 'foo' in flask.g148 assert "foo" not in flask.g149 flask.g.foo = "bar"150 assert "foo" in flask.g151 # setdefault152 flask.g.setdefault('bar', 'the cake is a lie')153 flask.g.setdefault('bar', 'hello world')154 assert flask.g.bar == 'the cake is a lie'152 flask.g.setdefault("bar", "the cake is a lie")153 flask.g.setdefault("bar", "hello world")154 assert flask.g.bar == "the cake is a lie"155 # pop156 assert flask.g.pop('bar') == 'the cake is a lie'156 assert flask.g.pop("bar") == "the cake is a lie"157 with pytest.raises(KeyError):158 flask.g.pop('bar')159 assert flask.g.pop('bar', 'more cake') == 'more cake'158 flask.g.pop("bar")159 assert flask.g.pop("bar", "more cake") == "more cake"160 # __iter__161 assert list(flask.g) == ['foo']162 #__repr__161 assert list(flask.g) == ["foo"]162 # __repr__163 assert repr(flask.g) == "<flask.g of 'flask_test'>"164165166def test_custom_app_ctx_globals_class(app):167 class CustomRequestGlobals(object):168 def __init__(self):169 self.spam = 'eggs'169 self.spam = "eggs"170171 app.app_ctx_globals_class = CustomRequestGlobals172 with app.app_context():173 assert flask.render_template_string('{{ g.spam }}') == 'eggs'173 assert flask.render_template_string("{{ g.spam }}") == "eggs"174175176def test_context_refcounts(app, client):177 called = []178179 @app.teardown_request180 def teardown_req(error=None):181 called.append('request')181 called.append("request")182183 @app.teardown_appcontext184 def teardown_app(error=None):185 called.append('app')185 called.append("app")186187 @app.route('/')187 @app.route("/")188 def index():189 with flask._app_ctx_stack.top:190 with flask._request_ctx_stack.top:191 pass192 env = flask._request_ctx_stack.top.request.environ193 assert env['werkzeug.request'] is not None194 return u''193 assert env["werkzeug.request"] is not None194 return u""195196 res = client.get('/')196 res = client.get("/")197 assert res.status_code == 200198 assert res.data == b''199 assert called == ['request', 'app']198 assert res.data == b""199 assert called == ["request", "app"]200201202def test_clean_pop(app):203 app.testing = False
4 unmodified lines
208 1 / 0209210 @app.teardown_appcontext211 def teardown_app(error=None):212 called.append('TEARDOWN')212 called.append("TEARDOWN")213214 try:215 with app.test_request_context():216 called.append(flask.current_app.name)217 except ZeroDivisionError:218 pass219220 assert called == ['flask_test', 'TEARDOWN']220 assert called == ["flask_test", "TEARDOWN"]221 assert not flask.current_app
modified:tests/test_basic.py+695 added-713 removed
24 unmodified lines
25from flask._compat import text_type262728def test_options_work(app, client):29 @app.route('/', methods=['GET', 'POST'])29 @app.route("/", methods=["GET", "POST"])30 def index():31 return 'Hello World'31 return "Hello World"3233 rv = client.open('/', method='OPTIONS')34 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']35 assert rv.data == b''33 rv = client.open("/", method="OPTIONS")34 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]35 assert rv.data == b""363738def test_options_on_multiple_rules(app, client):39 @app.route('/', methods=['GET', 'POST'])39 @app.route("/", methods=["GET", "POST"])40 def index():41 return 'Hello World'41 return "Hello World"4243 @app.route('/', methods=['PUT'])43 @app.route("/", methods=["PUT"])44 def index_put():45 return 'Aha!'45 return "Aha!"4647 rv = client.open('/', method='OPTIONS')48 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']47 rv = client.open("/", method="OPTIONS")48 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST", "PUT"]495051def test_provide_automatic_options_attr():52 app = flask.Flask(__name__)5354 def index():55 return 'Hello World!'55 return "Hello World!"5657 index.provide_automatic_options = False58 app.route('/')(index)59 rv = app.test_client().open('/', method='OPTIONS')58 app.route("/")(index)59 rv = app.test_client().open("/", method="OPTIONS")60 assert rv.status_code == 4056162 app = flask.Flask(__name__)6364 def index2():65 return 'Hello World!'65 return "Hello World!"6667 index2.provide_automatic_options = True68 app.route('/', methods=['OPTIONS'])(index2)69 rv = app.test_client().open('/', method='OPTIONS')70 assert sorted(rv.allow) == ['OPTIONS']68 app.route("/", methods=["OPTIONS"])(index2)69 rv = app.test_client().open("/", method="OPTIONS")70 assert sorted(rv.allow) == ["OPTIONS"]717273def test_provide_automatic_options_kwarg(app, client):74 def index():
1 unmodified line
7677 def more():78 return flask.request.method7980 app.add_url_rule('/', view_func=index, provide_automatic_options=False)80 app.add_url_rule("/", view_func=index, provide_automatic_options=False)81 app.add_url_rule(82 '/more', view_func=more, methods=['GET', 'POST'],83 provide_automatic_options=False82 "/more",83 view_func=more,84 methods=["GET", "POST"],85 provide_automatic_options=False,86 )85 assert client.get('/').data == b'GET'87 assert client.get("/").data == b"GET"8887 rv = client.post('/')89 rv = client.post("/")90 assert rv.status_code == 40589 assert sorted(rv.allow) == ['GET', 'HEAD']91 assert sorted(rv.allow) == ["GET", "HEAD"]9293 # Older versions of Werkzeug.test.Client don't have an options method92 if hasattr(client, 'options'):93 rv = client.options('/')94 if hasattr(client, "options"):95 rv = client.options("/")96 else:95 rv = client.open('/', method='OPTIONS')97 rv = client.open("/", method="OPTIONS")9899 assert rv.status_code == 40510099 rv = client.head('/')101 rv = client.head("/")102 assert rv.status_code == 200103 assert not rv.data # head truncates102 assert client.post('/more').data == b'POST'103 assert client.get('/more').data == b'GET'104 assert client.post("/more").data == b"POST"105 assert client.get("/more").data == b"GET"106105 rv = client.delete('/more')107 rv = client.delete("/more")108 assert rv.status_code == 405107 assert sorted(rv.allow) == ['GET', 'HEAD', 'POST']109 assert sorted(rv.allow) == ["GET", "HEAD", "POST"]110109 if hasattr(client, 'options'):110 rv = client.options('/more')111 if hasattr(client, "options"):112 rv = client.options("/more")113 else:112 rv = client.open('/more', method='OPTIONS')114 rv = client.open("/more", method="OPTIONS")115116 assert rv.status_code == 405117118119def test_request_dispatching(app, client):118 @app.route('/')120 @app.route("/")121 def index():122 return flask.request.method123122 @app.route('/more', methods=['GET', 'POST'])124 @app.route("/more", methods=["GET", "POST"])125 def more():126 return flask.request.method127126 assert client.get('/').data == b'GET'127 rv = client.post('/')128 assert client.get("/").data == b"GET"129 rv = client.post("/")130 assert rv.status_code == 405129 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']130 rv = client.head('/')131 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]132 rv = client.head("/")133 assert rv.status_code == 200134 assert not rv.data # head truncates133 assert client.post('/more').data == b'POST'134 assert client.get('/more').data == b'GET'135 rv = client.delete('/more')135 assert client.post("/more").data == b"POST"136 assert client.get("/more").data == b"GET"137 rv = client.delete("/more")138 assert rv.status_code == 405137 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']139 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]140141142def test_disallow_string_for_allowed_methods(app):143 with pytest.raises(TypeError):142 @app.route('/', methods='GET POST')144145 @app.route("/", methods="GET POST")146 def index():147 return "Hey"148149
8 unmodified lines
158159 def options():160 return random_uuid4161159 app.add_url_rule('/', 'index', index)160 app.add_url_rule('/more', 'more', more, methods=['GET', 'POST'])162 app.add_url_rule("/", "index", index)163 app.add_url_rule("/more", "more", more, methods=["GET", "POST"])164165 # Issue 1288: Test that automatic options are not added when non-uppercase 'options' in methods163 app.add_url_rule('/options', 'options', options, methods=['options'])166 app.add_url_rule("/options", "options", options, methods=["options"])167165 assert client.get('/').data == b'GET'166 rv = client.post('/')168 assert client.get("/").data == b"GET"169 rv = client.post("/")170 assert rv.status_code == 405168 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS']169 rv = client.head('/')171 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS"]172 rv = client.head("/")173 assert rv.status_code == 200174 assert not rv.data # head truncates172 assert client.post('/more').data == b'POST'173 assert client.get('/more').data == b'GET'174 rv = client.delete('/more')175 assert client.post("/more").data == b"POST"176 assert client.get("/more").data == b"GET"177 rv = client.delete("/more")178 assert rv.status_code == 405176 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST']177 rv = client.open('/options', method='OPTIONS')179 assert sorted(rv.allow) == ["GET", "HEAD", "OPTIONS", "POST"]180 rv = client.open("/options", method="OPTIONS")181 assert rv.status_code == 200182 assert random_uuid4 in rv.data.decode("utf-8")183184185def test_werkzeug_routing(app, client):186 from werkzeug.routing import Submount, Rule184 app.url_map.add(Submount('/foo', [185 Rule('/bar', endpoint='bar'),186 Rule('/', endpoint='index')187 ]))187188 app.url_map.add(189 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])190 )191192 def bar():190 return 'bar'193 return "bar"194195 def index():193 return 'index'196 return "index"197195 app.view_functions['bar'] = bar196 app.view_functions['index'] = index198 app.view_functions["bar"] = bar199 app.view_functions["index"] = index200198 assert client.get('/foo/').data == b'index'199 assert client.get('/foo/bar').data == b'bar'201 assert client.get("/foo/").data == b"index"202 assert client.get("/foo/bar").data == b"bar"203204205def test_endpoint_decorator(app, client):206 from werkzeug.routing import Submount, Rule204 app.url_map.add(Submount('/foo', [205 Rule('/bar', endpoint='bar'),206 Rule('/', endpoint='index')207 ]))207208 app.url_map.add(209 Submount("/foo", [Rule("/bar", endpoint="bar"), Rule("/", endpoint="index")])210 )211209 @app.endpoint('bar')212 @app.endpoint("bar")213 def bar():211 return 'bar'214 return "bar"215213 @app.endpoint('index')216 @app.endpoint("index")217 def index():215 return 'index'218 return "index"219217 assert client.get('/foo/').data == b'index'218 assert client.get('/foo/bar').data == b'bar'220 assert client.get("/foo/").data == b"index"221 assert client.get("/foo/bar").data == b"bar"222223224def test_session(app, client):222 @app.route('/set', methods=['POST'])225 @app.route("/set", methods=["POST"])226 def set():227 assert not flask.session.accessed228 assert not flask.session.modified226 flask.session['value'] = flask.request.form['value']229 flask.session["value"] = flask.request.form["value"]230 assert flask.session.accessed231 assert flask.session.modified229 return 'value set'232 return "value set"233231 @app.route('/get')234 @app.route("/get")235 def get():236 assert not flask.session.accessed237 assert not flask.session.modified235 v = flask.session.get('value', 'None')238 v = flask.session.get("value", "None")239 assert flask.session.accessed240 assert not flask.session.modified241 return v242240 assert client.post('/set', data={'value': '42'}).data == b'value set'241 assert client.get('/get').data == b'42'243 assert client.post("/set", data={"value": "42"}).data == b"value set"244 assert client.get("/get").data == b"42"245246247def test_session_using_server_name(app, client):245 app.config.update(246 SERVER_NAME='example.com'247 )248 app.config.update(SERVER_NAME="example.com")249249 @app.route('/')250 @app.route("/")251 def index():251 flask.session['testing'] = 42252 return 'Hello World'252 flask.session["testing"] = 42253 return "Hello World"254254 rv = client.get('/', 'http://example.com/')255 assert 'domain=.example.com' in rv.headers['set-cookie'].lower()256 assert 'httponly' in rv.headers['set-cookie'].lower()255 rv = client.get("/", "http://example.com/")256 assert "domain=.example.com" in rv.headers["set-cookie"].lower()257 assert "httponly" in rv.headers["set-cookie"].lower()258259260def test_session_using_server_name_and_port(app, client):260 app.config.update(261 SERVER_NAME='example.com:8080'262 )261 app.config.update(SERVER_NAME="example.com:8080")262264 @app.route('/')263 @app.route("/")264 def index():266 flask.session['testing'] = 42267 return 'Hello World'265 flask.session["testing"] = 42266 return "Hello World"267269 rv = client.get('/', 'http://example.com:8080/')270 assert 'domain=.example.com' in rv.headers['set-cookie'].lower()271 assert 'httponly' in rv.headers['set-cookie'].lower()268 rv = client.get("/", "http://example.com:8080/")269 assert "domain=.example.com" in rv.headers["set-cookie"].lower()270 assert "httponly" in rv.headers["set-cookie"].lower()271272273def test_session_using_server_name_port_and_path(app, client):275 app.config.update(276 SERVER_NAME='example.com:8080',277 APPLICATION_ROOT='/foo'278 )274 app.config.update(SERVER_NAME="example.com:8080", APPLICATION_ROOT="/foo")275280 @app.route('/')276 @app.route("/")277 def index():282 flask.session['testing'] = 42283 return 'Hello World'278 flask.session["testing"] = 42279 return "Hello World"280285 rv = client.get('/', 'http://example.com:8080/foo')286 assert 'domain=example.com' in rv.headers['set-cookie'].lower()287 assert 'path=/foo' in rv.headers['set-cookie'].lower()288 assert 'httponly' in rv.headers['set-cookie'].lower()281 rv = client.get("/", "http://example.com:8080/foo")282 assert "domain=example.com" in rv.headers["set-cookie"].lower()283 assert "path=/foo" in rv.headers["set-cookie"].lower()284 assert "httponly" in rv.headers["set-cookie"].lower()285286287def test_session_using_application_root(app, client):288 class PrefixPathMiddleware(object):
1 unmodified line
290 self.app = app291 self.prefix = prefix292293 def __call__(self, environ, start_response):298 environ['SCRIPT_NAME'] = self.prefix294 environ["SCRIPT_NAME"] = self.prefix295 return self.app(environ, start_response)296301 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar')302 app.config.update(303 APPLICATION_ROOT='/bar'304 )297 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, "/bar")298 app.config.update(APPLICATION_ROOT="/bar")299306 @app.route('/')300 @app.route("/")301 def index():308 flask.session['testing'] = 42309 return 'Hello World'302 flask.session["testing"] = 42303 return "Hello World"304311 rv = client.get('/', 'http://example.com:8080/')312 assert 'path=/bar' in rv.headers['set-cookie'].lower()305 rv = client.get("/", "http://example.com:8080/")306 assert "path=/bar" in rv.headers["set-cookie"].lower()307308309def test_session_using_session_settings(app, client):310 app.config.update(317 SERVER_NAME='www.example.com:8080',318 APPLICATION_ROOT='/test',319 SESSION_COOKIE_DOMAIN='.example.com',311 SERVER_NAME="www.example.com:8080",312 APPLICATION_ROOT="/test",313 SESSION_COOKIE_DOMAIN=".example.com",314 SESSION_COOKIE_HTTPONLY=False,315 SESSION_COOKIE_SECURE=True,322 SESSION_COOKIE_SAMESITE='Lax',323 SESSION_COOKIE_PATH='/'316 SESSION_COOKIE_SAMESITE="Lax",317 SESSION_COOKIE_PATH="/",318 )319326 @app.route('/')320 @app.route("/")321 def index():328 flask.session['testing'] = 42329 return 'Hello World'322 flask.session["testing"] = 42323 return "Hello World"324331 rv = client.get('/', 'http://www.example.com:8080/test/')332 cookie = rv.headers['set-cookie'].lower()333 assert 'domain=.example.com' in cookie334 assert 'path=/' in cookie335 assert 'secure' in cookie336 assert 'httponly' not in cookie337 assert 'samesite' in cookie325 rv = client.get("/", "http://www.example.com:8080/test/")326 cookie = rv.headers["set-cookie"].lower()327 assert "domain=.example.com" in cookie328 assert "path=/" in cookie329 assert "secure" in cookie330 assert "httponly" not in cookie331 assert "samesite" in cookie332333334def test_session_using_samesite_attribute(app, client):341 @app.route('/')335 @app.route("/")336 def index():343 flask.session['testing'] = 42344 return 'Hello World'337 flask.session["testing"] = 42338 return "Hello World"339346 app.config.update(SESSION_COOKIE_SAMESITE='invalid')340 app.config.update(SESSION_COOKIE_SAMESITE="invalid")341342 with pytest.raises(ValueError):349 client.get('/')343 client.get("/")344345 app.config.update(SESSION_COOKIE_SAMESITE=None)352 rv = client.get('/')353 cookie = rv.headers['set-cookie'].lower()354 assert 'samesite' not in cookie346 rv = client.get("/")347 cookie = rv.headers["set-cookie"].lower()348 assert "samesite" not in cookie349356 app.config.update(SESSION_COOKIE_SAMESITE='Strict')357 rv = client.get('/')358 cookie = rv.headers['set-cookie'].lower()359 assert 'samesite=strict' in cookie350 app.config.update(SESSION_COOKIE_SAMESITE="Strict")351 rv = client.get("/")352 cookie = rv.headers["set-cookie"].lower()353 assert "samesite=strict" in cookie354361 app.config.update(SESSION_COOKIE_SAMESITE='Lax')362 rv = client.get('/')363 cookie = rv.headers['set-cookie'].lower()364 assert 'samesite=lax' in cookie355 app.config.update(SESSION_COOKIE_SAMESITE="Lax")356 rv = client.get("/")357 cookie = rv.headers["set-cookie"].lower()358 assert "samesite=lax" in cookie359360361def test_session_localhost_warning(recwarn, app, client):368 app.config.update(369 SERVER_NAME='localhost:5000',370 )362 app.config.update(SERVER_NAME="localhost:5000")363372 @app.route('/')364 @app.route("/")365 def index():374 flask.session['testing'] = 42375 return 'testing'366 flask.session["testing"] = 42367 return "testing"368377 rv = client.get('/', 'http://localhost:5000/')378 assert 'domain' not in rv.headers['set-cookie'].lower()369 rv = client.get("/", "http://localhost:5000/")370 assert "domain" not in rv.headers["set-cookie"].lower()371 w = recwarn.pop(UserWarning)372 assert '"localhost" is not a valid cookie domain' in str(w.message)373374375def test_session_ip_warning(recwarn, app, client):384 app.config.update(385 SERVER_NAME='127.0.0.1:5000',386 )376 app.config.update(SERVER_NAME="127.0.0.1:5000")377388 @app.route('/')378 @app.route("/")379 def index():390 flask.session['testing'] = 42391 return 'testing'380 flask.session["testing"] = 42381 return "testing"382393 rv = client.get('/', 'http://127.0.0.1:5000/')394 assert 'domain=127.0.0.1' in rv.headers['set-cookie'].lower()383 rv = client.get("/", "http://127.0.0.1:5000/")384 assert "domain=127.0.0.1" in rv.headers["set-cookie"].lower()385 w = recwarn.pop(UserWarning)396 assert 'cookie domain is an IP' in str(w.message)386 assert "cookie domain is an IP" in str(w.message)387388389def test_missing_session(app):390 app.secret_key = None391392 def expect_exception(f, *args, **kwargs):393 e = pytest.raises(RuntimeError, f, *args, **kwargs)404 assert e.value.args and 'session is unavailable' in e.value.args[0]394 assert e.value.args and "session is unavailable" in e.value.args[0]395396 with app.test_request_context():407 assert flask.session.get('missing_key') is None408 expect_exception(flask.session.__setitem__, 'foo', 42)409 expect_exception(flask.session.pop, 'foo')397 assert flask.session.get("missing_key") is None398 expect_exception(flask.session.__setitem__, "foo", 42)399 expect_exception(flask.session.pop, "foo")400401402def test_session_expiration(app, client):403 permanent = True404415 @app.route('/')405 @app.route("/")406 def index():417 flask.session['test'] = 42407 flask.session["test"] = 42408 flask.session.permanent = permanent419 return ''409 return ""410421 @app.route('/test')411 @app.route("/test")412 def test():413 return text_type(flask.session.permanent)414425 rv = client.get('/')426 assert 'set-cookie' in rv.headers427 match = re.search(r'(?i)\bexpires=([^;]+)', rv.headers['set-cookie'])415 rv = client.get("/")416 assert "set-cookie" in rv.headers417 match = re.search(r"(?i)\bexpires=([^;]+)", rv.headers["set-cookie"])418 expires = parse_date(match.group())419 expected = datetime.utcnow() + app.permanent_session_lifetime420 assert expires.year == expected.year421 assert expires.month == expected.month422 assert expires.day == expected.day423434 rv = client.get('/test')435 assert rv.data == b'True'424 rv = client.get("/test")425 assert rv.data == b"True"426427 permanent = False438 rv = client.get('/')439 assert 'set-cookie' in rv.headers440 match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie'])428 rv = client.get("/")429 assert "set-cookie" in rv.headers430 match = re.search(r"\bexpires=([^;]+)", rv.headers["set-cookie"])431 assert match is None432433434def test_session_stored_last(app, client):435 @app.after_request436 def modify_session(response):447 flask.session['foo'] = 42437 flask.session["foo"] = 42438 return response439450 @app.route('/')440 @app.route("/")441 def dump_session_contents():452 return repr(flask.session.get('foo'))442 return repr(flask.session.get("foo"))443454 assert client.get('/').data == b'None'455 assert client.get('/').data == b'42'444 assert client.get("/").data == b"None"445 assert client.get("/").data == b"42"446447448def test_session_special_types(app, client):449 now = datetime.utcnow().replace(microsecond=0)450 the_uuid = uuid.uuid4()451462 @app.route('/')452 @app.route("/")453 def dump_session_contents():464 flask.session['t'] = (1, 2, 3)465 flask.session['b'] = b'\xff'466 flask.session['m'] = flask.Markup('<html>')467 flask.session['u'] = the_uuid468 flask.session['d'] = now469 flask.session['t_tag'] = {' t': 'not-a-tuple'}470 flask.session['di_t_tag'] = {' t__': 'not-a-tuple'}471 flask.session['di_tag'] = {' di': 'not-a-dict'}472 return '', 204454 flask.session["t"] = (1, 2, 3)455 flask.session["b"] = b"\xff"456 flask.session["m"] = flask.Markup("<html>")457 flask.session["u"] = the_uuid458 flask.session["d"] = now459 flask.session["t_tag"] = {" t": "not-a-tuple"}460 flask.session["di_t_tag"] = {" t__": "not-a-tuple"}461 flask.session["di_tag"] = {" di": "not-a-dict"}462 return "", 204463464 with client:475 client.get('/')465 client.get("/")466 s = flask.session477 assert s['t'] == (1, 2, 3)478 assert type(s['b']) == bytes479 assert s['b'] == b'\xff'480 assert type(s['m']) == flask.Markup481 assert s['m'] == flask.Markup('<html>')482 assert s['u'] == the_uuid483 assert s['d'] == now484 assert s['t_tag'] == {' t': 'not-a-tuple'}485 assert s['di_t_tag'] == {' t__': 'not-a-tuple'}486 assert s['di_tag'] == {' di': 'not-a-dict'}467 assert s["t"] == (1, 2, 3)468 assert type(s["b"]) == bytes469 assert s["b"] == b"\xff"470 assert type(s["m"]) == flask.Markup471 assert s["m"] == flask.Markup("<html>")472 assert s["u"] == the_uuid473 assert s["d"] == now474 assert s["t_tag"] == {" t": "not-a-tuple"}475 assert s["di_t_tag"] == {" t__": "not-a-tuple"}476 assert s["di_tag"] == {" di": "not-a-dict"}477478479def test_session_cookie_setting(app):480 is_permanent = True481492 @app.route('/bump')482 @app.route("/bump")483 def bump():494 rv = flask.session['foo'] = flask.session.get('foo', 0) + 1484 rv = flask.session["foo"] = flask.session.get("foo", 0) + 1485 flask.session.permanent = is_permanent486 return str(rv)487498 @app.route('/read')488 @app.route("/read")489 def read():500 return str(flask.session.get('foo', 0))490 return str(flask.session.get("foo", 0))491492 def run_test(expect_header):493 with app.test_client() as c:504 assert c.get('/bump').data == b'1'505 assert c.get('/bump').data == b'2'506 assert c.get('/bump').data == b'3'494 assert c.get("/bump").data == b"1"495 assert c.get("/bump").data == b"2"496 assert c.get("/bump").data == b"3"497508 rv = c.get('/read')509 set_cookie = rv.headers.get('set-cookie')498 rv = c.get("/read")499 set_cookie = rv.headers.get("set-cookie")500 assert (set_cookie is not None) == expect_header511 assert rv.data == b'3'501 assert rv.data == b"3"502503 is_permanent = True514 app.config['SESSION_REFRESH_EACH_REQUEST'] = True504 app.config["SESSION_REFRESH_EACH_REQUEST"] = True505 run_test(expect_header=True)506507 is_permanent = True518 app.config['SESSION_REFRESH_EACH_REQUEST'] = False508 app.config["SESSION_REFRESH_EACH_REQUEST"] = False509 run_test(expect_header=False)510511 is_permanent = False522 app.config['SESSION_REFRESH_EACH_REQUEST'] = True512 app.config["SESSION_REFRESH_EACH_REQUEST"] = True513 run_test(expect_header=False)514515 is_permanent = False526 app.config['SESSION_REFRESH_EACH_REQUEST'] = False516 app.config["SESSION_REFRESH_EACH_REQUEST"] = False517 run_test(expect_header=False)518519520def test_session_vary_cookie(app, client):531 @app.route('/set')521 @app.route("/set")522 def set_session():533 flask.session['test'] = 'test'534 return ''523 flask.session["test"] = "test"524 return ""525536 @app.route('/get')526 @app.route("/get")527 def get():538 return flask.session.get('test')528 return flask.session.get("test")529540 @app.route('/getitem')530 @app.route("/getitem")531 def getitem():542 return flask.session['test']532 return flask.session["test"]533544 @app.route('/setdefault')534 @app.route("/setdefault")535 def setdefault():546 return flask.session.setdefault('test', 'default')536 return flask.session.setdefault("test", "default")537548 @app.route('/vary-cookie-header-set')538 @app.route("/vary-cookie-header-set")539 def vary_cookie_header_set():540 response = flask.Response()551 response.vary.add('Cookie')552 flask.session['test'] = 'test'541 response.vary.add("Cookie")542 flask.session["test"] = "test"543 return response544555 @app.route('/vary-header-set')545 @app.route("/vary-header-set")546 def vary_header_set():547 response = flask.Response()558 response.vary.update(('Accept-Encoding', 'Accept-Language'))559 flask.session['test'] = 'test'548 response.vary.update(("Accept-Encoding", "Accept-Language"))549 flask.session["test"] = "test"550 return response551562 @app.route('/no-vary-header')552 @app.route("/no-vary-header")553 def no_vary_header():564 return ''554 return ""555566 def expect(path, header_value='Cookie'):556 def expect(path, header_value="Cookie"):557 rv = client.get(path)558559 if header_value:560 # The 'Vary' key should exist in the headers only once.571 assert len(rv.headers.get_all('Vary')) == 1572 assert rv.headers['Vary'] == header_value561 assert len(rv.headers.get_all("Vary")) == 1562 assert rv.headers["Vary"] == header_value563 else:574 assert 'Vary' not in rv.headers564 assert "Vary" not in rv.headers565576 expect('/set')577 expect('/get')578 expect('/getitem')579 expect('/setdefault')580 expect('/vary-cookie-header-set')581 expect('/vary-header-set', 'Accept-Encoding, Accept-Language, Cookie')582 expect('/no-vary-header', None)566 expect("/set")567 expect("/get")568 expect("/getitem")569 expect("/setdefault")570 expect("/vary-cookie-header-set")571 expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")572 expect("/no-vary-header", None)573574575def test_flashes(app, req_ctx):576 assert not flask.session.modified587 flask.flash('Zap')577 flask.flash("Zap")578 flask.session.modified = False589 flask.flash('Zip')579 flask.flash("Zip")580 assert flask.session.modified591 assert list(flask.get_flashed_messages()) == ['Zap', 'Zip']581 assert list(flask.get_flashed_messages()) == ["Zap", "Zip"]582583584def test_extended_flashing(app):585 # Be sure app.testing=True below, else tests can fail silently.
1 unmodified line
587 # Specifically, if app.testing is not set to True, the AssertionErrors588 # in the view functions will cause a 500 response to the test client589 # instead of propagating exceptions.590601 @app.route('/')591 @app.route("/")592 def index():603 flask.flash(u'Hello World')604 flask.flash(u'Hello World', 'error')605 flask.flash(flask.Markup(u'<em>Testing</em>'), 'warning')606 return ''593 flask.flash(u"Hello World")594 flask.flash(u"Hello World", "error")595 flask.flash(flask.Markup(u"<em>Testing</em>"), "warning")596 return ""597608 @app.route('/test/')598 @app.route("/test/")599 def test():600 messages = flask.get_flashed_messages()601 assert list(messages) == [612 u'Hello World',613 u'Hello World',614 flask.Markup(u'<em>Testing</em>')602 u"Hello World",603 u"Hello World",604 flask.Markup(u"<em>Testing</em>"),605 ]616 return ''606 return ""607618 @app.route('/test_with_categories/')608 @app.route("/test_with_categories/")609 def test_with_categories():610 messages = flask.get_flashed_messages(with_categories=True)611 assert len(messages) == 3612 assert list(messages) == [623 ('message', u'Hello World'),624 ('error', u'Hello World'),625 ('warning', flask.Markup(u'<em>Testing</em>'))613 ("message", u"Hello World"),614 ("error", u"Hello World"),615 ("warning", flask.Markup(u"<em>Testing</em>")),616 ]627 return ''617 return ""618629 @app.route('/test_filter/')619 @app.route("/test_filter/")620 def test_filter():621 messages = flask.get_flashed_messages(632 category_filter=['message'], with_categories=True)633 assert list(messages) == [('message', u'Hello World')]634 return ''622 category_filter=["message"], with_categories=True623 )624 assert list(messages) == [("message", u"Hello World")]625 return ""626636 @app.route('/test_filters/')627 @app.route("/test_filters/")628 def test_filters():629 messages = flask.get_flashed_messages(639 category_filter=['message', 'warning'], with_categories=True)630 category_filter=["message", "warning"], with_categories=True631 )632 assert list(messages) == [641 ('message', u'Hello World'),642 ('warning', flask.Markup(u'<em>Testing</em>'))633 ("message", u"Hello World"),634 ("warning", flask.Markup(u"<em>Testing</em>")),635 ]644 return ''636 return ""637646 @app.route('/test_filters_without_returning_categories/')638 @app.route("/test_filters_without_returning_categories/")639 def test_filters2():648 messages = flask.get_flashed_messages(649 category_filter=['message', 'warning'])640 messages = flask.get_flashed_messages(category_filter=["message", "warning"])641 assert len(messages) == 2651 assert messages[0] == u'Hello World'652 assert messages[1] == flask.Markup(u'<em>Testing</em>')653 return ''642 assert messages[0] == u"Hello World"643 assert messages[1] == flask.Markup(u"<em>Testing</em>")644 return ""645646 # Create new test client on each test to clean flashed messages.647648 client = app.test_client()658 client.get('/')659 client.get('/test_with_categories/')649 client.get("/")650 client.get("/test_with_categories/")651652 client = app.test_client()662 client.get('/')663 client.get('/test_filter/')653 client.get("/")654 client.get("/test_filter/")655656 client = app.test_client()666 client.get('/')667 client.get('/test_filters/')657 client.get("/")658 client.get("/test_filters/")659660 client = app.test_client()670 client.get('/')671 client.get('/test_filters_without_returning_categories/')661 client.get("/")662 client.get("/test_filters_without_returning_categories/")663664665def test_request_processing(app, client):666 evts = []667668 @app.before_request669 def before_request():679 evts.append('before')670 evts.append("before")671672 @app.after_request673 def after_request(response):683 response.data += b'|after'684 evts.append('after')674 response.data += b"|after"675 evts.append("after")676 return response677687 @app.route('/')678 @app.route("/")679 def index():689 assert 'before' in evts690 assert 'after' not in evts691 return 'request'680 assert "before" in evts681 assert "after" not in evts682 return "request"683693 assert 'after' not in evts694 rv = client.get('/').data695 assert 'after' in evts696 assert rv == b'request|after'684 assert "after" not in evts685 rv = client.get("/").data686 assert "after" in evts687 assert rv == b"request|after"688689690def test_request_preprocessing_early_return(app, client):691 evts = []
11 unmodified lines
703 def before_request3():704 evts.append(3)705 return "bye"706716 @app.route('/')707 @app.route("/")708 def index():718 evts.append('index')709 evts.append("index")710 return "damnit"711721 rv = client.get('/').data.strip()722 assert rv == b'hello'712 rv = client.get("/").data.strip()713 assert rv == b"hello"714 assert evts == [1, 2]715716717def test_after_request_processing(app, client):727 @app.route('/')718 @app.route("/")719 def index():720 @flask.after_this_request721 def foo(response):731 response.headers['X-Foo'] = 'a header'722 response.headers["X-Foo"] = "a header"723 return response724734 return 'Test'725 return "Test"726736 resp = client.get('/')727 resp = client.get("/")728 assert resp.status_code == 200738 assert resp.headers['X-Foo'] == 'a header'729 assert resp.headers["X-Foo"] == "a header"730731732def test_teardown_request_handler(app, client):733 called = []
2 unmodified lines
736 def teardown_request(exc):737 called.append(True)738 return "Ignored"739749 @app.route('/')740 @app.route("/")741 def root():742 return "Response"743753 rv = client.get('/')744 rv = client.get("/")745 assert rv.status_code == 200755 assert b'Response' in rv.data746 assert b"Response" in rv.data747 assert len(called) == 1748749750def test_teardown_request_handler_debug_mode(app, client):
3 unmodified lines
754 def teardown_request(exc):755 called.append(True)756 return "Ignored"757767 @app.route('/')758 @app.route("/")759 def root():760 return "Response"761771 rv = client.get('/')762 rv = client.get("/")763 assert rv.status_code == 200773 assert b'Response' in rv.data764 assert b"Response" in rv.data765 assert len(called) == 1766767768def test_teardown_request_handler_error(app, client):
23 unmodified lines
792 raise TypeError()793 except:794 pass795805 @app.route('/')796 @app.route("/")797 def fails():798 1 // 0799809 rv = client.get('/')800 rv = client.get("/")801 assert rv.status_code == 500811 assert b'Internal Server Error' in rv.data802 assert b"Internal Server Error" in rv.data803 assert len(called) == 2804805806def test_before_after_request_order(app, client):
24 unmodified lines
831 @app.teardown_request832 def finish2(exc):833 called.append(5)834844 @app.route('/')835 @app.route("/")836 def index():846 return '42'837 return "42"838848 rv = client.get('/')849 assert rv.data == b'42'839 rv = client.get("/")840 assert rv.data == b"42"841 assert called == [1, 2, 3, 4, 5, 6]842843844def test_error_handling(app, client):845 app.testing = False846847 @app.errorhandler(404)848 def not_found(e):858 return 'not found', 404849 return "not found", 404850851 @app.errorhandler(500)852 def internal_server_error(e):862 return 'internal server error', 500853 return "internal server error", 500854855 @app.errorhandler(Forbidden)856 def forbidden(e):866 return 'forbidden', 403857 return "forbidden", 403858868 @app.route('/')859 @app.route("/")860 def index():861 flask.abort(404)862872 @app.route('/error')863 @app.route("/error")864 def error():865 1 // 0866876 @app.route('/forbidden')867 @app.route("/forbidden")868 def error2():869 flask.abort(403)870880 rv = client.get('/')871 rv = client.get("/")872 assert rv.status_code == 404882 assert rv.data == b'not found'883 rv = client.get('/error')873 assert rv.data == b"not found"874 rv = client.get("/error")875 assert rv.status_code == 500885 assert b'internal server error' == rv.data886 rv = client.get('/forbidden')876 assert b"internal server error" == rv.data877 rv = client.get("/forbidden")878 assert rv.status_code == 403888 assert b'forbidden' == rv.data879 assert b"forbidden" == rv.data880881882def test_error_handler_unknown_code(app):883 with pytest.raises(KeyError) as exc_info:893 app.register_error_handler(999, lambda e: ('999', 999))884 app.register_error_handler(999, lambda e: ("999", 999))885895 assert 'Use a subclass' in exc_info.value.args[0]886 assert "Use a subclass" in exc_info.value.args[0]887888889def test_error_handling_processing(app, client):890 app.testing = False891892 @app.errorhandler(500)893 def internal_server_error(e):903 return 'internal server error', 500894 return "internal server error", 500895905 @app.route('/')896 @app.route("/")897 def broken_func():898 1 // 0899900 @app.after_request901 def after_request(resp):911 resp.mimetype = 'text/x-special'902 resp.mimetype = "text/x-special"903 return resp904914 resp = client.get('/')915 assert resp.mimetype == 'text/x-special'916 assert resp.data == b'internal server error'905 resp = client.get("/")906 assert resp.mimetype == "text/x-special"907 assert resp.data == b"internal server error"908909910def test_baseexception_error_handling(app, client):911 app.testing = False912922 @app.route('/')913 @app.route("/")914 def broken_func():915 raise KeyboardInterrupt()916917 with pytest.raises(KeyboardInterrupt):927 client.get('/')918 client.get("/")919920 ctx = flask._request_ctx_stack.top921 assert ctx.preserved922 assert type(ctx._preserved_exc) is KeyboardInterrupt
1 unmodified line
924925def test_before_request_and_routing_errors(app, client):926 @app.before_request927 def attach_something():937 flask.g.something = 'value'928 flask.g.something = "value"929930 @app.errorhandler(404)931 def return_something(error):932 return flask.g.something, 404933943 rv = client.get('/')934 rv = client.get("/")935 assert rv.status_code == 404945 assert rv.data == b'value'936 assert rv.data == b"value"937938939def test_user_error_handling(app, client):940 class MyException(Exception):
1 unmodified line
942943 @app.errorhandler(MyException)944 def handle_my_exception(e):945 assert isinstance(e, MyException)955 return '42'946 return "42"947957 @app.route('/')948 @app.route("/")949 def index():950 raise MyException()951961 assert client.get('/').data == b'42'952 assert client.get("/").data == b"42"953954955def test_http_error_subclass_handling(app, client):956 class ForbiddenSubclass(Forbidden):
1 unmodified line
958959 @app.errorhandler(ForbiddenSubclass)960 def handle_forbidden_subclass(e):961 assert isinstance(e, ForbiddenSubclass)971 return 'banana'962 return "banana"963964 @app.errorhandler(403)965 def handle_forbidden_subclass(e):966 assert not isinstance(e, ForbiddenSubclass)967 assert isinstance(e, Forbidden)977 return 'apple'968 return "apple"969979 @app.route('/1')970 @app.route("/1")971 def index1():972 raise ForbiddenSubclass()973983 @app.route('/2')974 @app.route("/2")975 def index2():976 flask.abort(403)977987 @app.route('/3')978 @app.route("/3")979 def index3():980 raise Forbidden()981991 assert client.get('/1').data == b'banana'992 assert client.get('/2').data == b'apple'993 assert client.get('/3').data == b'apple'982 assert client.get("/1").data == b"banana"983 assert client.get("/2").data == b"apple"984 assert client.get("/3").data == b"apple"985986987def test_errorhandler_precedence(app, client):988 class E1(Exception):
6 unmodified lines
995 pass996997 @app.errorhandler(E2)998 def handle_e2(e):1008 return 'E2'999 return "E2"10001001 @app.errorhandler(Exception)1002 def handle_exception(e):1012 return 'Exception'1003 return "Exception"10041014 @app.route('/E1')1005 @app.route("/E1")1006 def raise_e1():1007 raise E110081018 @app.route('/E3')1009 @app.route("/E3")1010 def raise_e3():1011 raise E310121022 rv = client.get('/E1')1023 assert rv.data == b'Exception'1013 rv = client.get("/E1")1014 assert rv.data == b"Exception"10151025 rv = client.get('/E3')1026 assert rv.data == b'E2'1016 rv = client.get("/E3")1017 assert rv.data == b"E2"101810191020def test_trapping_of_bad_request_key_errors(app, client):1030 @app.route('/key')1021 @app.route("/key")1022 def fail():1032 flask.request.form['missing_key']1023 flask.request.form["missing_key"]10241034 @app.route('/abort')1025 @app.route("/abort")1026 def allow_abort():1027 flask.abort(400)10281038 rv = client.get('/key')1029 rv = client.get("/key")1030 assert rv.status_code == 4001040 assert b'missing_key' not in rv.data1041 rv = client.get('/abort')1031 assert b"missing_key" not in rv.data1032 rv = client.get("/abort")1033 assert rv.status_code == 40010341035 app.debug = True1036 with pytest.raises(KeyError) as e:1037 client.get("/key")1038 assert e.errisinstance(BadRequest)1048 assert 'missing_key' in e.value.get_description()1049 rv = client.get('/abort')1039 assert "missing_key" in e.value.get_description()1040 rv = client.get("/abort")1041 assert rv.status_code == 40010421043 app.debug = False1053 app.config['TRAP_BAD_REQUEST_ERRORS'] = True1044 app.config["TRAP_BAD_REQUEST_ERRORS"] = True1045 with pytest.raises(KeyError):1055 client.get('/key')1046 client.get("/key")1047 with pytest.raises(BadRequest):1057 client.get('/abort')1048 client.get("/abort")104910501051def test_trapping_of_all_http_exceptions(app, client):1061 app.config['TRAP_HTTP_EXCEPTIONS'] = True1052 app.config["TRAP_HTTP_EXCEPTIONS"] = True10531063 @app.route('/fail')1054 @app.route("/fail")1055 def fail():1056 flask.abort(404)10571058 with pytest.raises(NotFound):1068 client.get('/fail')1059 client.get("/fail")106010611062def test_error_handler_after_processor_error(app, client):1063 app.testing = False10641065 @app.before_request1066 def before_request():1076 if trigger == 'before':1067 if trigger == "before":1068 1 // 010691070 @app.after_request1071 def after_request(response):1081 if trigger == 'after':1072 if trigger == "after":1073 1 // 01074 return response10751085 @app.route('/')1076 @app.route("/")1077 def index():1087 return 'Foo'1078 return "Foo"10791080 @app.errorhandler(500)1081 def internal_server_error(e):1091 return 'Hello Server Error', 5001082 return "Hello Server Error", 50010831093 for trigger in 'before', 'after':1094 rv = client.get('/')1084 for trigger in "before", "after":1085 rv = client.get("/")1086 assert rv.status_code == 5001096 assert rv.data == b'Hello Server Error'1087 assert rv.data == b"Hello Server Error"108810891090def test_enctype_debug_helper(app, client):1091 from flask.debughelpers import DebugFilesKeyError10921093 app.debug = True10941103 @app.route('/fail', methods=['POST'])1095 @app.route("/fail", methods=["POST"])1096 def index():1105 return flask.request.files['foo'].filename1097 return flask.request.files["foo"].filename10981099 # with statement is important because we leave an exception on the1100 # stack otherwise and we want to ensure that this is not the case1101 # to not negatively affect other tests.1102 with client:1103 with pytest.raises(DebugFilesKeyError) as e:1112 client.post('/fail', data={'foo': 'index.txt'})1113 assert 'no file contents were transmitted' in str(e.value)1104 client.post("/fail", data={"foo": "index.txt"})1105 assert "no file contents were transmitted" in str(e.value)1106 assert 'This was submitted: "index.txt"' in str(e.value)110711081109def test_response_types(app, client):1118 @app.route('/text')1110 @app.route("/text")1111 def from_text():1120 return u'Hällo Wörld'1112 return u"Hällo Wörld"11131122 @app.route('/bytes')1114 @app.route("/bytes")1115 def from_bytes():1124 return u'Hällo Wörld'.encode('utf-8')1116 return u"Hällo Wörld".encode("utf-8")11171126 @app.route('/full_tuple')1118 @app.route("/full_tuple")1119 def from_full_tuple():1128 return 'Meh', 400, {1129 'X-Foo': 'Testing',1130 'Content-Type': 'text/plain; charset=utf-8'1131 }1120 return (1121 "Meh",1122 400,1123 {"X-Foo": "Testing", "Content-Type": "text/plain; charset=utf-8"},1124 )11251133 @app.route('/text_headers')1126 @app.route("/text_headers")1127 def from_text_headers():1135 return 'Hello', {1136 'X-Foo': 'Test',1137 'Content-Type': 'text/plain; charset=utf-8'1138 }1128 return "Hello", {"X-Foo": "Test", "Content-Type": "text/plain; charset=utf-8"}11291140 @app.route('/text_status')1130 @app.route("/text_status")1131 def from_text_status():1142 return 'Hi, status!', 4001132 return "Hi, status!", 40011331144 @app.route('/response_headers')1134 @app.route("/response_headers")1135 def from_response_headers():1146 return flask.Response('Hello world', 404, {'X-Foo': 'Baz'}), {1147 "X-Foo": "Bar",1148 "X-Bar": "Foo"1149 }1136 return (1137 flask.Response("Hello world", 404, {"X-Foo": "Baz"}),1138 {"X-Foo": "Bar", "X-Bar": "Foo"},1139 )11401151 @app.route('/response_status')1141 @app.route("/response_status")1142 def from_response_status():1153 return app.response_class('Hello world', 400), 5001143 return app.response_class("Hello world", 400), 50011441155 @app.route('/wsgi')1145 @app.route("/wsgi")1146 def from_wsgi():1147 return NotFound()11481159 assert client.get('/text').data == u'Hällo Wörld'.encode('utf-8')1160 assert client.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')1149 assert client.get("/text").data == u"Hällo Wörld".encode("utf-8")1150 assert client.get("/bytes").data == u"Hällo Wörld".encode("utf-8")11511162 rv = client.get('/full_tuple')1163 assert rv.data == b'Meh'1164 assert rv.headers['X-Foo'] == 'Testing'1152 rv = client.get("/full_tuple")1153 assert rv.data == b"Meh"1154 assert rv.headers["X-Foo"] == "Testing"1155 assert rv.status_code == 4001166 assert rv.mimetype == 'text/plain'1156 assert rv.mimetype == "text/plain"11571168 rv = client.get('/text_headers')1169 assert rv.data == b'Hello'1170 assert rv.headers['X-Foo'] == 'Test'1158 rv = client.get("/text_headers")1159 assert rv.data == b"Hello"1160 assert rv.headers["X-Foo"] == "Test"1161 assert rv.status_code == 2001172 assert rv.mimetype == 'text/plain'1162 assert rv.mimetype == "text/plain"11631174 rv = client.get('/text_status')1175 assert rv.data == b'Hi, status!'1164 rv = client.get("/text_status")1165 assert rv.data == b"Hi, status!"1166 assert rv.status_code == 4001177 assert rv.mimetype == 'text/html'1167 assert rv.mimetype == "text/html"11681179 rv = client.get('/response_headers')1180 assert rv.data == b'Hello world'1181 assert rv.headers.getlist('X-Foo') == ['Baz', 'Bar']1182 assert rv.headers['X-Bar'] == 'Foo'1169 rv = client.get("/response_headers")1170 assert rv.data == b"Hello world"1171 assert rv.headers.getlist("X-Foo") == ["Baz", "Bar"]1172 assert rv.headers["X-Bar"] == "Foo"1173 assert rv.status_code == 40411741185 rv = client.get('/response_status')1186 assert rv.data == b'Hello world'1175 rv = client.get("/response_status")1176 assert rv.data == b"Hello world"1177 assert rv.status_code == 50011781189 rv = client.get('/wsgi')1190 assert b'Not Found' in rv.data1179 rv = client.get("/wsgi")1180 assert b"Not Found" in rv.data1181 assert rv.status_code == 404118211831184def test_response_type_errors():1185 app = flask.Flask(__name__)1186 app.testing = True11871198 @app.route('/none')1188 @app.route("/none")1189 def from_none():1190 pass11911202 @app.route('/small_tuple')1192 @app.route("/small_tuple")1193 def from_small_tuple():1204 return 'Hello',1194 return ("Hello",)11951206 @app.route('/large_tuple')1196 @app.route("/large_tuple")1197 def from_large_tuple():1208 return 'Hello', 234, {'X-Foo': 'Bar'}, '???'1198 return "Hello", 234, {"X-Foo": "Bar"}, "???"11991210 @app.route('/bad_type')1200 @app.route("/bad_type")1201 def from_bad_type():1202 return True12031214 @app.route('/bad_wsgi')1204 @app.route("/bad_wsgi")1205 def from_bad_wsgi():1206 return lambda: None12071208 c = app.test_client()12091210 with pytest.raises(TypeError) as e:1221 c.get('/none')1222 assert 'returned None' in str(e)1211 c.get("/none")1212 assert "returned None" in str(e)12131214 with pytest.raises(TypeError) as e:1225 c.get('/small_tuple')1226 assert 'tuple must have the form' in str(e)1215 c.get("/small_tuple")1216 assert "tuple must have the form" in str(e)12171228 pytest.raises(TypeError, c.get, '/large_tuple')1218 pytest.raises(TypeError, c.get, "/large_tuple")12191220 with pytest.raises(TypeError) as e:1231 c.get('/bad_type')1232 assert 'it was a bool' in str(e)1221 c.get("/bad_type")1222 assert "it was a bool" in str(e)12231234 pytest.raises(TypeError, c.get, '/bad_wsgi')1224 pytest.raises(TypeError, c.get, "/bad_wsgi")122512261227def test_make_response(app, req_ctx):1228 rv = flask.make_response()1229 assert rv.status_code == 2001240 assert rv.data == b''1241 assert rv.mimetype == 'text/html'1230 assert rv.data == b""1231 assert rv.mimetype == "text/html"12321243 rv = flask.make_response('Awesome')1233 rv = flask.make_response("Awesome")1234 assert rv.status_code == 2001245 assert rv.data == b'Awesome'1246 assert rv.mimetype == 'text/html'1235 assert rv.data == b"Awesome"1236 assert rv.mimetype == "text/html"12371248 rv = flask.make_response('W00t', 404)1238 rv = flask.make_response("W00t", 404)1239 assert rv.status_code == 4041250 assert rv.data == b'W00t'1251 assert rv.mimetype == 'text/html'1240 assert rv.data == b"W00t"1241 assert rv.mimetype == "text/html"124212431244def test_make_response_with_response_instance(app, req_ctx):1255 rv = flask.make_response(1256 flask.jsonify({'msg': 'W00t'}), 400)1245 rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1246 assert rv.status_code == 4001247 assert rv.data == b'{"msg":"W00t"}\n'1259 assert rv.mimetype == 'application/json'1248 assert rv.mimetype == "application/json"12491261 rv = flask.make_response(1262 flask.Response(''), 400)1250 rv = flask.make_response(flask.Response(""), 400)1251 assert rv.status_code == 4001264 assert rv.data == b''1265 assert rv.mimetype == 'text/html'1252 assert rv.data == b""1253 assert rv.mimetype == "text/html"12541255 rv = flask.make_response(1268 flask.Response('', headers={'Content-Type': 'text/html'}),1269 400, [('X-Foo', 'bar')])1256 flask.Response("", headers={"Content-Type": "text/html"}),1257 400,1258 [("X-Foo", "bar")],1259 )1260 assert rv.status_code == 4001271 assert rv.headers['Content-Type'] == 'text/html'1272 assert rv.headers['X-Foo'] == 'bar'1261 assert rv.headers["Content-Type"] == "text/html"1262 assert rv.headers["X-Foo"] == "bar"126312641265def test_jsonify_no_prettyprint(app, req_ctx):1266 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})1267 compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n'1278 uncompressed_msg = {1279 "msg": {1280 "submsg": "W00t"1281 },1282 "msg2": "foobar"1283 }1268 uncompressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}12691285 rv = flask.make_response(1286 flask.jsonify(uncompressed_msg), 200)1270 rv = flask.make_response(flask.jsonify(uncompressed_msg), 200)1271 assert rv.data == compressed_msg127212731274def test_jsonify_prettyprint(app, req_ctx):1275 app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})1276 compressed_msg = {"msg": {"submsg": "W00t"}, "msg2": "foobar"}1293 pretty_response = \1277 pretty_response = (1278 b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n'1279 )12801296 rv = flask.make_response(1297 flask.jsonify(compressed_msg), 200)1281 rv = flask.make_response(flask.jsonify(compressed_msg), 200)1282 assert rv.data == pretty_response128312841285def test_jsonify_mimetype(app, req_ctx):1302 app.config.update({"JSONIFY_MIMETYPE": 'application/vnd.api+json'})1303 msg = {1304 "msg": {"submsg": "W00t"},1305 }1306 rv = flask.make_response(1307 flask.jsonify(msg), 200)1308 assert rv.mimetype == 'application/vnd.api+json'1286 app.config.update({"JSONIFY_MIMETYPE": "application/vnd.api+json"})1287 msg = {"msg": {"submsg": "W00t"}}1288 rv = flask.make_response(flask.jsonify(msg), 200)1289 assert rv.mimetype == "application/vnd.api+json"129012911292def test_jsonify_args_and_kwargs_check(app, req_ctx):1293 with pytest.raises(TypeError) as e:1313 flask.jsonify('fake args', kwargs='fake')1314 assert 'behavior undefined' in str(e.value)1294 flask.jsonify("fake args", kwargs="fake")1295 assert "behavior undefined" in str(e.value)129612971298def test_url_generation(app, req_ctx):1318 @app.route('/hello/<name>', methods=['POST'])1299 @app.route("/hello/<name>", methods=["POST"])1300 def hello():1301 pass13021322 assert flask.url_for('hello', name='test x') == '/hello/test%20x'1323 assert flask.url_for('hello', name='test x', _external=True) == \1324 'http://localhost/hello/test%20x'1303 assert flask.url_for("hello", name="test x") == "/hello/test%20x"1304 assert (1305 flask.url_for("hello", name="test x", _external=True)1306 == "http://localhost/hello/test%20x"1307 )130813091310def test_build_error_handler(app):1311 # Test base case, a URL which results in a BuildError.1312 with app.test_request_context():1330 pytest.raises(BuildError, flask.url_for, 'spam')1313 pytest.raises(BuildError, flask.url_for, "spam")13141315 # Verify the error is re-raised if not the current exception.1316 try:1317 with app.test_request_context():1335 flask.url_for('spam')1318 flask.url_for("spam")1319 except BuildError as err:1320 error = err1321 try:1339 raise RuntimeError('Test case where BuildError is not current.')1322 raise RuntimeError("Test case where BuildError is not current.")1323 except RuntimeError:1341 pytest.raises(1342 BuildError, app.handle_url_build_error, error, 'spam', {})1324 pytest.raises(BuildError, app.handle_url_build_error, error, "spam", {})13251326 # Test a custom handler.1327 def handler(error, endpoint, values):1328 # Just a test.1347 return '/test_handler/'1329 return "/test_handler/"13301331 app.url_build_error_handlers.append(handler)1332 with app.test_request_context():1351 assert flask.url_for('spam') == '/test_handler/'1333 assert flask.url_for("spam") == "/test_handler/"133413351336def test_build_error_handler_reraise(app):1337 # Test a custom handler which reraises the BuildError
2 unmodified lines
13401341 app.url_build_error_handlers.append(handler_raises_build_error)13421343 with app.test_request_context():1362 pytest.raises(BuildError, flask.url_for, 'not.existing')1344 pytest.raises(BuildError, flask.url_for, "not.existing")134513461347def test_url_for_passes_special_values_to_build_error_handler(app):1348 @app.url_build_error_handlers.append1349 def handler(error, endpoint, values):1350 assert values == {1369 '_external': False,1370 '_anchor': None,1371 '_method': None,1372 '_scheme': None,1351 "_external": False,1352 "_anchor": None,1353 "_method": None,1354 "_scheme": None,1355 }1374 return 'handled'1356 return "handled"13571358 with app.test_request_context():1377 flask.url_for('/')1359 flask.url_for("/")136013611362def test_custom_converters(app, client):1363 from werkzeug.routing import BaseConverter13641365 class ListConverter(BaseConverter):1366 def to_python(self, value):1385 return value.split(',')1367 return value.split(",")13681369 def to_url(self, value):1370 base_to_url = super(ListConverter, self).to_url1389 return ','.join(base_to_url(x) for x in value)1371 return ",".join(base_to_url(x) for x in value)13721391 app.url_map.converters['list'] = ListConverter1373 app.url_map.converters["list"] = ListConverter13741393 @app.route('/<list:args>')1375 @app.route("/<list:args>")1376 def index(args):1395 return '|'.join(args)1377 return "|".join(args)13781397 assert client.get('/1,2,3').data == b'1|2|3'1379 assert client.get("/1,2,3").data == b"1|2|3"138013811382def test_static_files(app, client):1401 rv = client.get('/static/index.html')1383 rv = client.get("/static/index.html")1384 assert rv.status_code == 2001403 assert rv.data.strip() == b'<h1>Hello World!</h1>'1385 assert rv.data.strip() == b"<h1>Hello World!</h1>"1386 with app.test_request_context():1405 assert flask.url_for('static', filename='index.html') == \1406 '/static/index.html'1387 assert flask.url_for("static", filename="index.html") == "/static/index.html"1388 rv.close()138913901391def test_static_url_path():1411 app = flask.Flask(__name__, static_url_path='/foo')1392 app = flask.Flask(__name__, static_url_path="/foo")1393 app.testing = True1413 rv = app.test_client().get('/foo/index.html')1394 rv = app.test_client().get("/foo/index.html")1395 assert rv.status_code == 2001396 rv.close()13971398 with app.test_request_context():1418 assert flask.url_for('static', filename='index.html') == '/foo/index.html'1399 assert flask.url_for("static", filename="index.html") == "/foo/index.html"140014011402def test_static_route_with_host_matching():1422 app = flask.Flask(__name__, host_matching=True, static_host='example.com')1403 app = flask.Flask(__name__, host_matching=True, static_host="example.com")1404 c = app.test_client()1424 rv = c.get('http://example.com/static/index.html')1405 rv = c.get("http://example.com/static/index.html")1406 assert rv.status_code == 2001407 rv.close()1408 with app.test_request_context():1428 rv = flask.url_for('static', filename='index.html', _external=True)1429 assert rv == 'http://example.com/static/index.html'1409 rv = flask.url_for("static", filename="index.html", _external=True)1410 assert rv == "http://example.com/static/index.html"1411 # Providing static_host without host_matching=True should error.1412 with pytest.raises(Exception):1432 flask.Flask(__name__, static_host='example.com')1413 flask.Flask(__name__, static_host="example.com")1414 # Providing host_matching=True with static_folder but without static_host should error.1415 with pytest.raises(Exception):1416 flask.Flask(__name__, host_matching=True)1417 # Providing host_matching=True without static_host but with static_folder=None should not error.1418 flask.Flask(__name__, host_matching=True, static_folder=None)141914201421def test_request_locals():1441 assert repr(flask.g) == '<LocalProxy unbound>'1422 assert repr(flask.g) == "<LocalProxy unbound>"1423 assert not flask.g142414251426def test_test_app_proper_environ():1427 app = flask.Flask(__name__, subdomain_matching=True)1447 app.config.update(1448 SERVER_NAME='localhost.localdomain:5000'1449 )1428 app.config.update(SERVER_NAME="localhost.localdomain:5000")1429 client = app.test_client()14301452 @app.route('/')1431 @app.route("/")1432 def index():1454 return 'Foo'1433 return "Foo"14341456 @app.route('/', subdomain='foo')1435 @app.route("/", subdomain="foo")1436 def subdomain():1458 return 'Foo SubDomain'1437 return "Foo SubDomain"14381460 rv = client.get('/')1461 assert rv.data == b'Foo'1439 rv = client.get("/")1440 assert rv.data == b"Foo"14411463 rv = client.get('/', 'http://localhost.localdomain:5000')1464 assert rv.data == b'Foo'1442 rv = client.get("/", "http://localhost.localdomain:5000")1443 assert rv.data == b"Foo"14441466 rv = client.get('/', 'https://localhost.localdomain:5000')1467 assert rv.data == b'Foo'1445 rv = client.get("/", "https://localhost.localdomain:5000")1446 assert rv.data == b"Foo"14471469 app.config.update(SERVER_NAME='localhost.localdomain')1470 rv = client.get('/', 'https://localhost.localdomain')1471 assert rv.data == b'Foo'1448 app.config.update(SERVER_NAME="localhost.localdomain")1449 rv = client.get("/", "https://localhost.localdomain")1450 assert rv.data == b"Foo"14511452 try:1474 app.config.update(SERVER_NAME='localhost.localdomain:443')1475 rv = client.get('/', 'https://localhost.localdomain')1453 app.config.update(SERVER_NAME="localhost.localdomain:443")1454 rv = client.get("/", "https://localhost.localdomain")1455 # Werkzeug 0.81456 assert rv.status_code == 4041457 except ValueError as e:1458 # Werkzeug 0.7
3 unmodified lines
1462 "server name from the WSGI environment ('localhost.localdomain')"1463 )14641465 try:1487 app.config.update(SERVER_NAME='localhost.localdomain')1488 rv = client.get('/', 'http://foo.localhost')1466 app.config.update(SERVER_NAME="localhost.localdomain")1467 rv = client.get("/", "http://foo.localhost")1468 # Werkzeug 0.81469 assert rv.status_code == 4041470 except ValueError as e:1471 # Werkzeug 0.7
2 unmodified lines
1474 "('localhost.localdomain') does not match the "1475 "server name from the WSGI environment ('foo.localhost')"1476 )14771499 rv = client.get('/', 'http://foo.localhost.localdomain')1500 assert rv.data == b'Foo SubDomain'1478 rv = client.get("/", "http://foo.localhost.localdomain")1479 assert rv.data == b"Foo SubDomain"148014811482def test_exception_propagation(app, client):1483 def apprunner(config_key):15051506 @app.route('/')1484 @app.route("/")1485 def index():1486 1 // 014871488 if config_key is not None:1489 app.config[config_key] = True1490 with pytest.raises(Exception):1513 client.get('/')1491 client.get("/")1492 else:1515 assert client.get('/').status_code == 5001493 assert client.get("/").status_code == 50014941495 # we have to run this test in an isolated thread because if the1496 # debug flag is set to true and an exception happens the context is1497 # not torn down. This causes other tests that run after this fail1498 # when they expect no exception on the stack.1521 for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None:1499 for config_key in "TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None:1500 t = Thread(target=apprunner, args=(config_key,))1501 t.start()1502 t.join()150315041527@pytest.mark.parametrize('debug', [True, False])1528@pytest.mark.parametrize('use_debugger', [True, False])1529@pytest.mark.parametrize('use_reloader', [True, False])1530@pytest.mark.parametrize('propagate_exceptions', [None, True, False])1531def test_werkzeug_passthrough_errors(monkeypatch, debug, use_debugger,1532 use_reloader, propagate_exceptions, app):1505@pytest.mark.parametrize("debug", [True, False])1506@pytest.mark.parametrize("use_debugger", [True, False])1507@pytest.mark.parametrize("use_reloader", [True, False])1508@pytest.mark.parametrize("propagate_exceptions", [None, True, False])1509def test_werkzeug_passthrough_errors(1510 monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app1511):1512 rv = {}15131514 # Mocks werkzeug.serving.run_simple method1515 def run_simple_mock(*args, **kwargs):1537 rv['passthrough_errors'] = kwargs.get('passthrough_errors')1516 rv["passthrough_errors"] = kwargs.get("passthrough_errors")15171539 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1540 app.config['PROPAGATE_EXCEPTIONS'] = propagate_exceptions1518 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1519 app.config["PROPAGATE_EXCEPTIONS"] = propagate_exceptions1520 app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)152115221523def test_max_content_length(app, client):1545 app.config['MAX_CONTENT_LENGTH'] = 641524 app.config["MAX_CONTENT_LENGTH"] = 6415251526 @app.before_request1527 def always_first():1549 flask.request.form['myfile']1528 flask.request.form["myfile"]1529 assert False15301552 @app.route('/accept', methods=['POST'])1531 @app.route("/accept", methods=["POST"])1532 def accept_file():1554 flask.request.form['myfile']1533 flask.request.form["myfile"]1534 assert False15351536 @app.errorhandler(413)1537 def catcher(error):1559 return '42'1538 return "42"15391561 rv = client.post('/accept', data={'myfile': 'foo' * 100})1562 assert rv.data == b'42'1540 rv = client.post("/accept", data={"myfile": "foo" * 100})1541 assert rv.data == b"42"154215431544def test_url_processors(app, client):15661545 @app.url_defaults1546 def add_language_code(endpoint, values):1569 if flask.g.lang_code is not None and \1570 app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):1571 values.setdefault('lang_code', flask.g.lang_code)1547 if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(1548 endpoint, "lang_code"1549 ):1550 values.setdefault("lang_code", flask.g.lang_code)15511552 @app.url_value_preprocessor1553 def pull_lang_code(endpoint, values):1575 flask.g.lang_code = values.pop('lang_code', None)1554 flask.g.lang_code = values.pop("lang_code", None)15551577 @app.route('/<lang_code>/')1556 @app.route("/<lang_code>/")1557 def index():1579 return flask.url_for('about')1558 return flask.url_for("about")15591581 @app.route('/<lang_code>/about')1560 @app.route("/<lang_code>/about")1561 def about():1583 return flask.url_for('something_else')1562 return flask.url_for("something_else")15631585 @app.route('/foo')1564 @app.route("/foo")1565 def something_else():1587 return flask.url_for('about', lang_code='en')1566 return flask.url_for("about", lang_code="en")15671589 assert client.get('/de/').data == b'/de/about'1590 assert client.get('/de/about').data == b'/foo'1591 assert client.get('/foo').data == b'/en/about'1568 assert client.get("/de/").data == b"/de/about"1569 assert client.get("/de/about").data == b"/foo"1570 assert client.get("/foo").data == b"/en/about"157115721573def test_inject_blueprint_url_defaults(app):1595 bp = flask.Blueprint('foo.bar.baz', __name__,1596 template_folder='template')1574 bp = flask.Blueprint("foo.bar.baz", __name__, template_folder="template")15751576 @bp.url_defaults1577 def bp_defaults(endpoint, values):1600 values['page'] = 'login'1578 values["page"] = "login"15791602 @bp.route('/<page>')1580 @bp.route("/<page>")1581 def view(page):1582 pass15831584 app.register_blueprint(bp)15851586 values = dict()1609 app.inject_url_defaults('foo.bar.baz.view', values)1610 expected = dict(page='login')1587 app.inject_url_defaults("foo.bar.baz.view", values)1588 expected = dict(page="login")1589 assert values == expected15901613 with app.test_request_context('/somepage'):1614 url = flask.url_for('foo.bar.baz.view')1615 expected = '/login'1591 with app.test_request_context("/somepage"):1592 url = flask.url_for("foo.bar.baz.view")1593 expected = "/login"1594 assert url == expected159515961597def test_nonascii_pathinfo(app, client):1620 @app.route(u'/киртест')1598 @app.route(u"/киртест")1599 def index():1622 return 'Hello World!'1600 return "Hello World!"16011624 rv = client.get(u'/киртест')1625 assert rv.data == b'Hello World!'1602 rv = client.get(u"/киртест")1603 assert rv.data == b"Hello World!"160416051606def test_debug_mode_complains_after_first_request(app, client):1607 app.debug = True16081631 @app.route('/')1609 @app.route("/")1610 def index():1633 return 'Awesome'1611 return "Awesome"16121613 assert not app.got_first_request1636 assert client.get('/').data == b'Awesome'1614 assert client.get("/").data == b"Awesome"1615 with pytest.raises(AssertionError) as e:16161638 @app.route('/foo')1617 @app.route("/foo")1618 def broken():1640 return 'Meh'1641 assert 'A setup function was called' in str(e)1619 return "Meh"16201621 assert "A setup function was called" in str(e)16221623 app.debug = False16241645 @app.route('/foo')1625 @app.route("/foo")1626 def working():1647 return 'Meh'1627 return "Meh"16281649 assert client.get('/foo').data == b'Meh'1629 assert client.get("/foo").data == b"Meh"1630 assert app.got_first_request163116321633def test_before_first_request_functions(app, client):
2 unmodified lines
1636 @app.before_first_request1637 def foo():1638 got.append(42)16391660 client.get('/')1640 client.get("/")1641 assert got == [42]1662 client.get('/')1642 client.get("/")1643 assert got == [42]1644 assert app.got_first_request16451646
18 unmodified lines
16651666def test_routing_redirect_debugging(app, client):1667 app.debug = True16681689 @app.route('/foo/', methods=['GET', 'POST'])1669 @app.route("/foo/", methods=["GET", "POST"])1670 def foo():1691 return 'success'1671 return "success"16721673 with client:1674 with pytest.raises(AssertionError) as e:1695 client.post('/foo', data={})1696 assert 'http://localhost/foo/' in str(e)1697 assert ('Make sure to directly send '1698 'your POST-request to this URL') in str(e)1675 client.post("/foo", data={})1676 assert "http://localhost/foo/" in str(e)1677 assert ("Make sure to directly send " "your POST-request to this URL") in str(e)16781700 rv = client.get('/foo', data={}, follow_redirects=True)1701 assert rv.data == b'success'1679 rv = client.get("/foo", data={}, follow_redirects=True)1680 assert rv.data == b"success"16811682 app.debug = False1683 with client:1705 rv = client.post('/foo', data={}, follow_redirects=True)1706 assert rv.data == b'success'1684 rv = client.post("/foo", data={}, follow_redirects=True)1685 assert rv.data == b"success"168616871688def test_route_decorator_custom_endpoint(app, client):1689 app.debug = True16901712 @app.route('/foo/')1691 @app.route("/foo/")1692 def foo():1693 return flask.request.endpoint16941716 @app.route('/bar/', endpoint='bar')1695 @app.route("/bar/", endpoint="bar")1696 def for_bar():1697 return flask.request.endpoint16981720 @app.route('/bar/123', endpoint='123')1699 @app.route("/bar/123", endpoint="123")1700 def for_bar_foo():1701 return flask.request.endpoint17021703 with app.test_request_context():1725 assert flask.url_for('foo') == '/foo/'1726 assert flask.url_for('bar') == '/bar/'1727 assert flask.url_for('123') == '/bar/123'1704 assert flask.url_for("foo") == "/foo/"1705 assert flask.url_for("bar") == "/bar/"1706 assert flask.url_for("123") == "/bar/123"17071729 assert client.get('/foo/').data == b'foo'1730 assert client.get('/bar/').data == b'bar'1731 assert client.get('/bar/123').data == b'123'1708 assert client.get("/foo/").data == b"foo"1709 assert client.get("/bar/").data == b"bar"1710 assert client.get("/bar/123").data == b"123"171117121713def test_preserve_only_once(app, client):1714 app.debug = True17151737 @app.route('/fail')1716 @app.route("/fail")1717 def fail_func():1718 1 // 017191720 for x in range(3):1721 with pytest.raises(ZeroDivisionError):1743 client.get('/fail')1722 client.get("/fail")17231724 assert flask._request_ctx_stack.top is not None1725 assert flask._app_ctx_stack.top is not None1726 # implicit appctx disappears too
5 unmodified lines
1732def test_preserve_remembers_exception(app, client):1733 app.debug = True1734 errors = []17351757 @app.route('/fail')1736 @app.route("/fail")1737 def fail_func():1738 1 // 017391761 @app.route('/success')1740 @app.route("/success")1741 def success_func():1763 return 'Okay'1742 return "Okay"17431744 @app.teardown_request1745 def teardown_handler(exc):1746 errors.append(exc)17471748 # After this failure we did not yet call the teardown handler1749 with pytest.raises(ZeroDivisionError):1771 client.get('/fail')1750 client.get("/fail")1751 assert errors == []17521753 # But this request triggers it, and it's an error1775 client.get('/success')1754 client.get("/success")1755 assert len(errors) == 21756 assert isinstance(errors[0], ZeroDivisionError)17571758 # At this point another request does nothing.1780 client.get('/success')1759 client.get("/success")1760 assert len(errors) == 31761 assert errors[1] is None176217631764def test_get_method_on_g(app_ctx):1786 assert flask.g.get('x') is None1787 assert flask.g.get('x', 11) == 111765 assert flask.g.get("x") is None1766 assert flask.g.get("x", 11) == 111767 flask.g.x = 421789 assert flask.g.get('x') == 421768 assert flask.g.get("x") == 421769 assert flask.g.x == 42177017711772def test_g_iteration_protocol(app_ctx):1773 flask.g.foo = 231774 flask.g.bar = 421796 assert 'foo' in flask.g1797 assert 'foos' not in flask.g1798 assert sorted(flask.g) == ['bar', 'foo']1775 assert "foo" in flask.g1776 assert "foos" not in flask.g1777 assert sorted(flask.g) == ["bar", "foo"]177817791780def test_subdomain_basic_support():1781 app = flask.Flask(__name__, subdomain_matching=True)1803 app.config['SERVER_NAME'] = 'localhost.localdomain'1782 app.config["SERVER_NAME"] = "localhost.localdomain"1783 client = app.test_client()17841806 @app.route('/')1785 @app.route("/")1786 def normal_index():1808 return 'normal index'1787 return "normal index"17881810 @app.route('/', subdomain='test')1789 @app.route("/", subdomain="test")1790 def test_index():1812 return 'test index'1791 return "test index"17921814 rv = client.get('/', 'http://localhost.localdomain/')1815 assert rv.data == b'normal index'1793 rv = client.get("/", "http://localhost.localdomain/")1794 assert rv.data == b"normal index"17951817 rv = client.get('/', 'http://test.localhost.localdomain/')1818 assert rv.data == b'test index'1796 rv = client.get("/", "http://test.localhost.localdomain/")1797 assert rv.data == b"test index"179817991800def test_subdomain_matching():1801 app = flask.Flask(__name__, subdomain_matching=True)1802 client = app.test_client()1824 app.config['SERVER_NAME'] = 'localhost.localdomain'1803 app.config["SERVER_NAME"] = "localhost.localdomain"18041826 @app.route('/', subdomain='<user>')1805 @app.route("/", subdomain="<user>")1806 def index(user):1828 return 'index for %s' % user1807 return "index for %s" % user18081830 rv = client.get('/', 'http://mitsuhiko.localhost.localdomain/')1831 assert rv.data == b'index for mitsuhiko'1809 rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1810 assert rv.data == b"index for mitsuhiko"181118121813def test_subdomain_matching_with_ports():1814 app = flask.Flask(__name__, subdomain_matching=True)1836 app.config['SERVER_NAME'] = 'localhost.localdomain:3000'1815 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1816 client = app.test_client()18171839 @app.route('/', subdomain='<user>')1818 @app.route("/", subdomain="<user>")1819 def index(user):1841 return 'index for %s' % user1820 return "index for %s" % user18211843 rv = client.get('/', 'http://mitsuhiko.localhost.localdomain:3000/')1844 assert rv.data == b'index for mitsuhiko'1822 rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1823 assert rv.data == b"index for mitsuhiko"182418251847@pytest.mark.parametrize('matching', (False, True))1826@pytest.mark.parametrize("matching", (False, True))1827def test_subdomain_matching_other_name(matching):1828 app = flask.Flask(__name__, subdomain_matching=matching)1850 app.config['SERVER_NAME'] = 'localhost.localdomain:3000'1829 app.config["SERVER_NAME"] = "localhost.localdomain:3000"1830 client = app.test_client()18311853 @app.route('/')1832 @app.route("/")1833 def index():1855 return '', 2041834 return "", 20418351836 # ip address can't match name1858 rv = client.get('/', 'http://127.0.0.1:3000/')1837 rv = client.get("/", "http://127.0.0.1:3000/")1838 assert rv.status_code == 404 if matching else 20418391840 # allow all subdomains if matching is disabled1862 rv = client.get('/', 'http://www.localhost.localdomain:3000/')1841 rv = client.get("/", "http://www.localhost.localdomain:3000/")1842 assert rv.status_code == 404 if matching else 204184318441845def test_multi_route_rules(app, client):1867 @app.route('/')1868 @app.route('/<test>/')1869 def index(test='a'):1846 @app.route("/")1847 @app.route("/<test>/")1848 def index(test="a"):1849 return test18501872 rv = client.open('/')1873 assert rv.data == b'a'1874 rv = client.open('/b/')1875 assert rv.data == b'b'1851 rv = client.open("/")1852 assert rv.data == b"a"1853 rv = client.open("/b/")1854 assert rv.data == b"b"185518561857def test_multi_route_class_views(app, client):1858 class View(object):1859 def __init__(self, app):1881 app.add_url_rule('/', 'index', self.index)1882 app.add_url_rule('/<test>/', 'index', self.index)1860 app.add_url_rule("/", "index", self.index)1861 app.add_url_rule("/<test>/", "index", self.index)18621884 def index(self, test='a'):1863 def index(self, test="a"):1864 return test18651866 _ = View(app)1888 rv = client.open('/')1889 assert rv.data == b'a'1890 rv = client.open('/b/')1891 assert rv.data == b'b'1867 rv = client.open("/")1868 assert rv.data == b"a"1869 rv = client.open("/b/")1870 assert rv.data == b"b"187118721873def test_run_defaults(monkeypatch, app):1874 rv = {}18751876 # Mocks werkzeug.serving.run_simple method1877 def run_simple_mock(*args, **kwargs):1899 rv['result'] = 'running...'1878 rv["result"] = "running..."18791901 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1880 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1881 app.run()1903 assert rv['result'] == 'running...'1882 assert rv["result"] == "running..."188318841885def test_run_server_port(monkeypatch, app):1886 rv = {}18871888 # Mocks werkzeug.serving.run_simple method1889 def run_simple_mock(hostname, port, application, *args, **kwargs):1911 rv['result'] = 'running on %s:%s ...' % (hostname, port)1890 rv["result"] = "running on %s:%s ..." % (hostname, port)18911913 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1914 hostname, port = 'localhost', 80001892 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1893 hostname, port = "localhost", 80001894 app.run(hostname, port, debug=True)1916 assert rv['result'] == 'running on %s:%s ...' % (hostname, port)1895 assert rv["result"] == "running on %s:%s ..." % (hostname, port)189618971919@pytest.mark.parametrize('host,port,expect_host,expect_port', (1920 (None, None, 'pocoo.org', 8080),1921 ('localhost', None, 'localhost', 8080),1922 (None, 80, 'pocoo.org', 80),1923 ('localhost', 80, 'localhost', 80),1924))1898@pytest.mark.parametrize(1899 "host,port,expect_host,expect_port",1900 (1901 (None, None, "pocoo.org", 8080),1902 ("localhost", None, "localhost", 8080),1903 (None, 80, "pocoo.org", 80),1904 ("localhost", 80, "localhost", 80),1905 ),1906)1907def test_run_from_config(monkeypatch, host, port, expect_host, expect_port, app):1908 def run_simple_mock(hostname, port, *args, **kwargs):1909 assert hostname == expect_host1910 assert port == expect_port19111930 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)1931 app.config['SERVER_NAME'] = 'pocoo.org:8080'1912 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1913 app.config["SERVER_NAME"] = "pocoo.org:8080"1914 app.run(host, port)191519161917def test_max_cookie_size(app, client, recwarn):1936 app.config['MAX_COOKIE_SIZE'] = 1001918 app.config["MAX_COOKIE_SIZE"] = 10019191920 # outside app context, default to Werkzeug static value,1921 # which is also the default config1922 response = flask.Response()1941 default = flask.Flask.default_config['MAX_COOKIE_SIZE']1923 default = flask.Flask.default_config["MAX_COOKIE_SIZE"]1924 assert response.max_cookie_size == default19251926 # inside app context, use app config1927 with app.app_context():1928 assert flask.Response().max_cookie_size == 10019291948 @app.route('/')1930 @app.route("/")1931 def index():1950 r = flask.Response('', status=204)1951 r.set_cookie('foo', 'bar' * 100)1932 r = flask.Response("", status=204)1933 r.set_cookie("foo", "bar" * 100)1934 return r19351954 client.get('/')1936 client.get("/")1937 assert len(recwarn) == 11938 w = recwarn.pop()1957 assert 'cookie is too large' in str(w.message)1939 assert "cookie is too large" in str(w.message)19401959 app.config['MAX_COOKIE_SIZE'] = 01941 app.config["MAX_COOKIE_SIZE"] = 019421961 client.get('/')1943 client.get("/")1944 assert len(recwarn) == 0
modified:tests/test_blueprints.py+320 added-312 removed
18 unmodified lines
19from jinja2 import TemplateNotFound202122def test_blueprint_specific_error_handling(app, client):23 frontend = flask.Blueprint('frontend', __name__)24 backend = flask.Blueprint('backend', __name__)25 sideend = flask.Blueprint('sideend', __name__)23 frontend = flask.Blueprint("frontend", __name__)24 backend = flask.Blueprint("backend", __name__)25 sideend = flask.Blueprint("sideend", __name__)2627 @frontend.errorhandler(403)28 def frontend_forbidden(e):29 return 'frontend says no', 40329 return "frontend says no", 4033031 @frontend.route('/frontend-no')31 @frontend.route("/frontend-no")32 def frontend_no():33 flask.abort(403)3435 @backend.errorhandler(403)36 def backend_forbidden(e):37 return 'backend says no', 40337 return "backend says no", 4033839 @backend.route('/backend-no')39 @backend.route("/backend-no")40 def backend_no():41 flask.abort(403)4243 @sideend.route('/what-is-a-sideend')43 @sideend.route("/what-is-a-sideend")44 def sideend_no():45 flask.abort(403)4647 app.register_blueprint(frontend)
1 unmodified line
49 app.register_blueprint(sideend)5051 @app.errorhandler(403)52 def app_forbidden(e):53 return 'application itself says no', 40353 return "application itself says no", 4035455 assert client.get('/frontend-no').data == b'frontend says no'56 assert client.get('/backend-no').data == b'backend says no'57 assert client.get('/what-is-a-sideend').data == b'application itself says no'55 assert client.get("/frontend-no").data == b"frontend says no"56 assert client.get("/backend-no").data == b"backend says no"57 assert client.get("/what-is-a-sideend").data == b"application itself says no"585960def test_blueprint_specific_user_error_handling(app, client):61 class MyDecoratorException(Exception):
1 unmodified line
6364 class MyFunctionException(Exception):65 pass6667 blue = flask.Blueprint('blue', __name__)67 blue = flask.Blueprint("blue", __name__)6869 @blue.errorhandler(MyDecoratorException)70 def my_decorator_exception_handler(e):71 assert isinstance(e, MyDecoratorException)72 return 'boom'72 return "boom"7374 def my_function_exception_handler(e):75 assert isinstance(e, MyFunctionException)76 return 'bam'76 return "bam"7778 blue.register_error_handler(MyFunctionException, my_function_exception_handler)7980 @blue.route('/decorator')80 @blue.route("/decorator")81 def blue_deco_test():82 raise MyDecoratorException()8384 @blue.route('/function')84 @blue.route("/function")85 def blue_func_test():86 raise MyFunctionException()8788 app.register_blueprint(blue)8990 assert client.get('/decorator').data == b'boom'91 assert client.get('/function').data == b'bam'90 assert client.get("/decorator").data == b"boom"91 assert client.get("/function").data == b"bam"929394def test_blueprint_app_error_handling(app, client):95 errors = flask.Blueprint('errors', __name__)95 errors = flask.Blueprint("errors", __name__)9697 @errors.app_errorhandler(403)98 def forbidden_handler(e):99 return 'you shall not pass', 40399 return "you shall not pass", 403100101 @app.route('/forbidden')101 @app.route("/forbidden")102 def app_forbidden():103 flask.abort(403)104105 forbidden_bp = flask.Blueprint('forbidden_bp', __name__)105 forbidden_bp = flask.Blueprint("forbidden_bp", __name__)106107 @forbidden_bp.route('/nope')107 @forbidden_bp.route("/nope")108 def bp_forbidden():109 flask.abort(403)110111 app.register_blueprint(errors)112 app.register_blueprint(forbidden_bp)113114 assert client.get('/forbidden').data == b'you shall not pass'115 assert client.get('/nope').data == b'you shall not pass'114 assert client.get("/forbidden").data == b"you shall not pass"115 assert client.get("/nope").data == b"you shall not pass"116117118@pytest.mark.parametrize(('prefix', 'rule', 'url'), (119 ('', '/', '/'),120 ('/', '', '/'),121 ('/', '/', '/'),122 ('/foo', '', '/foo'),123 ('/foo/', '', '/foo/'),124 ('', '/bar', '/bar'),125 ('/foo/', '/bar', '/foo/bar'),126 ('/foo/', 'bar', '/foo/bar'),127 ('/foo', '/bar', '/foo/bar'),128 ('/foo/', '//bar', '/foo/bar'),129 ('/foo//', '/bar', '/foo/bar'),130))118@pytest.mark.parametrize(119 ("prefix", "rule", "url"),120 (121 ("", "/", "/"),122 ("/", "", "/"),123 ("/", "/", "/"),124 ("/foo", "", "/foo"),125 ("/foo/", "", "/foo/"),126 ("", "/bar", "/bar"),127 ("/foo/", "/bar", "/foo/bar"),128 ("/foo/", "bar", "/foo/bar"),129 ("/foo", "/bar", "/foo/bar"),130 ("/foo/", "//bar", "/foo/bar"),131 ("/foo//", "/bar", "/foo/bar"),132 ),133)134def test_blueprint_prefix_slash(app, client, prefix, rule, url):132 bp = flask.Blueprint('test', __name__, url_prefix=prefix)135 bp = flask.Blueprint("test", __name__, url_prefix=prefix)136137 @bp.route(rule)138 def index():136 return '', 204139 return "", 204140141 app.register_blueprint(bp)142 assert client.get(url).status_code == 204143144145def test_blueprint_url_defaults(app, client):143 bp = flask.Blueprint('test', __name__)146 bp = flask.Blueprint("test", __name__)147145 @bp.route('/foo', defaults={'baz': 42})148 @bp.route("/foo", defaults={"baz": 42})149 def foo(bar, baz):147 return '%s/%d' % (bar, baz)150 return "%s/%d" % (bar, baz)151149 @bp.route('/bar')152 @bp.route("/bar")153 def bar(bar):154 return text_type(bar)155153 app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23})154 app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19})156 app.register_blueprint(bp, url_prefix="/1", url_defaults={"bar": 23})157 app.register_blueprint(bp, url_prefix="/2", url_defaults={"bar": 19})158156 assert client.get('/1/foo').data == b'23/42'157 assert client.get('/2/foo').data == b'19/42'158 assert client.get('/1/bar').data == b'23'159 assert client.get('/2/bar').data == b'19'159 assert client.get("/1/foo").data == b"23/42"160 assert client.get("/2/foo").data == b"19/42"161 assert client.get("/1/bar").data == b"23"162 assert client.get("/2/bar").data == b"19"163164165def test_blueprint_url_processors(app, client):163 bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')166 bp = flask.Blueprint("frontend", __name__, url_prefix="/<lang_code>")167168 @bp.url_defaults169 def add_language_code(endpoint, values):167 values.setdefault('lang_code', flask.g.lang_code)170 values.setdefault("lang_code", flask.g.lang_code)171172 @bp.url_value_preprocessor173 def pull_lang_code(endpoint, values):171 flask.g.lang_code = values.pop('lang_code')174 flask.g.lang_code = values.pop("lang_code")175173 @bp.route('/')176 @bp.route("/")177 def index():175 return flask.url_for('.about')178 return flask.url_for(".about")179177 @bp.route('/about')180 @bp.route("/about")181 def about():179 return flask.url_for('.index')182 return flask.url_for(".index")183184 app.register_blueprint(bp)185183 assert client.get('/de/').data == b'/de/about'184 assert client.get('/de/about').data == b'/de/'186 assert client.get("/de/").data == b"/de/about"187 assert client.get("/de/about").data == b"/de/"188189190def test_templates_and_static(test_apps):191 from blueprintapp import app192193 client = app.test_client()194191 rv = client.get('/')192 assert rv.data == b'Hello from the Frontend'193 rv = client.get('/admin/')194 assert rv.data == b'Hello from the Admin'195 rv = client.get('/admin/index2')196 assert rv.data == b'Hello from the Admin'197 rv = client.get('/admin/static/test.txt')198 assert rv.data.strip() == b'Admin File'195 rv = client.get("/")196 assert rv.data == b"Hello from the Frontend"197 rv = client.get("/admin/")198 assert rv.data == b"Hello from the Admin"199 rv = client.get("/admin/index2")200 assert rv.data == b"Hello from the Admin"201 rv = client.get("/admin/static/test.txt")202 assert rv.data.strip() == b"Admin File"203 rv.close()200 rv = client.get('/admin/static/css/test.css')201 assert rv.data.strip() == b'/* nested file */'204 rv = client.get("/admin/static/css/test.css")205 assert rv.data.strip() == b"/* nested file */"206 rv.close()207208 # try/finally, in case other tests use this app for Blueprint tests.205 max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT']209 max_age_default = app.config["SEND_FILE_MAX_AGE_DEFAULT"]210 try:211 expected_max_age = 3600208 if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == expected_max_age:212 if app.config["SEND_FILE_MAX_AGE_DEFAULT"] == expected_max_age:213 expected_max_age = 7200210 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age211 rv = client.get('/admin/static/css/test.css')212 cc = parse_cache_control_header(rv.headers['Cache-Control'])214 app.config["SEND_FILE_MAX_AGE_DEFAULT"] = expected_max_age215 rv = client.get("/admin/static/css/test.css")216 cc = parse_cache_control_header(rv.headers["Cache-Control"])217 assert cc.max_age == expected_max_age218 rv.close()219 finally:216 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default220 app.config["SEND_FILE_MAX_AGE_DEFAULT"] = max_age_default221222 with app.test_request_context():219 assert flask.url_for('admin.static', filename='test.txt') == '/admin/static/test.txt'223 assert (224 flask.url_for("admin.static", filename="test.txt")225 == "/admin/static/test.txt"226 )227228 with app.test_request_context():229 with pytest.raises(TemplateNotFound) as e:223 flask.render_template('missing.html')224 assert e.value.name == 'missing.html'230 flask.render_template("missing.html")231 assert e.value.name == "missing.html"232233 with flask.Flask(__name__).test_request_context():227 assert flask.render_template('nested/nested.txt') == 'I\'m nested'234 assert flask.render_template("nested/nested.txt") == "I'm nested"235236237def test_default_static_cache_timeout(app):238 class MyBlueprint(flask.Blueprint):239 def get_send_file_max_age(self, filename):240 return 100241235 blueprint = MyBlueprint('blueprint', __name__, static_folder='static')242 blueprint = MyBlueprint("blueprint", __name__, static_folder="static")243 app.register_blueprint(blueprint)244245 # try/finally, in case other tests use this app for Blueprint tests.239 max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT']246 max_age_default = app.config["SEND_FILE_MAX_AGE_DEFAULT"]247 try:248 with app.test_request_context():249 unexpected_max_age = 3600243 if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == unexpected_max_age:250 if app.config["SEND_FILE_MAX_AGE_DEFAULT"] == unexpected_max_age:251 unexpected_max_age = 7200245 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = unexpected_max_age246 rv = blueprint.send_static_file('index.html')247 cc = parse_cache_control_header(rv.headers['Cache-Control'])252 app.config["SEND_FILE_MAX_AGE_DEFAULT"] = unexpected_max_age253 rv = blueprint.send_static_file("index.html")254 cc = parse_cache_control_header(rv.headers["Cache-Control"])255 assert cc.max_age == 100256 rv.close()257 finally:251 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default258 app.config["SEND_FILE_MAX_AGE_DEFAULT"] = max_age_default259260261def test_templates_list(test_apps):262 from blueprintapp import app263264 templates = sorted(app.jinja_env.list_templates())257 assert templates == ['admin/index.html', 'frontend/index.html']265 assert templates == ["admin/index.html", "frontend/index.html"]266267268def test_dotted_names(app, client):261 frontend = flask.Blueprint('myapp.frontend', __name__)262 backend = flask.Blueprint('myapp.backend', __name__)269 frontend = flask.Blueprint("myapp.frontend", __name__)270 backend = flask.Blueprint("myapp.backend", __name__)271264 @frontend.route('/fe')272 @frontend.route("/fe")273 def frontend_index():266 return flask.url_for('myapp.backend.backend_index')274 return flask.url_for("myapp.backend.backend_index")275268 @frontend.route('/fe2')276 @frontend.route("/fe2")277 def frontend_page2():270 return flask.url_for('.frontend_index')278 return flask.url_for(".frontend_index")279272 @backend.route('/be')280 @backend.route("/be")281 def backend_index():274 return flask.url_for('myapp.frontend.frontend_index')282 return flask.url_for("myapp.frontend.frontend_index")283284 app.register_blueprint(frontend)285 app.register_blueprint(backend)286279 assert client.get('/fe').data.strip() == b'/be'280 assert client.get('/fe2').data.strip() == b'/fe'281 assert client.get('/be').data.strip() == b'/fe'287 assert client.get("/fe").data.strip() == b"/be"288 assert client.get("/fe2").data.strip() == b"/fe"289 assert client.get("/be").data.strip() == b"/fe"290291292def test_dotted_names_from_app(app, client):285 test = flask.Blueprint('test', __name__)293 test = flask.Blueprint("test", __name__)294287 @app.route('/')295 @app.route("/")296 def app_index():289 return flask.url_for('test.index')297 return flask.url_for("test.index")298291 @test.route('/test/')299 @test.route("/test/")300 def index():293 return flask.url_for('app_index')301 return flask.url_for("app_index")302303 app.register_blueprint(test)304297 rv = client.get('/')298 assert rv.data == b'/test/'305 rv = client.get("/")306 assert rv.data == b"/test/"307308309def test_empty_url_defaults(app, client):302 bp = flask.Blueprint('bp', __name__)310 bp = flask.Blueprint("bp", __name__)311304 @bp.route('/', defaults={'page': 1})305 @bp.route('/page/<int:page>')312 @bp.route("/", defaults={"page": 1})313 @bp.route("/page/<int:page>")314 def something(page):315 return str(page)316317 app.register_blueprint(bp)318311 assert client.get('/').data == b'1'312 assert client.get('/page/2').data == b'2'319 assert client.get("/").data == b"1"320 assert client.get("/page/2").data == b"2"321322323def test_route_decorator_custom_endpoint(app, client):316 bp = flask.Blueprint('bp', __name__)324 bp = flask.Blueprint("bp", __name__)325318 @bp.route('/foo')326 @bp.route("/foo")327 def foo():328 return flask.request.endpoint329322 @bp.route('/bar', endpoint='bar')330 @bp.route("/bar", endpoint="bar")331 def foo_bar():332 return flask.request.endpoint333326 @bp.route('/bar/123', endpoint='123')334 @bp.route("/bar/123", endpoint="123")335 def foo_bar_foo():336 return flask.request.endpoint337330 @bp.route('/bar/foo')338 @bp.route("/bar/foo")339 def bar_foo():340 return flask.request.endpoint341334 app.register_blueprint(bp, url_prefix='/py')342 app.register_blueprint(bp, url_prefix="/py")343336 @app.route('/')344 @app.route("/")345 def index():346 return flask.request.endpoint347340 assert client.get('/').data == b'index'341 assert client.get('/py/foo').data == b'bp.foo'342 assert client.get('/py/bar').data == b'bp.bar'343 assert client.get('/py/bar/123').data == b'bp.123'344 assert client.get('/py/bar/foo').data == b'bp.bar_foo'348 assert client.get("/").data == b"index"349 assert client.get("/py/foo").data == b"bp.foo"350 assert client.get("/py/bar").data == b"bp.bar"351 assert client.get("/py/bar/123").data == b"bp.123"352 assert client.get("/py/bar/foo").data == b"bp.bar_foo"353354355def test_route_decorator_custom_endpoint_with_dots(app, client):348 bp = flask.Blueprint('bp', __name__)356 bp = flask.Blueprint("bp", __name__)357350 @bp.route('/foo')358 @bp.route("/foo")359 def foo():360 return flask.request.endpoint361362 try:355 @bp.route('/bar', endpoint='bar.bar')363364 @bp.route("/bar", endpoint="bar.bar")365 def foo_bar():366 return flask.request.endpoint367368 except AssertionError:369 pass370 else:361 raise AssertionError('expected AssertionError not raised')371 raise AssertionError("expected AssertionError not raised")372373 try:364 @bp.route('/bar/123', endpoint='bar.123')374375 @bp.route("/bar/123", endpoint="bar.123")376 def foo_bar_foo():377 return flask.request.endpoint378379 except AssertionError:380 pass381 else:370 raise AssertionError('expected AssertionError not raised')382 raise AssertionError("expected AssertionError not raised")383384 def foo_foo_foo():385 pass386387 pytest.raises(388 AssertionError,377 lambda: bp.add_url_rule(378 '/bar/123', endpoint='bar.123', view_func=foo_foo_foo379 )389 lambda: bp.add_url_rule("/bar/123", endpoint="bar.123", view_func=foo_foo_foo),390 )391392 pytest.raises(383 AssertionError,384 bp.route('/bar/123', endpoint='bar.123'),385 lambda: None393 AssertionError, bp.route("/bar/123", endpoint="bar.123"), lambda: None394 )395388 foo_foo_foo.__name__ = 'bar.123'396 foo_foo_foo.__name__ = "bar.123"397398 pytest.raises(391 AssertionError,392 lambda: bp.add_url_rule(393 '/bar/123', view_func=foo_foo_foo394 )399 AssertionError, lambda: bp.add_url_rule("/bar/123", view_func=foo_foo_foo)400 )401397 bp.add_url_rule('/bar/456', endpoint='foofoofoo', view_func=functools.partial(foo_foo_foo))402 bp.add_url_rule(403 "/bar/456", endpoint="foofoofoo", view_func=functools.partial(foo_foo_foo)404 )405399 app.register_blueprint(bp, url_prefix='/py')406 app.register_blueprint(bp, url_prefix="/py")407401 assert client.get('/py/foo').data == b'bp.foo'408 assert client.get("/py/foo").data == b"bp.foo"409 # The rule's didn't actually made it through403 rv = client.get('/py/bar')410 rv = client.get("/py/bar")411 assert rv.status_code == 404405 rv = client.get('/py/bar/123')412 rv = client.get("/py/bar/123")413 assert rv.status_code == 404414415416def test_endpoint_decorator(app, client):417 from werkzeug.routing import Rule411 app.url_map.add(Rule('/foo', endpoint='bar'))418413 bp = flask.Blueprint('bp', __name__)419 app.url_map.add(Rule("/foo", endpoint="bar"))420421 bp = flask.Blueprint("bp", __name__)422415 @bp.endpoint('bar')423 @bp.endpoint("bar")424 def foobar():425 return flask.request.endpoint426419 app.register_blueprint(bp, url_prefix='/bp_prefix')427 app.register_blueprint(bp, url_prefix="/bp_prefix")428421 assert client.get('/foo').data == b'bar'422 assert client.get('/bp_prefix/bar').status_code == 404429 assert client.get("/foo").data == b"bar"430 assert client.get("/bp_prefix/bar").status_code == 404431432433def test_template_filter(app):426 bp = flask.Blueprint('bp', __name__)434 bp = flask.Blueprint("bp", __name__)435436 @bp.app_template_filter()437 def my_reverse(s):438 return s[::-1]439432 app.register_blueprint(bp, url_prefix='/py')433 assert 'my_reverse' in app.jinja_env.filters.keys()434 assert app.jinja_env.filters['my_reverse'] == my_reverse435 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'440 app.register_blueprint(bp, url_prefix="/py")441 assert "my_reverse" in app.jinja_env.filters.keys()442 assert app.jinja_env.filters["my_reverse"] == my_reverse443 assert app.jinja_env.filters["my_reverse"]("abcd") == "dcba"444445446def test_add_template_filter(app):439 bp = flask.Blueprint('bp', __name__)447 bp = flask.Blueprint("bp", __name__)448449 def my_reverse(s):450 return s[::-1]451452 bp.add_app_template_filter(my_reverse)445 app.register_blueprint(bp, url_prefix='/py')446 assert 'my_reverse' in app.jinja_env.filters.keys()447 assert app.jinja_env.filters['my_reverse'] == my_reverse448 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'453 app.register_blueprint(bp, url_prefix="/py")454 assert "my_reverse" in app.jinja_env.filters.keys()455 assert app.jinja_env.filters["my_reverse"] == my_reverse456 assert app.jinja_env.filters["my_reverse"]("abcd") == "dcba"457458459def test_template_filter_with_name(app):452 bp = flask.Blueprint('bp', __name__)460 bp = flask.Blueprint("bp", __name__)461454 @bp.app_template_filter('strrev')462 @bp.app_template_filter("strrev")463 def my_reverse(s):464 return s[::-1]465458 app.register_blueprint(bp, url_prefix='/py')459 assert 'strrev' in app.jinja_env.filters.keys()460 assert app.jinja_env.filters['strrev'] == my_reverse461 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'466 app.register_blueprint(bp, url_prefix="/py")467 assert "strrev" in app.jinja_env.filters.keys()468 assert app.jinja_env.filters["strrev"] == my_reverse469 assert app.jinja_env.filters["strrev"]("abcd") == "dcba"470471472def test_add_template_filter_with_name(app):465 bp = flask.Blueprint('bp', __name__)473 bp = flask.Blueprint("bp", __name__)474475 def my_reverse(s):476 return s[::-1]477470 bp.add_app_template_filter(my_reverse, 'strrev')471 app.register_blueprint(bp, url_prefix='/py')472 assert 'strrev' in app.jinja_env.filters.keys()473 assert app.jinja_env.filters['strrev'] == my_reverse474 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'478 bp.add_app_template_filter(my_reverse, "strrev")479 app.register_blueprint(bp, url_prefix="/py")480 assert "strrev" in app.jinja_env.filters.keys()481 assert app.jinja_env.filters["strrev"] == my_reverse482 assert app.jinja_env.filters["strrev"]("abcd") == "dcba"483484485def test_template_filter_with_template(app, client):478 bp = flask.Blueprint('bp', __name__)486 bp = flask.Blueprint("bp", __name__)487488 @bp.app_template_filter()489 def super_reverse(s):490 return s[::-1]491484 app.register_blueprint(bp, url_prefix='/py')492 app.register_blueprint(bp, url_prefix="/py")493486 @app.route('/')494 @app.route("/")495 def index():488 return flask.render_template('template_filter.html', value='abcd')496 return flask.render_template("template_filter.html", value="abcd")497490 rv = client.get('/')491 assert rv.data == b'dcba'498 rv = client.get("/")499 assert rv.data == b"dcba"500501502def test_template_filter_after_route_with_template(app, client):495 @app.route('/')503 @app.route("/")504 def index():497 return flask.render_template('template_filter.html', value='abcd')505 return flask.render_template("template_filter.html", value="abcd")506499 bp = flask.Blueprint('bp', __name__)507 bp = flask.Blueprint("bp", __name__)508509 @bp.app_template_filter()510 def super_reverse(s):511 return s[::-1]512505 app.register_blueprint(bp, url_prefix='/py')506 rv = client.get('/')507 assert rv.data == b'dcba'513 app.register_blueprint(bp, url_prefix="/py")514 rv = client.get("/")515 assert rv.data == b"dcba"516517518def test_add_template_filter_with_template(app, client):511 bp = flask.Blueprint('bp', __name__)519 bp = flask.Blueprint("bp", __name__)520521 def super_reverse(s):522 return s[::-1]523524 bp.add_app_template_filter(super_reverse)517 app.register_blueprint(bp, url_prefix='/py')525 app.register_blueprint(bp, url_prefix="/py")526519 @app.route('/')527 @app.route("/")528 def index():521 return flask.render_template('template_filter.html', value='abcd')529 return flask.render_template("template_filter.html", value="abcd")530523 rv = client.get('/')524 assert rv.data == b'dcba'531 rv = client.get("/")532 assert rv.data == b"dcba"533534535def test_template_filter_with_name_and_template(app, client):528 bp = flask.Blueprint('bp', __name__)536 bp = flask.Blueprint("bp", __name__)537530 @bp.app_template_filter('super_reverse')538 @bp.app_template_filter("super_reverse")539 def my_reverse(s):540 return s[::-1]541534 app.register_blueprint(bp, url_prefix='/py')542 app.register_blueprint(bp, url_prefix="/py")543536 @app.route('/')544 @app.route("/")545 def index():538 return flask.render_template('template_filter.html', value='abcd')546 return flask.render_template("template_filter.html", value="abcd")547540 rv = client.get('/')541 assert rv.data == b'dcba'548 rv = client.get("/")549 assert rv.data == b"dcba"550551552def test_add_template_filter_with_name_and_template(app, client):545 bp = flask.Blueprint('bp', __name__)553 bp = flask.Blueprint("bp", __name__)554555 def my_reverse(s):556 return s[::-1]557550 bp.add_app_template_filter(my_reverse, 'super_reverse')551 app.register_blueprint(bp, url_prefix='/py')558 bp.add_app_template_filter(my_reverse, "super_reverse")559 app.register_blueprint(bp, url_prefix="/py")560553 @app.route('/')561 @app.route("/")562 def index():555 return flask.render_template('template_filter.html', value='abcd')563 return flask.render_template("template_filter.html", value="abcd")564557 rv = client.get('/')558 assert rv.data == b'dcba'565 rv = client.get("/")566 assert rv.data == b"dcba"567568569def test_template_test(app):562 bp = flask.Blueprint('bp', __name__)570 bp = flask.Blueprint("bp", __name__)571572 @bp.app_template_test()573 def is_boolean(value):574 return isinstance(value, bool)575568 app.register_blueprint(bp, url_prefix='/py')569 assert 'is_boolean' in app.jinja_env.tests.keys()570 assert app.jinja_env.tests['is_boolean'] == is_boolean571 assert app.jinja_env.tests['is_boolean'](False)576 app.register_blueprint(bp, url_prefix="/py")577 assert "is_boolean" in app.jinja_env.tests.keys()578 assert app.jinja_env.tests["is_boolean"] == is_boolean579 assert app.jinja_env.tests["is_boolean"](False)580581582def test_add_template_test(app):575 bp = flask.Blueprint('bp', __name__)583 bp = flask.Blueprint("bp", __name__)584585 def is_boolean(value):586 return isinstance(value, bool)587588 bp.add_app_template_test(is_boolean)581 app.register_blueprint(bp, url_prefix='/py')582 assert 'is_boolean' in app.jinja_env.tests.keys()583 assert app.jinja_env.tests['is_boolean'] == is_boolean584 assert app.jinja_env.tests['is_boolean'](False)589 app.register_blueprint(bp, url_prefix="/py")590 assert "is_boolean" in app.jinja_env.tests.keys()591 assert app.jinja_env.tests["is_boolean"] == is_boolean592 assert app.jinja_env.tests["is_boolean"](False)593594595def test_template_test_with_name(app):588 bp = flask.Blueprint('bp', __name__)596 bp = flask.Blueprint("bp", __name__)597590 @bp.app_template_test('boolean')598 @bp.app_template_test("boolean")599 def is_boolean(value):600 return isinstance(value, bool)601594 app.register_blueprint(bp, url_prefix='/py')595 assert 'boolean' in app.jinja_env.tests.keys()596 assert app.jinja_env.tests['boolean'] == is_boolean597 assert app.jinja_env.tests['boolean'](False)602 app.register_blueprint(bp, url_prefix="/py")603 assert "boolean" in app.jinja_env.tests.keys()604 assert app.jinja_env.tests["boolean"] == is_boolean605 assert app.jinja_env.tests["boolean"](False)606607608def test_add_template_test_with_name(app):601 bp = flask.Blueprint('bp', __name__)609 bp = flask.Blueprint("bp", __name__)610611 def is_boolean(value):612 return isinstance(value, bool)613606 bp.add_app_template_test(is_boolean, 'boolean')607 app.register_blueprint(bp, url_prefix='/py')608 assert 'boolean' in app.jinja_env.tests.keys()609 assert app.jinja_env.tests['boolean'] == is_boolean610 assert app.jinja_env.tests['boolean'](False)614 bp.add_app_template_test(is_boolean, "boolean")615 app.register_blueprint(bp, url_prefix="/py")616 assert "boolean" in app.jinja_env.tests.keys()617 assert app.jinja_env.tests["boolean"] == is_boolean618 assert app.jinja_env.tests["boolean"](False)619620621def test_template_test_with_template(app, client):614 bp = flask.Blueprint('bp', __name__)622 bp = flask.Blueprint("bp", __name__)623624 @bp.app_template_test()625 def boolean(value):626 return isinstance(value, bool)627620 app.register_blueprint(bp, url_prefix='/py')628 app.register_blueprint(bp, url_prefix="/py")629622 @app.route('/')630 @app.route("/")631 def index():624 return flask.render_template('template_test.html', value=False)632 return flask.render_template("template_test.html", value=False)633626 rv = client.get('/')627 assert b'Success!' in rv.data634 rv = client.get("/")635 assert b"Success!" in rv.data636637638def test_template_test_after_route_with_template(app, client):631 @app.route('/')639 @app.route("/")640 def index():633 return flask.render_template('template_test.html', value=False)641 return flask.render_template("template_test.html", value=False)642635 bp = flask.Blueprint('bp', __name__)643 bp = flask.Blueprint("bp", __name__)644645 @bp.app_template_test()646 def boolean(value):647 return isinstance(value, bool)648641 app.register_blueprint(bp, url_prefix='/py')642 rv = client.get('/')643 assert b'Success!' in rv.data649 app.register_blueprint(bp, url_prefix="/py")650 rv = client.get("/")651 assert b"Success!" in rv.data652653654def test_add_template_test_with_template(app, client):647 bp = flask.Blueprint('bp', __name__)655 bp = flask.Blueprint("bp", __name__)656657 def boolean(value):658 return isinstance(value, bool)659660 bp.add_app_template_test(boolean)653 app.register_blueprint(bp, url_prefix='/py')661 app.register_blueprint(bp, url_prefix="/py")662655 @app.route('/')663 @app.route("/")664 def index():657 return flask.render_template('template_test.html', value=False)665 return flask.render_template("template_test.html", value=False)666659 rv = client.get('/')660 assert b'Success!' in rv.data667 rv = client.get("/")668 assert b"Success!" in rv.data669670671def test_template_test_with_name_and_template(app, client):664 bp = flask.Blueprint('bp', __name__)672 bp = flask.Blueprint("bp", __name__)673666 @bp.app_template_test('boolean')674 @bp.app_template_test("boolean")675 def is_boolean(value):676 return isinstance(value, bool)677670 app.register_blueprint(bp, url_prefix='/py')678 app.register_blueprint(bp, url_prefix="/py")679672 @app.route('/')680 @app.route("/")681 def index():674 return flask.render_template('template_test.html', value=False)682 return flask.render_template("template_test.html", value=False)683676 rv = client.get('/')677 assert b'Success!' in rv.data684 rv = client.get("/")685 assert b"Success!" in rv.data686687688def test_add_template_test_with_name_and_template(app, client):681 bp = flask.Blueprint('bp', __name__)689 bp = flask.Blueprint("bp", __name__)690691 def is_boolean(value):692 return isinstance(value, bool)693686 bp.add_app_template_test(is_boolean, 'boolean')687 app.register_blueprint(bp, url_prefix='/py')694 bp.add_app_template_test(is_boolean, "boolean")695 app.register_blueprint(bp, url_prefix="/py")696689 @app.route('/')697 @app.route("/")698 def index():691 return flask.render_template('template_test.html', value=False)699 return flask.render_template("template_test.html", value=False)700693 rv = client.get('/')694 assert b'Success!' in rv.data701 rv = client.get("/")702 assert b"Success!" in rv.data703704705def test_context_processing(app, client):698 answer_bp = flask.Blueprint('answer_bp', __name__)706 answer_bp = flask.Blueprint("answer_bp", __name__)707708 template_string = lambda: flask.render_template_string(701 '{% if notanswer %}{{ notanswer }} is not the answer. {% endif %}'702 '{% if answer %}{{ answer }} is the answer.{% endif %}'709 "{% if notanswer %}{{ notanswer }} is not the answer. {% endif %}"710 "{% if answer %}{{ answer }} is the answer.{% endif %}"711 )712713 # App global context processor714 @answer_bp.app_context_processor715 def not_answer_context_processor():708 return {'notanswer': 43}716 return {"notanswer": 43}717718 # Blueprint local context processor719 @answer_bp.context_processor720 def answer_context_processor():713 return {'answer': 42}721 return {"answer": 42}722723 # Setup endpoints for testing716 @answer_bp.route('/bp')724 @answer_bp.route("/bp")725 def bp_page():726 return template_string()727720 @app.route('/')728 @app.route("/")729 def app_page():730 return template_string()731732 # Register the blueprint733 app.register_blueprint(answer_bp)734727 app_page_bytes = client.get('/').data728 answer_page_bytes = client.get('/bp').data735 app_page_bytes = client.get("/").data736 answer_page_bytes = client.get("/bp").data737730 assert b'43' in app_page_bytes731 assert b'42' not in app_page_bytes738 assert b"43" in app_page_bytes739 assert b"42" not in app_page_bytes740733 assert b'42' in answer_page_bytes734 assert b'43' in answer_page_bytes741 assert b"42" in answer_page_bytes742 assert b"43" in answer_page_bytes743744745def test_template_global(app):738 bp = flask.Blueprint('bp', __name__)746 bp = flask.Blueprint("bp", __name__)747748 @bp.app_template_global()749 def get_answer():750 return 42751752 # Make sure the function is not in the jinja_env already745 assert 'get_answer' not in app.jinja_env.globals.keys()753 assert "get_answer" not in app.jinja_env.globals.keys()754 app.register_blueprint(bp)755756 # Tests749 assert 'get_answer' in app.jinja_env.globals.keys()750 assert app.jinja_env.globals['get_answer'] is get_answer751 assert app.jinja_env.globals['get_answer']() == 42757 assert "get_answer" in app.jinja_env.globals.keys()758 assert app.jinja_env.globals["get_answer"] is get_answer759 assert app.jinja_env.globals["get_answer"]() == 42760761 with app.app_context():754 rv = flask.render_template_string('{{ get_answer() }}')755 assert rv == '42'762 rv = flask.render_template_string("{{ get_answer() }}")763 assert rv == "42"764765766def test_request_processing(app, client):759 bp = flask.Blueprint('bp', __name__)767 bp = flask.Blueprint("bp", __name__)768 evts = []769770 @bp.before_request771 def before_bp():764 evts.append('before')772 evts.append("before")773774 @bp.after_request775 def after_bp(response):768 response.data += b'|after'769 evts.append('after')776 response.data += b"|after"777 evts.append("after")778 return response779780 @bp.teardown_request781 def teardown_bp(exc):774 evts.append('teardown')782 evts.append("teardown")783784 # Setup routes for testing777 @bp.route('/bp')785 @bp.route("/bp")786 def bp_endpoint():779 return 'request'787 return "request"788789 app.register_blueprint(bp)790791 assert evts == []784 rv = client.get('/bp')785 assert rv.data == b'request|after'786 assert evts == ['before', 'after', 'teardown']792 rv = client.get("/bp")793 assert rv.data == b"request|after"794 assert evts == ["before", "after", "teardown"]795796797def test_app_request_processing(app, client):790 bp = flask.Blueprint('bp', __name__)798 bp = flask.Blueprint("bp", __name__)799 evts = []800801 @bp.before_app_first_request802 def before_first_request():795 evts.append('first')803 evts.append("first")804805 @bp.before_app_request806 def before_app():799 evts.append('before')807 evts.append("before")808809 @bp.after_app_request810 def after_app(response):803 response.data += b'|after'804 evts.append('after')811 response.data += b"|after"812 evts.append("after")813 return response814815 @bp.teardown_app_request816 def teardown_app(exc):809 evts.append('teardown')817 evts.append("teardown")818819 app.register_blueprint(bp)820821 # Setup routes for testing814 @app.route('/')822 @app.route("/")823 def bp_endpoint():816 return 'request'824 return "request"825826 # before first request827 assert evts == []828829 # first request822 resp = client.get('/').data823 assert resp == b'request|after'824 assert evts == ['first', 'before', 'after', 'teardown']830 resp = client.get("/").data831 assert resp == b"request|after"832 assert evts == ["first", "before", "after", "teardown"]833834 # second request827 resp = client.get('/').data828 assert resp == b'request|after'829 assert evts == ['first'] + ['before', 'after', 'teardown'] * 2835 resp = client.get("/").data836 assert resp == b"request|after"837 assert evts == ["first"] + ["before", "after", "teardown"] * 2838839840def test_app_url_processors(app, client):833 bp = flask.Blueprint('bp', __name__)841 bp = flask.Blueprint("bp", __name__)842843 # Register app-wide url defaults and preprocessor on blueprint844 @bp.app_url_defaults845 def add_language_code(endpoint, values):838 values.setdefault('lang_code', flask.g.lang_code)846 values.setdefault("lang_code", flask.g.lang_code)847848 @bp.app_url_value_preprocessor849 def pull_lang_code(endpoint, values):842 flask.g.lang_code = values.pop('lang_code')850 flask.g.lang_code = values.pop("lang_code")851852 # Register route rules at the app level845 @app.route('/<lang_code>/')853 @app.route("/<lang_code>/")854 def index():847 return flask.url_for('about')855 return flask.url_for("about")856849 @app.route('/<lang_code>/about')857 @app.route("/<lang_code>/about")858 def about():851 return flask.url_for('index')859 return flask.url_for("index")860861 app.register_blueprint(bp)862855 assert client.get('/de/').data == b'/de/about'856 assert client.get('/de/about').data == b'/de/'863 assert client.get("/de/").data == b"/de/about"864 assert client.get("/de/about").data == b"/de/"
modified:tests/test_cli.py+182 added-167 removed
23 unmodified lines
24from click.testing import CliRunner2526from flask import Flask, current_app27from flask.cli import (28 AppGroup, FlaskGroup, NoAppException, ScriptInfo, dotenv, find_best_app,29 get_version, load_dotenv, locate_app, prepare_import, run_command,30 with_appcontext28 AppGroup,29 FlaskGroup,30 NoAppException,31 ScriptInfo,32 dotenv,33 find_best_app,34 get_version,35 load_dotenv,36 locate_app,37 prepare_import,38 run_command,39 with_appcontext,40)4142cwd = os.getcwd()34test_path = os.path.abspath(os.path.join(35 os.path.dirname(__file__), 'test_apps'36))43test_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "test_apps"))444546@pytest.fixture47def runner():
2 unmodified lines
5051def test_cli_name(test_apps):52 """Make sure the CLI object's name is the app's name and not the app itself"""53 from cliapp.app import testapp5455 assert testapp.cli.name == testapp.name565758def test_find_best_app(test_apps):59 """Test if `find_best_app` behaves as expected with different combinations of input."""60 script_info = ScriptInfo()6162 class Module:55 app = Flask('appname')63 app = Flask("appname")6465 assert find_best_app(script_info, Module) == Module.app6667 class Module:60 application = Flask('appname')68 application = Flask("appname")6970 assert find_best_app(script_info, Module) == Module.application7172 class Module:65 myapp = Flask('appname')73 myapp = Flask("appname")7475 assert find_best_app(script_info, Module) == Module.myapp7677 class Module:78 @staticmethod79 def create_app():72 return Flask('appname')80 return Flask("appname")8182 assert isinstance(find_best_app(script_info, Module), Flask)75 assert find_best_app(script_info, Module).name == 'appname'83 assert find_best_app(script_info, Module).name == "appname"8485 class Module:86 @staticmethod87 def create_app(foo):80 return Flask('appname')88 return Flask("appname")8990 assert isinstance(find_best_app(script_info, Module), Flask)83 assert find_best_app(script_info, Module).name == 'appname'91 assert find_best_app(script_info, Module).name == "appname"9293 class Module:94 @staticmethod95 def create_app(foo=None, script_info=None):88 return Flask('appname')96 return Flask("appname")9798 assert isinstance(find_best_app(script_info, Module), Flask)91 assert find_best_app(script_info, Module).name == 'appname'99 assert find_best_app(script_info, Module).name == "appname"100101 class Module:102 @staticmethod103 def make_app():96 return Flask('appname')104 return Flask("appname")105106 assert isinstance(find_best_app(script_info, Module), Flask)99 assert find_best_app(script_info, Module).name == 'appname'107 assert find_best_app(script_info, Module).name == "appname"108109 class Module:102 myapp = Flask('appname1')110 myapp = Flask("appname1")111112 @staticmethod113 def create_app():106 return Flask('appname2')114 return Flask("appname2")115116 assert find_best_app(script_info, Module) == Module.myapp117118 class Module:111 myapp = Flask('appname1')119 myapp = Flask("appname1")120121 @staticmethod122 def create_app():115 return Flask('appname2')123 return Flask("appname2")124125 assert find_best_app(script_info, Module) == Module.myapp126127 class Module:
1 unmodified line
129130 pytest.raises(NoAppException, find_best_app, script_info, Module)131132 class Module:125 myapp1 = Flask('appname1')126 myapp2 = Flask('appname2')133 myapp1 = Flask("appname1")134 myapp2 = Flask("appname2")135136 pytest.raises(NoAppException, find_best_app, script_info, Module)137138 class Module:139 @staticmethod140 def create_app(foo, bar):133 return Flask('appname2')141 return Flask("appname2")142143 pytest.raises(NoAppException, find_best_app, script_info, Module)144145 class Module:146 @staticmethod147 def create_app():140 raise TypeError('bad bad factory!')148 raise TypeError("bad bad factory!")149150 pytest.raises(TypeError, find_best_app, script_info, Module)151152145@pytest.mark.parametrize('value,path,result', (146 ('test', cwd, 'test'),147 ('test.py', cwd, 'test'),148 ('a/test', os.path.join(cwd, 'a'), 'test'),149 ('test/__init__.py', cwd, 'test'),150 ('test/__init__', cwd, 'test'),151 # nested package153@pytest.mark.parametrize(154 "value,path,result",155 (153 os.path.join(test_path, 'cliapp', 'inner1', '__init__'),154 test_path, 'cliapp.inner1'156 ("test", cwd, "test"),157 ("test.py", cwd, "test"),158 ("a/test", os.path.join(cwd, "a"), "test"),159 ("test/__init__.py", cwd, "test"),160 ("test/__init__", cwd, "test"),161 # nested package162 (163 os.path.join(test_path, "cliapp", "inner1", "__init__"),164 test_path,165 "cliapp.inner1",166 ),167 (168 os.path.join(test_path, "cliapp", "inner1", "inner2"),169 test_path,170 "cliapp.inner1.inner2",171 ),172 # dotted name173 ("test.a.b", cwd, "test.a.b"),174 (os.path.join(test_path, "cliapp.app"), test_path, "cliapp.app"),175 # not a Python file, will be caught during import176 (177 os.path.join(test_path, "cliapp", "message.txt"),178 test_path,179 "cliapp.message.txt",180 ),181 ),156 (157 os.path.join(test_path, 'cliapp', 'inner1', 'inner2'),158 test_path, 'cliapp.inner1.inner2'159 ),160 # dotted name161 ('test.a.b', cwd, 'test.a.b'),162 (os.path.join(test_path, 'cliapp.app'), test_path, 'cliapp.app'),163 # not a Python file, will be caught during import164 (165 os.path.join(test_path, 'cliapp', 'message.txt'),166 test_path, 'cliapp.message.txt'167 ),168))182)183def test_prepare_import(request, value, path, result):184 """Expect the correct path to be set and the correct import and app names185 to be returned.186
11 unmodified lines
198 assert prepare_import(value) == result199 assert sys.path[0] == path200201188@pytest.mark.parametrize('iname,aname,result', (189 ('cliapp.app', None, 'testapp'),190 ('cliapp.app', 'testapp', 'testapp'),191 ('cliapp.factory', None, 'app'),192 ('cliapp.factory', 'create_app', 'app'),193 ('cliapp.factory', 'create_app()', 'app'),194 # no script_info195 ('cliapp.factory', 'create_app2("foo", "bar")', 'app2_foo_bar'),196 # trailing comma space197 ('cliapp.factory', 'create_app2("foo", "bar", )', 'app2_foo_bar'),198 # takes script_info199 ('cliapp.factory', 'create_app3("foo")', 'app3_foo_spam'),200 # strip whitespace201 ('cliapp.factory', ' create_app () ', 'app'),202))202@pytest.mark.parametrize(203 "iname,aname,result",204 (205 ("cliapp.app", None, "testapp"),206 ("cliapp.app", "testapp", "testapp"),207 ("cliapp.factory", None, "app"),208 ("cliapp.factory", "create_app", "app"),209 ("cliapp.factory", "create_app()", "app"),210 # no script_info211 ("cliapp.factory", 'create_app2("foo", "bar")', "app2_foo_bar"),212 # trailing comma space213 ("cliapp.factory", 'create_app2("foo", "bar", )', "app2_foo_bar"),214 # takes script_info215 ("cliapp.factory", 'create_app3("foo")', "app3_foo_spam"),216 # strip whitespace217 ("cliapp.factory", " create_app () ", "app"),218 ),219)220def test_locate_app(test_apps, iname, aname, result):221 info = ScriptInfo()205 info.data['test'] = 'spam'222 info.data["test"] = "spam"223 assert locate_app(info, iname, aname).name == result224225209@pytest.mark.parametrize('iname,aname', (210 ('notanapp.py', None),211 ('cliapp/app', None),212 ('cliapp.app', 'notanapp'),213 # not enough arguments214 ('cliapp.factory', 'create_app2("foo")'),215 # invalid identifier216 ('cliapp.factory', 'create_app('),217 # no app returned218 ('cliapp.factory', 'no_app'),219 # nested import error220 ('cliapp.importerrorapp', None),221 # not a Python file222 ('cliapp.message.txt', None),223))226@pytest.mark.parametrize(227 "iname,aname",228 (229 ("notanapp.py", None),230 ("cliapp/app", None),231 ("cliapp.app", "notanapp"),232 # not enough arguments233 ("cliapp.factory", 'create_app2("foo")'),234 # invalid identifier235 ("cliapp.factory", "create_app("),236 # no app returned237 ("cliapp.factory", "no_app"),238 # nested import error239 ("cliapp.importerrorapp", None),240 # not a Python file241 ("cliapp.message.txt", None),242 ),243)244def test_locate_app_raises(test_apps, iname, aname):245 info = ScriptInfo()246247 with pytest.raises(NoAppException):
1 unmodified line
249250251def test_locate_app_suppress_raise():252 info = ScriptInfo()233 app = locate_app(info, 'notanapp.py', None, raise_if_not_found=False)253 app = locate_app(info, "notanapp.py", None, raise_if_not_found=False)254 assert app is None255256 # only direct import error is suppressed257 with pytest.raises(NoAppException):238 locate_app(239 info, 'cliapp.importerrorapp', None, raise_if_not_found=False240 )258 locate_app(info, "cliapp.importerrorapp", None, raise_if_not_found=False)259260261def test_get_version(test_apps, capsys):262 from flask import __version__ as flask_version
3 unmodified lines
266 class MockCtx(object):267 resilient_parsing = False268 color = None269252 def exit(self): return270 def exit(self):271 return272273 ctx = MockCtx()274 get_version(ctx, None, "test")275 out, err = capsys.readouterr()
9 unmodified lines
285 assert app.name == "testapp"286 assert obj.load_app() is app287288 # import app with module's absolute path270 cli_app_path = os.path.abspath(os.path.join(271 os.path.dirname(__file__), 'test_apps', 'cliapp', 'app.py'))289 cli_app_path = os.path.abspath(290 os.path.join(os.path.dirname(__file__), "test_apps", "cliapp", "app.py")291 )292 obj = ScriptInfo(app_import_path=cli_app_path)293 app = obj.load_app()274 assert app.name == 'testapp'294 assert app.name == "testapp"295 assert obj.load_app() is app276 obj = ScriptInfo(app_import_path=cli_app_path + ':testapp')296 obj = ScriptInfo(app_import_path=cli_app_path + ":testapp")297 app = obj.load_app()278 assert app.name == 'testapp'298 assert app.name == "testapp"299 assert obj.load_app() is app300301 def create_app(info):302 return Flask("createapp")
6 unmodified lines
309 obj = ScriptInfo()310 pytest.raises(NoAppException, obj.load_app)311312 # import app from wsgi.py in current directory293 monkeypatch.chdir(os.path.abspath(os.path.join(294 os.path.dirname(__file__), 'test_apps', 'helloworld'295 )))313 monkeypatch.chdir(314 os.path.abspath(315 os.path.join(os.path.dirname(__file__), "test_apps", "helloworld")316 )317 )318 obj = ScriptInfo()319 app = obj.load_app()298 assert app.name == 'hello'320 assert app.name == "hello"321322 # import app from app.py in current directory301 monkeypatch.chdir(os.path.abspath(os.path.join(302 os.path.dirname(__file__), 'test_apps', 'cliapp'303 )))323 monkeypatch.chdir(324 os.path.abspath(os.path.join(os.path.dirname(__file__), "test_apps", "cliapp"))325 )326 obj = ScriptInfo()327 app = obj.load_app()306 assert app.name == 'testapp'328 assert app.name == "testapp"329330331def test_with_appcontext(runner):332 """Test of with_appcontext."""
6 unmodified lines
339 obj = ScriptInfo(create_app=lambda info: Flask("testapp"))340341 result = runner.invoke(testcmd, obj=obj)342 assert result.exit_code == 0321 assert result.output == 'testapp\n'343 assert result.output == "testapp\n"344345346def test_appgroup(runner):347 """Test of with_appcontext."""
15 unmodified lines
363 click.echo(current_app.name)364365 obj = ScriptInfo(create_app=lambda info: Flask("testappgroup"))366345 result = runner.invoke(cli, ['test'], obj=obj)367 result = runner.invoke(cli, ["test"], obj=obj)368 assert result.exit_code == 0347 assert result.output == 'testappgroup\n'369 assert result.output == "testappgroup\n"370349 result = runner.invoke(cli, ['subgroup', 'test2'], obj=obj)371 result = runner.invoke(cli, ["subgroup", "test2"], obj=obj)372 assert result.exit_code == 0351 assert result.output == 'testappgroup\n'373 assert result.output == "testappgroup\n"374375376def test_flaskgroup(runner):377 """Test FlaskGroup."""
8 unmodified lines
386 @cli.command()387 def test():388 click.echo(current_app.name)389368 result = runner.invoke(cli, ['test'])390 result = runner.invoke(cli, ["test"])391 assert result.exit_code == 0370 assert result.output == 'flaskgroup\n'392 assert result.output == "flaskgroup\n"393394373@pytest.mark.parametrize('set_debug_flag', (True, False))395@pytest.mark.parametrize("set_debug_flag", (True, False))396def test_flaskgroup_debug(runner, set_debug_flag):397 """Test FlaskGroup debug flag behavior."""398399 def create_app(info):
8 unmodified lines
408 @cli.command()409 def test():410 click.echo(str(current_app.debug))411390 result = runner.invoke(cli, ['test'])412 result = runner.invoke(cli, ["test"])413 assert result.exit_code == 0392 assert result.output == '%s\n' % str(not set_debug_flag)414 assert result.output == "%s\n" % str(not set_debug_flag)415416417def test_print_exceptions(runner):418 """Print the stacktrace if the CLI."""
5 unmodified lines
424 @click.group(cls=FlaskGroup, create_app=create_app)425 def cli(**params):426 pass427406 result = runner.invoke(cli, ['--help'])428 result = runner.invoke(cli, ["--help"])429 assert result.exit_code == 0408 assert 'Exception: oh no' in result.output409 assert 'Traceback' in result.output430 assert "Exception: oh no" in result.output431 assert "Traceback" in result.output432433434class TestRoutes:435 @pytest.fixture
1 unmodified line
437 def create_app(info):438 app = Flask(__name__)439 app.testing = True440419 @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])441 @app.route("/get_post/<int:x>/<int:y>", methods=["GET", "POST"])442 def yyy_get_post(x, y):443 pass444423 @app.route('/zzz_post', methods=['POST'])445 @app.route("/zzz_post", methods=["POST"])446 def aaa_post():447 pass448449 return app
15 unmodified lines
465 def expect_order(self, order, output):466 # skip the header and match the start of each row467 for expect, line in zip(order, output.splitlines()[2:]):468 # do this instead of startswith for nicer pytest output447 assert line[:len(expect)] == expect469 assert line[: len(expect)] == expect470471 def test_simple(self, invoke):450 result = invoke(['routes'])472 result = invoke(["routes"])473 assert result.exit_code == 0452 self.expect_order(453 ['aaa_post', 'static', 'yyy_get_post'],454 result.output455 )474 self.expect_order(["aaa_post", "static", "yyy_get_post"], result.output)475476 def test_sort(self, invoke):458 default_output = invoke(['routes']).output459 endpoint_output = invoke(['routes', '-s', 'endpoint']).output477 default_output = invoke(["routes"]).output478 endpoint_output = invoke(["routes", "-s", "endpoint"]).output479 assert default_output == endpoint_output480 self.expect_order(462 ['static', 'yyy_get_post', 'aaa_post'],463 invoke(['routes', '-s', 'methods']).output481 ["static", "yyy_get_post", "aaa_post"],482 invoke(["routes", "-s", "methods"]).output,483 )484 self.expect_order(466 ['yyy_get_post', 'static', 'aaa_post'],467 invoke(['routes', '-s', 'rule']).output485 ["yyy_get_post", "static", "aaa_post"],486 invoke(["routes", "-s", "rule"]).output,487 )488 self.expect_order(470 ['aaa_post', 'yyy_get_post', 'static'],471 invoke(['routes', '-s', 'match']).output489 ["aaa_post", "yyy_get_post", "static"],490 invoke(["routes", "-s", "match"]).output,491 )492493 def test_all_methods(self, invoke):475 output = invoke(['routes']).output476 assert 'GET, HEAD, OPTIONS, POST' not in output477 output = invoke(['routes', '--all-methods']).output478 assert 'GET, HEAD, OPTIONS, POST' in output494 output = invoke(["routes"]).output495 assert "GET, HEAD, OPTIONS, POST" not in output496 output = invoke(["routes", "--all-methods"]).output497 assert "GET, HEAD, OPTIONS, POST" in output498499 def test_no_routes(self, invoke_no_routes):481 result = invoke_no_routes(['routes'])500 result = invoke_no_routes(["routes"])501 assert result.exit_code == 0483 assert 'No routes were registered.' in result.output502 assert "No routes were registered." in result.output503504486need_dotenv = pytest.mark.skipif(487 dotenv is None, reason='dotenv is not installed'488)505need_dotenv = pytest.mark.skipif(dotenv is None, reason="dotenv is not installed")506507508@need_dotenv509def test_load_dotenv(monkeypatch):510 # can't use monkeypatch.delitem since the keys don't exist yet494 for item in ('FOO', 'BAR', 'SPAM'):511 for item in ("FOO", "BAR", "SPAM"):512 monkeypatch._setitem.append((os.environ, item, notset))513497 monkeypatch.setenv('EGGS', '3')498 monkeypatch.chdir(os.path.join(test_path, 'cliapp', 'inner1'))514 monkeypatch.setenv("EGGS", "3")515 monkeypatch.chdir(os.path.join(test_path, "cliapp", "inner1"))516 load_dotenv()517 assert os.getcwd() == test_path518 # .flaskenv doesn't overwrite .env502 assert os.environ['FOO'] == 'env'519 assert os.environ["FOO"] == "env"520 # set only in .flaskenv504 assert os.environ['BAR'] == 'bar'521 assert os.environ["BAR"] == "bar"522 # set only in .env506 assert os.environ['SPAM'] == '1'523 assert os.environ["SPAM"] == "1"524 # set manually, files don't overwrite508 assert os.environ['EGGS'] == '3'525 assert os.environ["EGGS"] == "3"526527528@need_dotenv529def test_dotenv_path(monkeypatch):513 for item in ('FOO', 'BAR', 'EGGS'):530 for item in ("FOO", "BAR", "EGGS"):531 monkeypatch._setitem.append((os.environ, item, notset))532533 cwd = os.getcwd()517 load_dotenv(os.path.join(test_path, '.flaskenv'))534 load_dotenv(os.path.join(test_path, ".flaskenv"))535 assert os.getcwd() == cwd519 assert 'FOO' in os.environ536 assert "FOO" in os.environ537538539def test_dotenv_optional(monkeypatch):523 monkeypatch.setattr('flask.cli.dotenv', None)540 monkeypatch.setattr("flask.cli.dotenv", None)541 monkeypatch.chdir(test_path)542 load_dotenv()526 assert 'FOO' not in os.environ543 assert "FOO" not in os.environ544545546@need_dotenv547def test_disable_dotenv_from_env(monkeypatch, runner):548 monkeypatch.chdir(test_path)532 monkeypatch.setitem(os.environ, 'FLASK_SKIP_DOTENV', '1')549 monkeypatch.setitem(os.environ, "FLASK_SKIP_DOTENV", "1")550 runner.invoke(FlaskGroup())534 assert 'FOO' not in os.environ551 assert "FOO" not in os.environ552553554def test_run_cert_path():555 # no key556 with pytest.raises(click.BadParameter):540 run_command.make_context('run', ['--cert', __file__])557 run_command.make_context("run", ["--cert", __file__])558559 # no cert560 with pytest.raises(click.BadParameter):544 run_command.make_context('run', ['--key', __file__])561 run_command.make_context("run", ["--key", __file__])562546 ctx = run_command.make_context(547 'run', ['--cert', __file__, '--key', __file__])548 assert ctx.params['cert'] == (__file__, __file__)563 ctx = run_command.make_context("run", ["--cert", __file__, "--key", __file__])564 assert ctx.params["cert"] == (__file__, __file__)565566567def test_run_cert_adhoc(monkeypatch):552 monkeypatch.setitem(sys.modules, 'OpenSSL', None)568 monkeypatch.setitem(sys.modules, "OpenSSL", None)569570 # pyOpenSSL not installed571 with pytest.raises(click.BadParameter):556 run_command.make_context('run', ['--cert', 'adhoc'])572 run_command.make_context("run", ["--cert", "adhoc"])573574 # pyOpenSSL installed559 monkeypatch.setitem(sys.modules, 'OpenSSL', types.ModuleType('OpenSSL'))560 ctx = run_command.make_context('run', ['--cert', 'adhoc'])561 assert ctx.params['cert'] == 'adhoc'575 monkeypatch.setitem(sys.modules, "OpenSSL", types.ModuleType("OpenSSL"))576 ctx = run_command.make_context("run", ["--cert", "adhoc"])577 assert ctx.params["cert"] == "adhoc"578579 # no key with adhoc580 with pytest.raises(click.BadParameter):565 run_command.make_context('run', ['--cert', 'adhoc', '--key', __file__])581 run_command.make_context("run", ["--cert", "adhoc", "--key", __file__])582583584def test_run_cert_import(monkeypatch):569 monkeypatch.setitem(sys.modules, 'not_here', None)585 monkeypatch.setitem(sys.modules, "not_here", None)586587 # ImportError588 with pytest.raises(click.BadParameter):573 run_command.make_context('run', ['--cert', 'not_here'])589 run_command.make_context("run", ["--cert", "not_here"])590591 # not an SSLContext592 if sys.version_info >= (2, 7, 9):593 with pytest.raises(click.BadParameter):578 run_command.make_context('run', ['--cert', 'flask'])594 run_command.make_context("run", ["--cert", "flask"])595596 # SSLContext597 if sys.version_info < (2, 7, 9):598 ssl_context = object()599 else:600 ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)601586 monkeypatch.setitem(sys.modules, 'ssl_context', ssl_context)587 ctx = run_command.make_context('run', ['--cert', 'ssl_context'])588 assert ctx.params['cert'] is ssl_context602 monkeypatch.setitem(sys.modules, "ssl_context", ssl_context)603 ctx = run_command.make_context("run", ["--cert", "ssl_context"])604 assert ctx.params["cert"] is ssl_context605606 # no --key with SSLContext607 with pytest.raises(click.BadParameter):592 run_command.make_context(593 'run', ['--cert', 'ssl_context', '--key', __file__])608 run_command.make_context("run", ["--cert", "ssl_context", "--key", __file__])
modified:tests/test_config.py+68 added-66 removed
15 unmodified lines
16import pytest171819# config keys used for the TestConfig20TEST_KEY = 'foo'21SECRET_KEY = 'config'20TEST_KEY = "foo"21SECRET_KEY = "config"222324def common_object_test(app):25 assert app.secret_key == 'config'26 assert app.config['TEST_KEY'] == 'foo'27 assert 'TestConfig' not in app.config25 assert app.secret_key == "config"26 assert app.config["TEST_KEY"] == "foo"27 assert "TestConfig" not in app.config282930def test_config_from_file():31 app = flask.Flask(__name__)32 app.config.from_pyfile(__file__.rsplit('.', 1)[0] + '.py')32 app.config.from_pyfile(__file__.rsplit(".", 1)[0] + ".py")33 common_object_test(app)343536def test_config_from_object():
4 unmodified lines
4142def test_config_from_json():43 app = flask.Flask(__name__)44 current_dir = os.path.dirname(os.path.abspath(__file__))45 app.config.from_json(os.path.join(current_dir, 'static', 'config.json'))45 app.config.from_json(os.path.join(current_dir, "static", "config.json"))46 common_object_test(app)474849def test_config_from_mapping():50 app = flask.Flask(__name__)51 app.config.from_mapping({52 'SECRET_KEY': 'config',53 'TEST_KEY': 'foo'54 })51 app.config.from_mapping({"SECRET_KEY": "config", "TEST_KEY": "foo"})52 common_object_test(app)5354 app = flask.Flask(__name__)58 app.config.from_mapping([59 ('SECRET_KEY', 'config'),60 ('TEST_KEY', 'foo')61 ])55 app.config.from_mapping([("SECRET_KEY", "config"), ("TEST_KEY", "foo")])56 common_object_test(app)5758 app = flask.Flask(__name__)65 app.config.from_mapping(66 SECRET_KEY='config',67 TEST_KEY='foo'68 )59 app.config.from_mapping(SECRET_KEY="config", TEST_KEY="foo")60 common_object_test(app)6162 app = flask.Flask(__name__)63 with pytest.raises(TypeError):73 app.config.from_mapping(74 {}, {}75 )64 app.config.from_mapping({}, {})656667def test_config_from_class():68 class Base(object):80 TEST_KEY = 'foo'69 TEST_KEY = "foo"7071 class Test(Base):83 SECRET_KEY = 'config'72 SECRET_KEY = "config"7374 app = flask.Flask(__name__)75 app.config.from_object(Test)76 common_object_test(app)
4 unmodified lines
81 try:82 os.environ = {}83 app = flask.Flask(__name__)84 with pytest.raises(RuntimeError) as e:96 app.config.from_envvar('FOO_SETTINGS')85 app.config.from_envvar("FOO_SETTINGS")86 assert "'FOO_SETTINGS' is not set" in str(e.value)98 assert not app.config.from_envvar('FOO_SETTINGS', silent=True)87 assert not app.config.from_envvar("FOO_SETTINGS", silent=True)88100 os.environ = {'FOO_SETTINGS': __file__.rsplit('.', 1)[0] + '.py'}101 assert app.config.from_envvar('FOO_SETTINGS')89 os.environ = {"FOO_SETTINGS": __file__.rsplit(".", 1)[0] + ".py"}90 assert app.config.from_envvar("FOO_SETTINGS")91 common_object_test(app)92 finally:93 os.environ = env949596def test_config_from_envvar_missing():97 env = os.environ98 try:110 os.environ = {'FOO_SETTINGS': 'missing.cfg'}99 os.environ = {"FOO_SETTINGS": "missing.cfg"}100 with pytest.raises(IOError) as e:101 app = flask.Flask(__name__)113 app.config.from_envvar('FOO_SETTINGS')102 app.config.from_envvar("FOO_SETTINGS")103 msg = str(e.value)115 assert msg.startswith('[Errno 2] Unable to load configuration '116 'file (No such file or directory):')104 assert msg.startswith(105 "[Errno 2] Unable to load configuration "106 "file (No such file or directory):"107 )108 assert msg.endswith("missing.cfg'")118 assert not app.config.from_envvar('FOO_SETTINGS', silent=True)109 assert not app.config.from_envvar("FOO_SETTINGS", silent=True)110 finally:111 os.environ = env112113114def test_config_missing():115 app = flask.Flask(__name__)116 with pytest.raises(IOError) as e:126 app.config.from_pyfile('missing.cfg')117 app.config.from_pyfile("missing.cfg")118 msg = str(e.value)128 assert msg.startswith('[Errno 2] Unable to load configuration '129 'file (No such file or directory):')119 assert msg.startswith(120 "[Errno 2] Unable to load configuration " "file (No such file or directory):"121 )122 assert msg.endswith("missing.cfg'")131 assert not app.config.from_pyfile('missing.cfg', silent=True)123 assert not app.config.from_pyfile("missing.cfg", silent=True)124125126def test_config_missing_json():127 app = flask.Flask(__name__)128 with pytest.raises(IOError) as e:137 app.config.from_json('missing.json')129 app.config.from_json("missing.json")130 msg = str(e.value)139 assert msg.startswith('[Errno 2] Unable to load configuration '140 'file (No such file or directory):')131 assert msg.startswith(132 "[Errno 2] Unable to load configuration " "file (No such file or directory):"133 )134 assert msg.endswith("missing.json'")142 assert not app.config.from_json('missing.json', silent=True)135 assert not app.config.from_json("missing.json", silent=True)136137138def test_custom_config_class():139 class Config(flask.Config):140 pass141142 class Flask(flask.Flask):143 config_class = Config144145 app = Flask(__name__)146 assert isinstance(app.config, Config)147 app.config.from_object(__name__)148 common_object_test(app)149150151def test_session_lifetime():152 app = flask.Flask(__name__)159 app.config['PERMANENT_SESSION_LIFETIME'] = 42153 app.config["PERMANENT_SESSION_LIFETIME"] = 42154 assert app.permanent_session_lifetime.seconds == 42155156157def test_send_file_max_age():158 app = flask.Flask(__name__)165 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600159 app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 3600160 assert app.send_file_max_age_default.seconds == 3600167 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(hours=2)161 app.config["SEND_FILE_MAX_AGE_DEFAULT"] = timedelta(hours=2)162 assert app.send_file_max_age_default.seconds == 7200163164165def test_get_namespace():166 app = flask.Flask(__name__)173 app.config['FOO_OPTION_1'] = 'foo option 1'174 app.config['FOO_OPTION_2'] = 'foo option 2'175 app.config['BAR_STUFF_1'] = 'bar stuff 1'176 app.config['BAR_STUFF_2'] = 'bar stuff 2'177 foo_options = app.config.get_namespace('FOO_')167 app.config["FOO_OPTION_1"] = "foo option 1"168 app.config["FOO_OPTION_2"] = "foo option 2"169 app.config["BAR_STUFF_1"] = "bar stuff 1"170 app.config["BAR_STUFF_2"] = "bar stuff 2"171 foo_options = app.config.get_namespace("FOO_")172 assert 2 == len(foo_options)179 assert 'foo option 1' == foo_options['option_1']180 assert 'foo option 2' == foo_options['option_2']181 bar_options = app.config.get_namespace('BAR_', lowercase=False)173 assert "foo option 1" == foo_options["option_1"]174 assert "foo option 2" == foo_options["option_2"]175 bar_options = app.config.get_namespace("BAR_", lowercase=False)176 assert 2 == len(bar_options)183 assert 'bar stuff 1' == bar_options['STUFF_1']184 assert 'bar stuff 2' == bar_options['STUFF_2']185 foo_options = app.config.get_namespace('FOO_', trim_namespace=False)177 assert "bar stuff 1" == bar_options["STUFF_1"]178 assert "bar stuff 2" == bar_options["STUFF_2"]179 foo_options = app.config.get_namespace("FOO_", trim_namespace=False)180 assert 2 == len(foo_options)187 assert 'foo option 1' == foo_options['foo_option_1']188 assert 'foo option 2' == foo_options['foo_option_2']189 bar_options = app.config.get_namespace('BAR_', lowercase=False, trim_namespace=False)181 assert "foo option 1" == foo_options["foo_option_1"]182 assert "foo option 2" == foo_options["foo_option_2"]183 bar_options = app.config.get_namespace(184 "BAR_", lowercase=False, trim_namespace=False185 )186 assert 2 == len(bar_options)191 assert 'bar stuff 1' == bar_options['BAR_STUFF_1']192 assert 'bar stuff 2' == bar_options['BAR_STUFF_2']187 assert "bar stuff 1" == bar_options["BAR_STUFF_1"]188 assert "bar stuff 2" == bar_options["BAR_STUFF_2"]189190195@pytest.mark.parametrize('encoding', ['utf-8', 'iso-8859-15', 'latin-1'])191@pytest.mark.parametrize("encoding", ["utf-8", "iso-8859-15", "latin-1"])192def test_from_pyfile_weird_encoding(tmpdir, encoding):197 f = tmpdir.join('my_config.py')198 f.write_binary(textwrap.dedent(u'''193 f = tmpdir.join("my_config.py")194 f.write_binary(195 textwrap.dedent(196 u"""197 # -*- coding: {0} -*-198 TEST_VALUE = "föö"201 '''.format(encoding)).encode(encoding))199 """.format(200 encoding201 )202 ).encode(encoding)203 )204 app = flask.Flask(__name__)205 app.config.from_pyfile(str(f))204 value = app.config['TEST_VALUE']206 value = app.config["TEST_VALUE"]207 if PY2:208 value = value.decode(encoding)207 assert value == u'föö'209 assert value == u"föö"
modified:tests/test_helpers.py+411 added-355 removed
15 unmodified lines
1617import pytest18from werkzeug.datastructures import Range19from werkzeug.exceptions import BadRequest, NotFound20from werkzeug.http import (21 http_date, parse_cache_control_header,22 parse_options_header23)20from werkzeug.http import http_date, parse_cache_control_header, parse_options_header2122import flask23from flask import json24from flask._compat import StringIO, text_type
2 unmodified lines
2728def has_encoding(name):29 try:30 import codecs3132 codecs.lookup(name)33 return True34 except LookupError:35 return False
4 unmodified lines
4041 This represents a ``pathlib.Path`` object in python 3.42 See: https://www.python.org/dev/peps/pep-0519/43 """4445 def __init__(self, path):46 self.path = path4748 def __fspath__(self):
21 unmodified lines
70 return datetime.timedelta()717273class TestJSON(object):75 @pytest.mark.parametrize('value', (76 1, 't', True, False, None,77 [], [1, 2, 3],78 {}, {'foo': u'🐍'},79 ))80 @pytest.mark.parametrize('encoding', (81 'utf-8', 'utf-8-sig',82 'utf-16-le', 'utf-16-be', 'utf-16',83 'utf-32-le', 'utf-32-be', 'utf-32',84 ))74 @pytest.mark.parametrize(75 "value", (1, "t", True, False, None, [], [1, 2, 3], {}, {"foo": u"🐍"})76 )77 @pytest.mark.parametrize(78 "encoding",79 (80 "utf-8",81 "utf-8-sig",82 "utf-16-le",83 "utf-16-be",84 "utf-16",85 "utf-32-le",86 "utf-32-be",87 "utf-32",88 ),89 )90 def test_detect_encoding(self, value, encoding):91 data = json.dumps(value).encode(encoding)92 assert json.detect_encoding(data) == encoding93 assert json.loads(data) == value9495 def test_ignore_cached_json(self, app):91 with app.test_request_context('/', method='POST', data='malformed',92 content_type='application/json'):96 with app.test_request_context(97 "/", method="POST", data="malformed", content_type="application/json"98 ):99 assert flask.request.get_json(silent=True, cache=True) is None100 with pytest.raises(BadRequest):101 flask.request.get_json(silent=False, cache=False)102103 def test_different_silent_on_bad_request(self, app):104 with app.test_request_context(99 '/', method='POST', data='malformed',100 content_type='application/json'):105 "/", method="POST", data="malformed", content_type="application/json"106 ):107 assert flask.request.get_json(silent=True) is None108 with pytest.raises(BadRequest):109 flask.request.get_json(silent=False)110111 def test_different_silent_on_normal_request(self, app):106 with app.test_request_context('/', method='POST', json={'foo': 'bar'}):112 with app.test_request_context("/", method="POST", json={"foo": "bar"}):113 silent_rv = flask.request.get_json(silent=True)114 normal_rv = flask.request.get_json(silent=False)115 assert silent_rv is normal_rv110 assert normal_rv['foo'] == 'bar'116 assert normal_rv["foo"] == "bar"117112 def test_post_empty_json_adds_exception_to_response_content_in_debug(self, app, client):113 app.config['DEBUG'] = True114 app.config['TRAP_BAD_REQUEST_ERRORS'] = False118 def test_post_empty_json_adds_exception_to_response_content_in_debug(119 self, app, client120 ):121 app.config["DEBUG"] = True122 app.config["TRAP_BAD_REQUEST_ERRORS"] = False123116 @app.route('/json', methods=['POST'])124 @app.route("/json", methods=["POST"])125 def post_json():126 flask.request.get_json()127 return None128121 rv = client.post('/json', data=None, content_type='application/json')129 rv = client.post("/json", data=None, content_type="application/json")130 assert rv.status_code == 400123 assert b'Failed to decode JSON object' in rv.data131 assert b"Failed to decode JSON object" in rv.data132125 def test_post_empty_json_wont_add_exception_to_response_if_no_debug(self, app, client):126 app.config['DEBUG'] = False127 app.config['TRAP_BAD_REQUEST_ERRORS'] = False133 def test_post_empty_json_wont_add_exception_to_response_if_no_debug(134 self, app, client135 ):136 app.config["DEBUG"] = False137 app.config["TRAP_BAD_REQUEST_ERRORS"] = False138129 @app.route('/json', methods=['POST'])139 @app.route("/json", methods=["POST"])140 def post_json():141 flask.request.get_json()142 return None143134 rv = client.post('/json', data=None, content_type='application/json')144 rv = client.post("/json", data=None, content_type="application/json")145 assert rv.status_code == 400136 assert b'Failed to decode JSON object' not in rv.data146 assert b"Failed to decode JSON object" not in rv.data147148 def test_json_bad_requests(self, app, client):139140 @app.route('/json', methods=['POST'])149 @app.route("/json", methods=["POST"])150 def return_json():151 return flask.jsonify(foo=text_type(flask.request.get_json()))152144 rv = client.post('/json', data='malformed', content_type='application/json')153 rv = client.post("/json", data="malformed", content_type="application/json")154 assert rv.status_code == 400155156 def test_json_custom_mimetypes(self, app, client):148149 @app.route('/json', methods=['POST'])157 @app.route("/json", methods=["POST"])158 def return_json():159 return flask.request.get_json()160153 rv = client.post('/json', data='"foo"', content_type='application/x+json')154 assert rv.data == b'foo'161 rv = client.post("/json", data='"foo"', content_type="application/x+json")162 assert rv.data == b"foo"163156 @pytest.mark.parametrize('test_value,expected', [(True, '"\\u2603"'), (False, u'"\u2603"')])164 @pytest.mark.parametrize(165 "test_value,expected", [(True, '"\\u2603"'), (False, u'"\u2603"')]166 )167 def test_json_as_unicode(self, test_value, expected, app, app_ctx):168159 app.config['JSON_AS_ASCII'] = test_value160 rv = flask.json.dumps(u'\N{SNOWMAN}')169 app.config["JSON_AS_ASCII"] = test_value170 rv = flask.json.dumps(u"\N{SNOWMAN}")171 assert rv == expected172173 def test_json_dump_to_file(self, app, app_ctx):164 test_data = {'name': 'Flask'}174 test_data = {"name": "Flask"}175 out = StringIO()176177 flask.json.dump(test_data, out)178 out.seek(0)179 rv = flask.json.load(out)180 assert rv == test_data181172 @pytest.mark.parametrize('test_value', [0, -1, 1, 23, 3.14, 's', "longer string", True, False, None])182 @pytest.mark.parametrize(183 "test_value", [0, -1, 1, 23, 3.14, "s", "longer string", True, False, None]184 )185 def test_jsonify_basic_types(self, test_value, app, client):186 """Test jsonify with basic types."""187176 url = '/jsonify_basic_types'188 url = "/jsonify_basic_types"189 app.add_url_rule(url, url, lambda x=test_value: flask.jsonify(x))190 rv = client.get(url)179 assert rv.mimetype == 'application/json'191 assert rv.mimetype == "application/json"192 assert flask.json.loads(rv.data) == test_value193194 def test_jsonify_dicts(self, app, client):195 """Test jsonify with dicts and kwargs unpacking."""184 d = {'a': 0, 'b': 23, 'c': 3.14, 'd': 't',185 'e': 'Hi', 'f': True, 'g': False,186 'h': ['test list', 10, False],187 'i': {'test': 'dict'}}196 d = {197 "a": 0,198 "b": 23,199 "c": 3.14,200 "d": "t",201 "e": "Hi",202 "f": True,203 "g": False,204 "h": ["test list", 10, False],205 "i": {"test": "dict"},206 }207189 @app.route('/kw')208 @app.route("/kw")209 def return_kwargs():210 return flask.jsonify(**d)211193 @app.route('/dict')212 @app.route("/dict")213 def return_dict():214 return flask.jsonify(d)215197 for url in '/kw', '/dict':216 for url in "/kw", "/dict":217 rv = client.get(url)199 assert rv.mimetype == 'application/json'218 assert rv.mimetype == "application/json"219 assert flask.json.loads(rv.data) == d220221 def test_jsonify_arrays(self, app, client):222 """Test jsonify of lists and args unpacking."""223 l = [205 0, 42, 3.14, 't', 'hello', True, False,206 ['test list', 2, False],207 {'test': 'dict'}224 0,225 42,226 3.14,227 "t",228 "hello",229 True,230 False,231 ["test list", 2, False],232 {"test": "dict"},233 ]234210 @app.route('/args_unpack')235 @app.route("/args_unpack")236 def return_args_unpack():237 return flask.jsonify(*l)238214 @app.route('/array')239 @app.route("/array")240 def return_array():241 return flask.jsonify(l)242218 for url in '/args_unpack', '/array':243 for url in "/args_unpack", "/array":244 rv = client.get(url)220 assert rv.mimetype == 'application/json'245 assert rv.mimetype == "application/json"246 assert flask.json.loads(rv.data) == l247248 def test_jsonify_date_types(self, app, client):249 """Test jsonify with datetime.date and datetime.datetime types."""250 test_dates = (251 datetime.datetime(1973, 3, 11, 6, 30, 45),227 datetime.date(1975, 1, 5)252 datetime.date(1975, 1, 5),253 )254255 for i, d in enumerate(test_dates):231 url = '/datetest{0}'.format(i)256 url = "/datetest{0}".format(i)257 app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val))258 rv = client.get(url)234 assert rv.mimetype == 'application/json'235 assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple())259 assert rv.mimetype == "application/json"260 assert flask.json.loads(rv.data)["x"] == http_date(d.timetuple())261237 @pytest.mark.parametrize('tz', (('UTC', 0), ('PST', -8), ('KST', 9)))262 @pytest.mark.parametrize("tz", (("UTC", 0), ("PST", -8), ("KST", 9)))263 def test_jsonify_aware_datetimes(self, tz):264 """Test if aware datetime.datetime objects are converted into GMT."""265 tzinfo = FixedOffset(hours=tz[1], name=tz[0])266 dt = datetime.datetime(2017, 1, 1, 12, 34, 56, tzinfo=tzinfo)242 gmt = FixedOffset(hours=0, name='GMT')267 gmt = FixedOffset(hours=0, name="GMT")268 expected = dt.astimezone(gmt).strftime('"%a, %d %b %Y %H:%M:%S %Z"')269 assert flask.json.JSONEncoder().encode(dt) == expected270271 def test_jsonify_uuid_types(self, app, client):272 """Test jsonify with uuid.UUID types"""273249 test_uuid = uuid.UUID(bytes=b'\xDE\xAD\xBE\xEF' * 4)250 url = '/uuid_test'274 test_uuid = uuid.UUID(bytes=b"\xDE\xAD\xBE\xEF" * 4)275 url = "/uuid_test"276 app.add_url_rule(url, url, lambda: flask.jsonify(x=test_uuid))277278 rv = client.get(url)279255 rv_x = flask.json.loads(rv.data)['x']280 rv_x = flask.json.loads(rv.data)["x"]281 assert rv_x == str(test_uuid)282 rv_uuid = uuid.UUID(rv_x)283 assert rv_uuid == test_uuid284285 def test_json_attr(self, app, client):261262 @app.route('/add', methods=['POST'])286 @app.route("/add", methods=["POST"])287 def add():288 json = flask.request.get_json()265 return text_type(json['a'] + json['b'])289 return text_type(json["a"] + json["b"])290267 rv = client.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),268 content_type='application/json')269 assert rv.data == b'3'291 rv = client.post(292 "/add",293 data=flask.json.dumps({"a": 1, "b": 2}),294 content_type="application/json",295 )296 assert rv.data == b"3"297298 def test_template_escaping(self, app, req_ctx):299 render = flask.render_template_string273 rv = flask.json.htmlsafe_dumps('</script>')300 rv = flask.json.htmlsafe_dumps("</script>")301 assert rv == u'"\\u003c/script\\u003e"'302 assert type(rv) == text_type303 rv = render('{{ "</script>"|tojson }}')304 assert rv == '"\\u003c/script\\u003e"'
4 unmodified lines
309 rv = render('{{ "&"|tojson }}')310 assert rv == '"\\u0026"'311 rv = render('{{ "\'"|tojson }}')312 assert rv == '"\\u0027"'286 rv = render("<a ng-data='{{ data|tojson }}'></a>",287 data={'x': ["foo", "bar", "baz'"]})313 rv = render(314 "<a ng-data='{{ data|tojson }}'></a>", data={"x": ["foo", "bar", "baz'"]}315 )316 assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'317318 def test_json_customization(self, app, client):319 class X(object):
2 unmodified lines
322323 class MyEncoder(flask.json.JSONEncoder):324 def default(self, o):325 if isinstance(o, X):298 return '<%d>' % o.val326 return "<%d>" % o.val327 return flask.json.JSONEncoder.default(self, o)328329 class MyDecoder(flask.json.JSONDecoder):330 def __init__(self, *args, **kwargs):303 kwargs.setdefault('object_hook', self.object_hook)331 kwargs.setdefault("object_hook", self.object_hook)332 flask.json.JSONDecoder.__init__(self, *args, **kwargs)333334 def object_hook(self, obj):307 if len(obj) == 1 and '_foo' in obj:308 return X(obj['_foo'])335 if len(obj) == 1 and "_foo" in obj:336 return X(obj["_foo"])337 return obj338339 app.json_encoder = MyEncoder340 app.json_decoder = MyDecoder341314 @app.route('/', methods=['POST'])342 @app.route("/", methods=["POST"])343 def index():316 return flask.json.dumps(flask.request.get_json()['x'])344 return flask.json.dumps(flask.request.get_json()["x"])345318 rv = client.post('/', data=flask.json.dumps({319 'x': {'_foo': 42}320 }), content_type='application/json')346 rv = client.post(347 "/",348 data=flask.json.dumps({"x": {"_foo": 42}}),349 content_type="application/json",350 )351 assert rv.data == b'"<42>"'352353 def test_blueprint_json_customization(self, app, client):354 class X(object):
2 unmodified lines
357358 class MyEncoder(flask.json.JSONEncoder):359 def default(self, o):360 if isinstance(o, X):331 return '<%d>' % o.val361 return "<%d>" % o.val362363 return flask.json.JSONEncoder.default(self, o)364365 class MyDecoder(flask.json.JSONDecoder):366 def __init__(self, *args, **kwargs):337 kwargs.setdefault('object_hook', self.object_hook)367 kwargs.setdefault("object_hook", self.object_hook)368 flask.json.JSONDecoder.__init__(self, *args, **kwargs)369370 def object_hook(self, obj):341 if len(obj) == 1 and '_foo' in obj:342 return X(obj['_foo'])371 if len(obj) == 1 and "_foo" in obj:372 return X(obj["_foo"])373374 return obj375346 bp = flask.Blueprint('bp', __name__)376 bp = flask.Blueprint("bp", __name__)377 bp.json_encoder = MyEncoder378 bp.json_decoder = MyDecoder379350 @bp.route('/bp', methods=['POST'])380 @bp.route("/bp", methods=["POST"])381 def index():352 return flask.json.dumps(flask.request.get_json()['x'])382 return flask.json.dumps(flask.request.get_json()["x"])383384 app.register_blueprint(bp)385356 rv = client.post('/bp', data=flask.json.dumps({357 'x': {'_foo': 42}358 }), content_type='application/json')386 rv = client.post(387 "/bp",388 data=flask.json.dumps({"x": {"_foo": 42}}),389 content_type="application/json",390 )391 assert rv.data == b'"<42>"'392393 def test_modified_url_encoding(self, app, client):394 class ModifiedRequest(flask.Request):363 url_charset = 'euc-kr'395 url_charset = "euc-kr"396397 app.request_class = ModifiedRequest366 app.url_map.charset = 'euc-kr'398 app.url_map.charset = "euc-kr"399368 @app.route('/')400 @app.route("/")401 def index():370 return flask.request.args['foo']402 return flask.request.args["foo"]403372 rv = client.get(u'/?foo=정상처리'.encode('euc-kr'))404 rv = client.get(u"/?foo=정상처리".encode("euc-kr"))405 assert rv.status_code == 200374 assert rv.data == u'정상처리'.encode('utf-8')406 assert rv.data == u"정상처리".encode("utf-8")407376 if not has_encoding('euc-kr'):408 if not has_encoding("euc-kr"):409 test_modified_url_encoding = None410411 def test_json_key_sorting(self, app, client):412 app.debug = True413382 assert app.config['JSON_SORT_KEYS'] == True383 d = dict.fromkeys(range(20), 'foo')414 assert app.config["JSON_SORT_KEYS"] == True415 d = dict.fromkeys(range(20), "foo")416385 @app.route('/')417 @app.route("/")418 def index():419 return flask.jsonify(values=d)420389 rv = client.get('/')390 lines = [x.strip() for x in rv.data.strip().decode('utf-8').splitlines()]421 rv = client.get("/")422 lines = [x.strip() for x in rv.data.strip().decode("utf-8").splitlines()]423 sorted_by_str = [392 '{',424 "{",425 '"values": {',426 '"0": "foo",',427 '"1": "foo",',428 '"10": "foo",',
13 unmodified lines
442 '"6": "foo",',443 '"7": "foo",',444 '"8": "foo",',445 '"9": "foo"',414 '}',415 '}'446 "}",447 "}",448 ]449 sorted_by_int = [418 '{',450 "{",451 '"values": {',452 '"0": "foo",',453 '"1": "foo",',454 '"2": "foo",',
13 unmodified lines
468 '"16": "foo",',469 '"17": "foo",',470 '"18": "foo",',471 '"19": "foo"',440 '}',441 '}'472 "}",473 "}",474 ]475476 try:477 assert lines == sorted_by_int
2 unmodified lines
480481482class TestSendfile(object):483 def test_send_file_regular(self, app, req_ctx):452 rv = flask.send_file('static/index.html')484 rv = flask.send_file("static/index.html")485 assert rv.direct_passthrough454 assert rv.mimetype == 'text/html'455 with app.open_resource('static/index.html') as f:486 assert rv.mimetype == "text/html"487 with app.open_resource("static/index.html") as f:488 rv.direct_passthrough = False489 assert rv.data == f.read()490 rv.close()491492 def test_send_file_xsendfile(self, app, req_ctx, catch_deprecation_warnings):493 app.use_x_sendfile = True462 rv = flask.send_file('static/index.html')494 rv = flask.send_file("static/index.html")495 assert rv.direct_passthrough464 assert 'x-sendfile' in rv.headers465 assert rv.headers['x-sendfile'] == \466 os.path.join(app.root_path, 'static/index.html')467 assert rv.mimetype == 'text/html'496 assert "x-sendfile" in rv.headers497 assert rv.headers["x-sendfile"] == os.path.join(498 app.root_path, "static/index.html"499 )500 assert rv.mimetype == "text/html"501 rv.close()502503 def test_send_file_last_modified(self, app, client):504 last_modified = datetime.datetime(1999, 1, 1)505473 @app.route('/')506 @app.route("/")507 def index():475 return flask.send_file(StringIO("party like it's"),476 last_modified=last_modified,477 mimetype='text/plain')508 return flask.send_file(509 StringIO("party like it's"),510 last_modified=last_modified,511 mimetype="text/plain",512 )513479 rv = client.get('/')514 rv = client.get("/")515 assert rv.last_modified == last_modified516517 def test_send_file_object_without_mimetype(self, app, req_ctx):518 with pytest.raises(ValueError) as excinfo:519 flask.send_file(StringIO("LOL"))485 assert 'Unable to infer MIME-type' in str(excinfo)486 assert 'no filename is available' in str(excinfo)520 assert "Unable to infer MIME-type" in str(excinfo)521 assert "no filename is available" in str(excinfo)522488 flask.send_file(StringIO("LOL"), attachment_filename='filename')523 flask.send_file(StringIO("LOL"), attachment_filename="filename")524525 def test_send_file_object(self, app, req_ctx):491 with open(os.path.join(app.root_path, 'static/index.html'), mode='rb') as f:492 rv = flask.send_file(f, mimetype='text/html')526 with open(os.path.join(app.root_path, "static/index.html"), mode="rb") as f:527 rv = flask.send_file(f, mimetype="text/html")528 rv.direct_passthrough = False494 with app.open_resource('static/index.html') as f:529 with app.open_resource("static/index.html") as f:530 assert rv.data == f.read()496 assert rv.mimetype == 'text/html'531 assert rv.mimetype == "text/html"532 rv.close()533534 app.use_x_sendfile = True535501 with open(os.path.join(app.root_path, 'static/index.html')) as f:502 rv = flask.send_file(f, mimetype='text/html')503 assert rv.mimetype == 'text/html'504 assert 'x-sendfile' not in rv.headers536 with open(os.path.join(app.root_path, "static/index.html")) as f:537 rv = flask.send_file(f, mimetype="text/html")538 assert rv.mimetype == "text/html"539 assert "x-sendfile" not in rv.headers540 rv.close()541542 app.use_x_sendfile = False508 f = StringIO('Test')509 rv = flask.send_file(f, mimetype='application/octet-stream')543 f = StringIO("Test")544 rv = flask.send_file(f, mimetype="application/octet-stream")545 rv.direct_passthrough = False511 assert rv.data == b'Test'512 assert rv.mimetype == 'application/octet-stream'546 assert rv.data == b"Test"547 assert rv.mimetype == "application/octet-stream"548 rv.close()549550 class PyStringIO(object):551 def __init__(self, *args, **kwargs):
1 unmodified line
553554 def __getattr__(self, name):555 return getattr(self._io, name)556522 f = PyStringIO('Test')523 f.name = 'test.txt'557 f = PyStringIO("Test")558 f.name = "test.txt"559 rv = flask.send_file(f, attachment_filename=f.name)560 rv.direct_passthrough = False526 assert rv.data == b'Test'527 assert rv.mimetype == 'text/plain'561 assert rv.data == b"Test"562 assert rv.mimetype == "text/plain"563 rv.close()564530 f = StringIO('Test')531 rv = flask.send_file(f, mimetype='text/plain')565 f = StringIO("Test")566 rv = flask.send_file(f, mimetype="text/plain")567 rv.direct_passthrough = False533 assert rv.data == b'Test'534 assert rv.mimetype == 'text/plain'568 assert rv.data == b"Test"569 assert rv.mimetype == "text/plain"570 rv.close()571572 app.use_x_sendfile = True573539 f = StringIO('Test')540 rv = flask.send_file(f, mimetype='text/html')541 assert 'x-sendfile' not in rv.headers574 f = StringIO("Test")575 rv = flask.send_file(f, mimetype="text/html")576 assert "x-sendfile" not in rv.headers577 rv.close()578579 def test_send_file_pathlike(self, app, req_ctx):545 rv = flask.send_file(FakePath('static/index.html'))580 rv = flask.send_file(FakePath("static/index.html"))581 assert rv.direct_passthrough547 assert rv.mimetype == 'text/html'548 with app.open_resource('static/index.html') as f:582 assert rv.mimetype == "text/html"583 with app.open_resource("static/index.html") as f:584 rv.direct_passthrough = False585 assert rv.data == f.read()586 rv.close()587588 @pytest.mark.skipif(554 not callable(getattr(Range, 'to_content_range_header', None)),555 reason="not implemented within werkzeug"589 not callable(getattr(Range, "to_content_range_header", None)),590 reason="not implemented within werkzeug",591 )592 def test_send_file_range_request(self, app, client):558 @app.route('/')593 @app.route("/")594 def index():560 return flask.send_file('static/index.html', conditional=True)595 return flask.send_file("static/index.html", conditional=True)596562 rv = client.get('/', headers={'Range': 'bytes=4-15'})597 rv = client.get("/", headers={"Range": "bytes=4-15"})598 assert rv.status_code == 206564 with app.open_resource('static/index.html') as f:599 with app.open_resource("static/index.html") as f:600 assert rv.data == f.read()[4:16]601 rv.close()602568 rv = client.get('/', headers={'Range': 'bytes=4-'})603 rv = client.get("/", headers={"Range": "bytes=4-"})604 assert rv.status_code == 206570 with app.open_resource('static/index.html') as f:605 with app.open_resource("static/index.html") as f:606 assert rv.data == f.read()[4:]607 rv.close()608574 rv = client.get('/', headers={'Range': 'bytes=4-1000'})609 rv = client.get("/", headers={"Range": "bytes=4-1000"})610 assert rv.status_code == 206576 with app.open_resource('static/index.html') as f:611 with app.open_resource("static/index.html") as f:612 assert rv.data == f.read()[4:]613 rv.close()614580 rv = client.get('/', headers={'Range': 'bytes=-10'})615 rv = client.get("/", headers={"Range": "bytes=-10"})616 assert rv.status_code == 206582 with app.open_resource('static/index.html') as f:617 with app.open_resource("static/index.html") as f:618 assert rv.data == f.read()[-10:]619 rv.close()620586 rv = client.get('/', headers={'Range': 'bytes=1000-'})621 rv = client.get("/", headers={"Range": "bytes=1000-"})622 assert rv.status_code == 416623 rv.close()624590 rv = client.get('/', headers={'Range': 'bytes=-'})625 rv = client.get("/", headers={"Range": "bytes=-"})626 assert rv.status_code == 416627 rv.close()628594 rv = client.get('/', headers={'Range': 'somethingsomething'})629 rv = client.get("/", headers={"Range": "somethingsomething"})630 assert rv.status_code == 416631 rv.close()632598 last_modified = datetime.datetime.utcfromtimestamp(os.path.getmtime(599 os.path.join(app.root_path, 'static/index.html'))).replace(600 microsecond=0)633 last_modified = datetime.datetime.utcfromtimestamp(634 os.path.getmtime(os.path.join(app.root_path, "static/index.html"))635 ).replace(microsecond=0)636602 rv = client.get('/', headers={'Range': 'bytes=4-15',603 'If-Range': http_date(last_modified)})637 rv = client.get(638 "/", headers={"Range": "bytes=4-15", "If-Range": http_date(last_modified)}639 )640 assert rv.status_code == 206641 rv.close()642607 rv = client.get('/', headers={'Range': 'bytes=4-15', 'If-Range': http_date(608 datetime.datetime(1999, 1, 1))})643 rv = client.get(644 "/",645 headers={646 "Range": "bytes=4-15",647 "If-Range": http_date(datetime.datetime(1999, 1, 1)),648 },649 )650 assert rv.status_code == 200651 rv.close()652653 def test_send_file_range_request_bytesio(self, app, client):613 @app.route('/')654 @app.route("/")655 def index():615 file = io.BytesIO(b'somethingsomething')656 file = io.BytesIO(b"somethingsomething")657 return flask.send_file(617 file, attachment_filename='filename', conditional=True658 file, attachment_filename="filename", conditional=True659 )660620 rv = client.get('/', headers={'Range': 'bytes=4-15'})661 rv = client.get("/", headers={"Range": "bytes=4-15"})662 assert rv.status_code == 206622 assert rv.data == b'somethingsomething'[4:16]663 assert rv.data == b"somethingsomething"[4:16]664 rv.close()665666 @pytest.mark.skipif(626 not callable(getattr(Range, 'to_content_range_header', None)),627 reason="not implemented within werkzeug"667 not callable(getattr(Range, "to_content_range_header", None)),668 reason="not implemented within werkzeug",669 )670 def test_send_file_range_request_xsendfile_invalid(self, app, client):671 # https://github.com/pallets/flask/issues/2526672 app.use_x_sendfile = True673633 @app.route('/')674 @app.route("/")675 def index():635 return flask.send_file('static/index.html', conditional=True)676 return flask.send_file("static/index.html", conditional=True)677637 rv = client.get('/', headers={'Range': 'bytes=1000-'})678 rv = client.get("/", headers={"Range": "bytes=1000-"})679 assert rv.status_code == 416680 rv.close()681682 def test_attachment(self, app, req_ctx):683 app = flask.Flask(__name__)684 with app.test_request_context():644 with open(os.path.join(app.root_path, 'static/index.html')) as f:645 rv = flask.send_file(f, as_attachment=True,646 attachment_filename='index.html')647 value, options = \648 parse_options_header(rv.headers['Content-Disposition'])649 assert value == 'attachment'685 with open(os.path.join(app.root_path, "static/index.html")) as f:686 rv = flask.send_file(687 f, as_attachment=True, attachment_filename="index.html"688 )689 value, options = parse_options_header(rv.headers["Content-Disposition"])690 assert value == "attachment"691 rv.close()692652 with open(os.path.join(app.root_path, 'static/index.html')) as f:653 rv = flask.send_file(f, as_attachment=True,654 attachment_filename='index.html')655 value, options = \656 parse_options_header(rv.headers['Content-Disposition'])657 assert value == 'attachment'658 assert options['filename'] == 'index.html'659 assert 'filename*' not in rv.headers['Content-Disposition']693 with open(os.path.join(app.root_path, "static/index.html")) as f:694 rv = flask.send_file(695 f, as_attachment=True, attachment_filename="index.html"696 )697 value, options = parse_options_header(rv.headers["Content-Disposition"])698 assert value == "attachment"699 assert options["filename"] == "index.html"700 assert "filename*" not in rv.headers["Content-Disposition"]701 rv.close()702662 rv = flask.send_file('static/index.html', as_attachment=True)663 value, options = parse_options_header(rv.headers['Content-Disposition'])664 assert value == 'attachment'665 assert options['filename'] == 'index.html'703 rv = flask.send_file("static/index.html", as_attachment=True)704 value, options = parse_options_header(rv.headers["Content-Disposition"])705 assert value == "attachment"706 assert options["filename"] == "index.html"707 rv.close()708668 rv = flask.send_file(StringIO('Test'), as_attachment=True,669 attachment_filename='index.txt',670 add_etags=False)671 assert rv.mimetype == 'text/plain'672 value, options = parse_options_header(rv.headers['Content-Disposition'])673 assert value == 'attachment'674 assert options['filename'] == 'index.txt'709 rv = flask.send_file(710 StringIO("Test"),711 as_attachment=True,712 attachment_filename="index.txt",713 add_etags=False,714 )715 assert rv.mimetype == "text/plain"716 value, options = parse_options_header(rv.headers["Content-Disposition"])717 assert value == "attachment"718 assert options["filename"] == "index.txt"719 rv.close()720677 @pytest.mark.usefixtures('req_ctx')678 @pytest.mark.parametrize(('filename', 'ascii', 'utf8'), (679 ('index.html', 'index.html', False),680 (u'Ñandú/pingüino.txt', '"Nandu/pinguino.txt"',681 '%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt'),682 (u'Vögel.txt', 'Vogel.txt', 'V%C3%B6gel.txt'),683 # Native string not marked as Unicode on Python 2684 ('tést.txt', 'test.txt', 't%C3%A9st.txt'),685 ))721 @pytest.mark.usefixtures("req_ctx")722 @pytest.mark.parametrize(723 ("filename", "ascii", "utf8"),724 (725 ("index.html", "index.html", False),726 (727 u"Ñandú/pingüino.txt",728 '"Nandu/pinguino.txt"',729 "%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt",730 ),731 (u"Vögel.txt", "Vogel.txt", "V%C3%B6gel.txt"),732 # Native string not marked as Unicode on Python 2733 ("tést.txt", "test.txt", "t%C3%A9st.txt"),734 ),735 )736 def test_attachment_filename_encoding(self, filename, ascii, utf8):687 rv = flask.send_file('static/index.html', as_attachment=True, attachment_filename=filename)737 rv = flask.send_file(738 "static/index.html", as_attachment=True, attachment_filename=filename739 )740 rv.close()689 content_disposition = rv.headers['Content-Disposition']690 assert 'filename=%s' % ascii in content_disposition741 content_disposition = rv.headers["Content-Disposition"]742 assert "filename=%s" % ascii in content_disposition743 if utf8:744 assert "filename*=UTF-8''" + utf8 in content_disposition745 else:746 assert "filename*=UTF-8''" not in content_disposition
1 unmodified line
748 def test_static_file(self, app, req_ctx):749 # default cache timeout is 12 hours750751 # Test with static file handler.700 rv = app.send_static_file('index.html')701 cc = parse_cache_control_header(rv.headers['Cache-Control'])752 rv = app.send_static_file("index.html")753 cc = parse_cache_control_header(rv.headers["Cache-Control"])754 assert cc.max_age == 12 * 60 * 60755 rv.close()756 # Test again with direct use of send_file utility.705 rv = flask.send_file('static/index.html')706 cc = parse_cache_control_header(rv.headers['Cache-Control'])757 rv = flask.send_file("static/index.html")758 cc = parse_cache_control_header(rv.headers["Cache-Control"])759 assert cc.max_age == 12 * 60 * 60760 rv.close()709 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600761 app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 3600762763 # Test with static file handler.712 rv = app.send_static_file('index.html')713 cc = parse_cache_control_header(rv.headers['Cache-Control'])764 rv = app.send_static_file("index.html")765 cc = parse_cache_control_header(rv.headers["Cache-Control"])766 assert cc.max_age == 3600767 rv.close()768 # Test again with direct use of send_file utility.717 rv = flask.send_file('static/index.html')718 cc = parse_cache_control_header(rv.headers['Cache-Control'])769 rv = flask.send_file("static/index.html")770 cc = parse_cache_control_header(rv.headers["Cache-Control"])771 assert cc.max_age == 3600772 rv.close()773774 # Test with static file handler.723 rv = app.send_static_file(FakePath('index.html'))724 cc = parse_cache_control_header(rv.headers['Cache-Control'])775 rv = app.send_static_file(FakePath("index.html"))776 cc = parse_cache_control_header(rv.headers["Cache-Control"])777 assert cc.max_age == 3600778 rv.close()779780 class StaticFileApp(flask.Flask):
2 unmodified lines
783784 app = StaticFileApp(__name__)785 with app.test_request_context():786 # Test with static file handler.735 rv = app.send_static_file('index.html')736 cc = parse_cache_control_header(rv.headers['Cache-Control'])787 rv = app.send_static_file("index.html")788 cc = parse_cache_control_header(rv.headers["Cache-Control"])789 assert cc.max_age == 10790 rv.close()791 # Test again with direct use of send_file utility.740 rv = flask.send_file('static/index.html')741 cc = parse_cache_control_header(rv.headers['Cache-Control'])792 rv = flask.send_file("static/index.html")793 cc = parse_cache_control_header(rv.headers["Cache-Control"])794 assert cc.max_age == 10795 rv.close()796797 def test_send_from_directory(self, app, req_ctx):746 app.root_path = os.path.join(os.path.dirname(__file__),747 'test_apps', 'subdomaintestmodule')748 rv = flask.send_from_directory('static', 'hello.txt')798 app.root_path = os.path.join(799 os.path.dirname(__file__), "test_apps", "subdomaintestmodule"800 )801 rv = flask.send_from_directory("static", "hello.txt")802 rv.direct_passthrough = False750 assert rv.data.strip() == b'Hello Subdomain'803 assert rv.data.strip() == b"Hello Subdomain"804 rv.close()805806 def test_send_from_directory_pathlike(self, app, req_ctx):754 app.root_path = os.path.join(os.path.dirname(__file__),755 'test_apps', 'subdomaintestmodule')756 rv = flask.send_from_directory(FakePath('static'), FakePath('hello.txt'))807 app.root_path = os.path.join(808 os.path.dirname(__file__), "test_apps", "subdomaintestmodule"809 )810 rv = flask.send_from_directory(FakePath("static"), FakePath("hello.txt"))811 rv.direct_passthrough = False758 assert rv.data.strip() == b'Hello Subdomain'812 assert rv.data.strip() == b"Hello Subdomain"813 rv.close()814815 def test_send_from_directory_bad_request(self, app, req_ctx):762 app.root_path = os.path.join(os.path.dirname(__file__),763 'test_apps', 'subdomaintestmodule')816 app.root_path = os.path.join(817 os.path.dirname(__file__), "test_apps", "subdomaintestmodule"818 )819820 with pytest.raises(BadRequest):766 flask.send_from_directory('static', 'bad\x00')821 flask.send_from_directory("static", "bad\x00")822823824class TestUrlFor(object):825 def test_url_for_with_anchor(self, app, req_ctx):771772 @app.route('/')826 @app.route("/")827 def index():774 return '42'828 return "42"829776 assert flask.url_for('index', _anchor='x y') == '/#x%20y'830 assert flask.url_for("index", _anchor="x y") == "/#x%20y"831832 def test_url_for_with_scheme(self, app, req_ctx):779780 @app.route('/')833 @app.route("/")834 def index():782 return '42'835 return "42"836784 assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'837 assert (838 flask.url_for("index", _external=True, _scheme="https")839 == "https://localhost/"840 )841842 def test_url_for_with_scheme_not_external(self, app, req_ctx):787788 @app.route('/')843 @app.route("/")844 def index():790 return '42'845 return "42"846792 pytest.raises(ValueError,793 flask.url_for,794 'index',795 _scheme='https')847 pytest.raises(ValueError, flask.url_for, "index", _scheme="https")848849 def test_url_for_with_alternating_schemes(self, app, req_ctx):798799 @app.route('/')850 @app.route("/")851 def index():801 return '42'852 return "42"853803 assert flask.url_for('index', _external=True) == 'http://localhost/'804 assert flask.url_for('index', _external=True, _scheme='https') == 'https://localhost/'805 assert flask.url_for('index', _external=True) == 'http://localhost/'854 assert flask.url_for("index", _external=True) == "http://localhost/"855 assert (856 flask.url_for("index", _external=True, _scheme="https")857 == "https://localhost/"858 )859 assert flask.url_for("index", _external=True) == "http://localhost/"860861 def test_url_with_method(self, app, req_ctx):862 from flask.views import MethodView863864 class MyView(MethodView):865 def get(self, id=None):866 if id is None:813 return 'List'814 return 'Get %d' % id867 return "List"868 return "Get %d" % id869870 def post(self):817 return 'Create'871 return "Create"872819 myview = MyView.as_view('myview')820 app.add_url_rule('/myview/', methods=['GET'],821 view_func=myview)822 app.add_url_rule('/myview/<int:id>', methods=['GET'],823 view_func=myview)824 app.add_url_rule('/myview/create', methods=['POST'],825 view_func=myview)873 myview = MyView.as_view("myview")874 app.add_url_rule("/myview/", methods=["GET"], view_func=myview)875 app.add_url_rule("/myview/<int:id>", methods=["GET"], view_func=myview)876 app.add_url_rule("/myview/create", methods=["POST"], view_func=myview)877827 assert flask.url_for('myview', _method='GET') == '/myview/'828 assert flask.url_for('myview', id=42, _method='GET') == '/myview/42'829 assert flask.url_for('myview', _method='POST') == '/myview/create'878 assert flask.url_for("myview", _method="GET") == "/myview/"879 assert flask.url_for("myview", id=42, _method="GET") == "/myview/42"880 assert flask.url_for("myview", _method="POST") == "/myview/create"881882883class TestNoImports(object):884 """Test Flasks are created without import.
6 unmodified lines
891 imp modules in the Python standard library.892 """893894 def test_name_with_import_error(self, modules_tmpdir):844 modules_tmpdir.join('importerror.py').write('raise NotImplementedError()')895 modules_tmpdir.join("importerror.py").write("raise NotImplementedError()")896 try:846 flask.Flask('importerror')897 flask.Flask("importerror")898 except NotImplementedError:848 assert False, 'Flask(import_name) is importing import_name.'899 assert False, "Flask(import_name) is importing import_name."900901902class TestStreaming(object):903 def test_streaming_with_context(self, app, client):853854 @app.route('/')904 @app.route("/")905 def index():906 def generate():857 yield 'Hello '858 yield flask.request.args['name']859 yield '!'907 yield "Hello "908 yield flask.request.args["name"]909 yield "!"910911 return flask.Response(flask.stream_with_context(generate()))912863 rv = client.get('/?name=World')864 assert rv.data == b'Hello World!'913 rv = client.get("/?name=World")914 assert rv.data == b"Hello World!"915916 def test_streaming_with_context_as_decorator(self, app, client):867868 @app.route('/')917 @app.route("/")918 def index():919 @flask.stream_with_context920 def generate(hello):921 yield hello873 yield flask.request.args['name']874 yield '!'922 yield flask.request.args["name"]923 yield "!"924876 return flask.Response(generate('Hello '))925 return flask.Response(generate("Hello "))926878 rv = client.get('/?name=World')879 assert rv.data == b'Hello World!'927 rv = client.get("/?name=World")928 assert rv.data == b"Hello World!"929930 def test_streaming_with_context_and_custom_close(self, app, client):931 called = []932
11 unmodified lines
944 return next(self._gen)945946 next = __next__947899 @app.route('/')948 @app.route("/")949 def index():950 def generate():902 yield 'Hello '903 yield flask.request.args['name']904 yield '!'951 yield "Hello "952 yield flask.request.args["name"]953 yield "!"954906 return flask.Response(flask.stream_with_context(907 Wrapper(generate())))955 return flask.Response(flask.stream_with_context(Wrapper(generate())))956909 rv = client.get('/?name=World')910 assert rv.data == b'Hello World!'957 rv = client.get("/?name=World")958 assert rv.data == b"Hello World!"959 assert called == [42]960961 def test_stream_keeps_session(self, app, client):914 @app.route('/')962 @app.route("/")963 def index():916 flask.session['test'] = 'flask'964 flask.session["test"] = "flask"965966 @flask.stream_with_context967 def gen():920 yield flask.session['test']968 yield flask.session["test"]969970 return flask.Response(gen())971924 rv = client.get('/')925 assert rv.data == b'flask'972 rv = client.get("/")973 assert rv.data == b"flask"974975976class TestSafeJoin(object):977 def test_safe_join(self):978 # Valid combinations of *args and expected joined paths.979 passing = (932 (('a/b/c',), 'a/b/c'),933 (('/', 'a/', 'b/', 'c/'), '/a/b/c'),934 (('a', 'b', 'c'), 'a/b/c'),935 (('/a', 'b/c'), '/a/b/c'),936 (('a/b', 'X/../c'), 'a/b/c'),937 (('/a/b', 'c/X/..'), '/a/b/c'),980 (("a/b/c",), "a/b/c"),981 (("/", "a/", "b/", "c/"), "/a/b/c"),982 (("a", "b", "c"), "a/b/c"),983 (("/a", "b/c"), "/a/b/c"),984 (("a/b", "X/../c"), "a/b/c"),985 (("/a/b", "c/X/.."), "/a/b/c"),986 # If last path is '' add a slash939 (('/a/b/c', ''), '/a/b/c/'),987 (("/a/b/c", ""), "/a/b/c/"),988 # Preserve dot slash941 (('/a/b/c', './'), '/a/b/c/.'),942 (('a/b/c', 'X/..'), 'a/b/c/.'),989 (("/a/b/c", "./"), "/a/b/c/."),990 (("a/b/c", "X/.."), "a/b/c/."),991 # Base directory is always considered safe944 (('../', 'a/b/c'), '../a/b/c'),945 (('/..',), '/..'),992 (("../", "a/b/c"), "../a/b/c"),993 (("/..",), "/.."),994 )995996 for args, expected in passing:997 assert flask.safe_join(*args) == expected
1 unmodified line
999 def test_safe_join_exceptions(self):1000 # Should raise werkzeug.exceptions.NotFound on unsafe joins.1001 failing = (1002 # path.isabs and ``..'' checks955 ('/a', 'b', '/c'),956 ('/a', '../b/c'),957 ('/a', '..', 'b/c'),1003 ("/a", "b", "/c"),1004 ("/a", "../b/c"),1005 ("/a", "..", "b/c"),1006 # Boundaries violations after path normalization959 ('/a', 'b/../b/../../c'),960 ('/a', 'b', 'c/../..'),961 ('/a', 'b/../../c'),1007 ("/a", "b/../b/../../c"),1008 ("/a", "b", "c/../.."),1009 ("/a", "b/../../c"),1010 )10111012 for args in failing:1013 with pytest.raises(NotFound):1014 print(flask.safe_join(*args))1015968class TestHelpers(object):1016970 @pytest.mark.parametrize('debug, expected_flag, expected_default_flag', [971 ('', False, False),972 ('0', False, False),973 ('False', False, False),974 ('No', False, False),975 ('True', True, True)976 ])977 def test_get_debug_flag(self, monkeypatch, debug, expected_flag, expected_default_flag):978 monkeypatch.setenv('FLASK_DEBUG', debug)1017class TestHelpers(object):1018 @pytest.mark.parametrize(1019 "debug, expected_flag, expected_default_flag",1020 [1021 ("", False, False),1022 ("0", False, False),1023 ("False", False, False),1024 ("No", False, False),1025 ("True", True, True),1026 ],1027 )1028 def test_get_debug_flag(1029 self, monkeypatch, debug, expected_flag, expected_default_flag1030 ):1031 monkeypatch.setenv("FLASK_DEBUG", debug)1032 if expected_flag is None:1033 assert get_debug_flag() is None1034 else:1035 assert get_debug_flag() == expected_flag1036 assert get_debug_flag() == expected_default_flag1037985 @pytest.mark.parametrize('env, ref_env, debug', [986 ('', 'production', False),987 ('production', 'production', False),988 ('development', 'development', True),989 ('other', 'other', False),990 ])1038 @pytest.mark.parametrize(1039 "env, ref_env, debug",1040 [1041 ("", "production", False),1042 ("production", "production", False),1043 ("development", "development", True),1044 ("other", "other", False),1045 ],1046 )1047 def test_get_env(self, monkeypatch, env, ref_env, debug):992 monkeypatch.setenv('FLASK_ENV', env)1048 monkeypatch.setenv("FLASK_ENV", env)1049 assert get_debug_flag() == debug1050 assert get_env() == ref_env10511052 def test_make_response(self):1053 app = flask.Flask(__name__)1054 with app.test_request_context():1055 rv = flask.helpers.make_response()1056 assert rv.status_code == 2001001 assert rv.mimetype == 'text/html'1057 assert rv.mimetype == "text/html"10581003 rv = flask.helpers.make_response('Hello')1059 rv = flask.helpers.make_response("Hello")1060 assert rv.status_code == 2001005 assert rv.data == b'Hello'1006 assert rv.mimetype == 'text/html'1061 assert rv.data == b"Hello"1062 assert rv.mimetype == "text/html"
modified:tests/test_instance_config.py+67 added-59 removed
15 unmodified lines
161718def test_explicit_instance_paths(modules_tmpdir):19 with pytest.raises(ValueError) as excinfo:20 flask.Flask(__name__, instance_path='instance')21 assert 'must be absolute' in str(excinfo.value)20 flask.Flask(__name__, instance_path="instance")21 assert "must be absolute" in str(excinfo.value)2223 app = flask.Flask(__name__, instance_path=str(modules_tmpdir))24 assert app.instance_path == str(modules_tmpdir)252627def test_main_module_paths(modules_tmpdir, purge_module):28 app = modules_tmpdir.join('main_app.py')28 app = modules_tmpdir.join("main_app.py")29 app.write('import flask\n\napp = flask.Flask("__main__")')30 purge_module('main_app')30 purge_module("main_app")3132 from main_app import app3334 here = os.path.abspath(os.getcwd())34 assert app.instance_path == os.path.join(here, 'instance')35 assert app.instance_path == os.path.join(here, "instance")363738def test_uninstalled_module_paths(modules_tmpdir, purge_module):38 app = modules_tmpdir.join('config_module_app.py').write(39 'import os\n'40 'import flask\n'41 'here = os.path.abspath(os.path.dirname(__file__))\n'42 'app = flask.Flask(__name__)\n'39 app = modules_tmpdir.join("config_module_app.py").write(40 "import os\n"41 "import flask\n"42 "here = os.path.abspath(os.path.dirname(__file__))\n"43 "app = flask.Flask(__name__)\n"44 )44 purge_module('config_module_app')45 purge_module("config_module_app")4647 from config_module_app import app47 assert app.instance_path == str(modules_tmpdir.join('instance'))4849 assert app.instance_path == str(modules_tmpdir.join("instance"))505152def test_uninstalled_package_paths(modules_tmpdir, purge_module):51 app = modules_tmpdir.mkdir('config_package_app')52 init = app.join('__init__.py')53 app = modules_tmpdir.mkdir("config_package_app")54 init = app.join("__init__.py")55 init.write(54 'import os\n'55 'import flask\n'56 'here = os.path.abspath(os.path.dirname(__file__))\n'57 'app = flask.Flask(__name__)\n'56 "import os\n"57 "import flask\n"58 "here = os.path.abspath(os.path.dirname(__file__))\n"59 "app = flask.Flask(__name__)\n"60 )59 purge_module('config_package_app')61 purge_module("config_package_app")6263 from config_package_app import app62 assert app.instance_path == str(modules_tmpdir.join('instance'))6465 assert app.instance_path == str(modules_tmpdir.join("instance"))6665def test_installed_module_paths(modules_tmpdir, modules_tmpdir_prefix,66 purge_module, site_packages, limit_loader):67 site_packages.join('site_app.py').write(68 'import flask\n'69 'app = flask.Flask(__name__)\n'6768def test_installed_module_paths(69 modules_tmpdir, modules_tmpdir_prefix, purge_module, site_packages, limit_loader70):71 site_packages.join("site_app.py").write(72 "import flask\n" "app = flask.Flask(__name__)\n"73 )71 purge_module('site_app')74 purge_module("site_app")7576 from site_app import app74 assert app.instance_path == \75 modules_tmpdir.join('var').join('site_app-instance')7778 assert app.instance_path == modules_tmpdir.join("var").join("site_app-instance")7978def test_installed_package_paths(limit_loader, modules_tmpdir,79 modules_tmpdir_prefix, purge_module,80 monkeypatch):81 installed_path = modules_tmpdir.mkdir('path')8081def test_installed_package_paths(82 limit_loader, modules_tmpdir, modules_tmpdir_prefix, purge_module, monkeypatch83):84 installed_path = modules_tmpdir.mkdir("path")85 monkeypatch.syspath_prepend(installed_path)8684 app = installed_path.mkdir('installed_package')85 init = app.join('__init__.py')86 init.write('import flask\napp = flask.Flask(__name__)')87 purge_module('installed_package')87 app = installed_path.mkdir("installed_package")88 init = app.join("__init__.py")89 init.write("import flask\napp = flask.Flask(__name__)")90 purge_module("installed_package")9192 from installed_package import app90 assert app.instance_path == \91 modules_tmpdir.join('var').join('installed_package-instance')9394 assert app.instance_path == modules_tmpdir.join("var").join(95 "installed_package-instance"96 )9794def test_prefix_package_paths(limit_loader, modules_tmpdir,95 modules_tmpdir_prefix, purge_module,96 site_packages):97 app = site_packages.mkdir('site_package')98 init = app.join('__init__.py')99 init.write('import flask\napp = flask.Flask(__name__)')100 purge_module('site_package')9899def test_prefix_package_paths(100 limit_loader, modules_tmpdir, modules_tmpdir_prefix, purge_module, site_packages101):102 app = site_packages.mkdir("site_package")103 init = app.join("__init__.py")104 init.write("import flask\napp = flask.Flask(__name__)")105 purge_module("site_package")106107 import site_package103 assert site_package.app.instance_path == \104 modules_tmpdir.join('var').join('site_package-instance')108109 assert site_package.app.instance_path == modules_tmpdir.join("var").join(110 "site_package-instance"111 )112107def test_egg_installed_paths(install_egg, modules_tmpdir,108 modules_tmpdir_prefix):109 modules_tmpdir.mkdir('site_egg').join('__init__.py').write(110 'import flask\n\napp = flask.Flask(__name__)'113114def test_egg_installed_paths(install_egg, modules_tmpdir, modules_tmpdir_prefix):115 modules_tmpdir.mkdir("site_egg").join("__init__.py").write(116 "import flask\n\napp = flask.Flask(__name__)"117 )112 install_egg('site_egg')118 install_egg("site_egg")119 try:120 import site_egg115 assert site_egg.app.instance_path == \116 str(modules_tmpdir.join('var/').join('site_egg-instance'))121122 assert site_egg.app.instance_path == str(123 modules_tmpdir.join("var/").join("site_egg-instance")124 )125 finally:118 if 'site_egg' in sys.modules:119 del sys.modules['site_egg']126 if "site_egg" in sys.modules:127 del sys.modules["site_egg"]128129122@pytest.mark.skipif(not PY2, reason='This only works under Python 2.')130@pytest.mark.skipif(not PY2, reason="This only works under Python 2.")131def test_meta_path_loader_without_is_package(request, modules_tmpdir):124 app = modules_tmpdir.join('unimportable.py')125 app.write('import flask\napp = flask.Flask(__name__)')132 app = modules_tmpdir.join("unimportable.py")133 app.write("import flask\napp = flask.Flask(__name__)")134135 class Loader(object):136 def find_module(self, name, path=None):137 return self
6 unmodified lines
modified:tests/test_json_tag.py+21 added-18 removed
14 unmodified lines
15from flask import Markup16from flask.json.tag import TaggedJSONSerializer, JSONTag171819@pytest.mark.parametrize("data", (20 {' t': (1, 2, 3)},21 {' t__': b'a'},22 {' di': ' di'},23 {'x': (1, 2, 3), 'y': 4},24 (1, 2, 3),25 [(1, 2, 3)],26 b'\xff',27 Markup('<html>'),28 uuid4(),29 datetime.utcnow().replace(microsecond=0),30))19@pytest.mark.parametrize(20 "data",21 (22 {" t": (1, 2, 3)},23 {" t__": b"a"},24 {" di": " di"},25 {"x": (1, 2, 3), "y": 4},26 (1, 2, 3),27 [(1, 2, 3)],28 b"\xff",29 Markup("<html>"),30 uuid4(),31 datetime.utcnow().replace(microsecond=0),32 ),33)34def test_dump_load_unchanged(data):35 s = TaggedJSONSerializer()36 assert s.loads(s.dumps(data)) == data373839def test_duplicate_tag():40 class TagDict(JSONTag):38 key = ' d'41 key = " d"4243 s = TaggedJSONSerializer()44 pytest.raises(KeyError, s.register, TagDict)45 s.register(TagDict, force=True, index=0)43 assert isinstance(s.tags[' d'], TagDict)46 assert isinstance(s.tags[" d"], TagDict)47 assert isinstance(s.order[0], TagDict)484950def test_custom_tag():
2 unmodified lines
53 self.data = data5455 class TagFoo(JSONTag):56 __slots__ = ()54 key = ' f'57 key = " f"5859 def check(self, value):60 return isinstance(value, Foo)61
4 unmodified lines
66 return Foo(value)6768 s = TaggedJSONSerializer()69 s.register(TagFoo)67 assert s.loads(s.dumps(Foo('bar'))).data == 'bar'70 assert s.loads(s.dumps(Foo("bar"))).data == "bar"717273def test_tag_interface():74 t = JSONTag(None)
3 unmodified lines
787980def test_tag_order():81 class Tag1(JSONTag):79 key = ' 1'82 key = " 1"8384 class Tag2(JSONTag):82 key = ' 2'85 key = " 2"8687 s = TaggedJSONSerializer()8889 s.register(Tag1, index=-1)
4 unmodified lines
modified:tests/test_logging.py+16 added-18 removed
11 unmodified lines
1213import pytest1415from flask._compat import StringIO16from flask.logging import default_handler, has_level_handler, \17 wsgi_errors_stream16from flask.logging import default_handler, has_level_handler, wsgi_errors_stream171819@pytest.fixture(autouse=True)20def reset_logging(pytestconfig):21 root_handlers = logging.root.handlers[:]22 logging.root.handlers = []23 root_level = logging.root.level2426 logger = logging.getLogger('flask.app')25 logger = logging.getLogger("flask.app")26 logger.handlers = []27 logger.setLevel(logging.NOTSET)2830 logging_plugin = pytestconfig.pluginmanager.unregister(31 name='logging-plugin')29 logging_plugin = pytestconfig.pluginmanager.unregister(name="logging-plugin")3031 yield3233 logging.root.handlers[:] = root_handlers
2 unmodified lines
36 logger.handlers = []37 logger.setLevel(logging.NOTSET)3839 if logging_plugin:42 pytestconfig.pluginmanager.register(logging_plugin, 'logging-plugin')40 pytestconfig.pluginmanager.register(logging_plugin, "logging-plugin")414243def test_logger(app):46 assert app.logger.name == 'flask.app'44 assert app.logger.name == "flask.app"45 assert app.logger.level == logging.NOTSET46 assert app.logger.handlers == [default_handler]4748
9 unmodified lines
58 assert not app.logger.handlers596061def test_wsgi_errors_stream(app, client):64 @app.route('/')62 @app.route("/")63 def index():66 app.logger.error('test')67 return ''64 app.logger.error("test")65 return ""6667 stream = StringIO()70 client.get('/', errors_stream=stream)71 assert 'ERROR in test_logging: test' in stream.getvalue()68 client.get("/", errors_stream=stream)69 assert "ERROR in test_logging: test" in stream.getvalue()7071 assert wsgi_errors_stream._get_current_object() is sys.stderr7273 with app.test_request_context(errors_stream=stream):74 assert wsgi_errors_stream._get_current_object() is stream757677def test_has_level_handler():80 logger = logging.getLogger('flask.app')78 logger = logging.getLogger("flask.app")79 assert not has_level_handler(logger)8081 handler = logging.StreamHandler()82 logging.root.addHandler(handler)
7 unmodified lines
90 assert not has_level_handler(logger)919293def test_log_view_exception(app, client):96 @app.route('/')94 @app.route("/")95 def index():98 raise Exception('test')96 raise Exception("test")9798 app.testing = False99 stream = StringIO()102 rv = client.get('/', errors_stream=stream)100 rv = client.get("/", errors_stream=stream)101 assert rv.status_code == 500102 assert rv.data103 err = stream.getvalue()106 assert 'Exception on / [GET]' in err107 assert 'Exception: test' in err104 assert "Exception on / [GET]" in err105 assert "Exception: test" in err
modified:tests/test_regression.py+16 added-17 removed
20 unmodified lines
21_gc_lock = threading.Lock()222324class assert_no_leak(object):2525 def __enter__(self):26 gc.disable()27 _gc_lock.acquire()28 loc = flask._request_ctx_stack._local
1 unmodified line
30 # Force Python to track this dictionary at all times.31 # This is necessary since Python only starts tracking32 # dicts if they contain mutable objects. It's a horrible,33 # horrible hack but makes this kinda testable.35 loc.__storage__['FOOO'] = [1, 2, 3]34 loc.__storage__["FOOO"] = [1, 2, 3]3536 gc.collect()37 self.old_objects = len(gc.get_objects())3839 def __exit__(self, exc_type, exc_value, tb):40 gc.collect()41 new_objects = len(gc.get_objects())42 if new_objects > self.old_objects:44 pytest.fail('Example code leaked')43 pytest.fail("Example code leaked")44 _gc_lock.release()45 gc.enable()464748def test_memory_consumption():49 app = flask.Flask(__name__)5052 @app.route('/')51 @app.route("/")52 def index():54 return flask.render_template('simple_template.html', whiskey=42)53 return flask.render_template("simple_template.html", whiskey=42)5455 def fire():56 with app.test_client() as c:58 rv = c.get('/')57 rv = c.get("/")58 assert rv.status_code == 20060 assert rv.data == b'<h1>42</h1>'59 assert rv.data == b"<h1>42</h1>"6061 # Trigger caches62 fire()6364 # This test only works on CPython 2.7.66 if sys.version_info >= (2, 7) and \67 not hasattr(sys, 'pypy_translation_info'):65 if sys.version_info >= (2, 7) and not hasattr(sys, "pypy_translation_info"):66 with assert_no_leak():67 for x in range(10):68 fire()697071def test_safe_join_toplevel_pardir():72 from flask.helpers import safe_join7374 with pytest.raises(NotFound):76 safe_join('/foo', '..')75 safe_join("/foo", "..")767778def test_aborting(app):79 class Foo(Exception):
2 unmodified lines
82 @app.errorhandler(Foo)83 def handle_foo(e):84 return str(e.whatever)8587 @app.route('/')86 @app.route("/")87 def index():89 raise flask.abort(flask.redirect(flask.url_for('test')))88 raise flask.abort(flask.redirect(flask.url_for("test")))8991 @app.route('/test')90 @app.route("/test")91 def test():92 raise Foo()9394 with app.test_client() as c:96 rv = c.get('/')97 assert rv.headers['Location'] == 'http://localhost/test'98 rv = c.get('/test')99 assert rv.data == b'42'95 rv = c.get("/")96 assert rv.headers["Location"] == "http://localhost/test"97 rv = c.get("/test")98 assert rv.data == b"42"
modified:tests/test_reqctx.py+63 added-56 removed
40 unmodified lines
41 def end_of_request(exception):42 buffer.append(exception)4344 try:45 raise Exception('dummy')45 raise Exception("dummy")46 except Exception:47 pass4849 with app.test_request_context():
10 unmodified lines
6061 with app.test_request_context():62 assert buffer == []63 try:64 raise Exception('dummy')64 raise Exception("dummy")65 except Exception:66 pass67 assert buffer == [None]686970def test_proper_test_request_context(app):71 app.config.update(72 SERVER_NAME='localhost.localdomain:5000'73 )71 app.config.update(SERVER_NAME="localhost.localdomain:5000")7275 @app.route('/')73 @app.route("/")74 def index():75 return None7679 @app.route('/', subdomain='foo')77 @app.route("/", subdomain="foo")78 def sub():79 return None8083 with app.test_request_context('/'):84 assert flask.url_for('index', _external=True) == \85 'http://localhost.localdomain:5000/'81 with app.test_request_context("/"):82 assert (83 flask.url_for("index", _external=True)84 == "http://localhost.localdomain:5000/"85 )8687 with app.test_request_context('/'):88 assert flask.url_for('sub', _external=True) == \89 'http://foo.localhost.localdomain:5000/'87 with app.test_request_context("/"):88 assert (89 flask.url_for("sub", _external=True)90 == "http://foo.localhost.localdomain:5000/"91 )9293 try:92 with app.test_request_context('/', environ_overrides={'HTTP_HOST': 'localhost'}):94 with app.test_request_context(95 "/", environ_overrides={"HTTP_HOST": "localhost"}96 ):97 pass98 except ValueError as e:99 assert str(e) == (100 "the server name provided "101 "('localhost.localdomain:5000') does not match the "102 "server name from the WSGI environment ('localhost')"103 )104101 app.config.update(SERVER_NAME='localhost')102 with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost'}):105 app.config.update(SERVER_NAME="localhost")106 with app.test_request_context("/", environ_overrides={"SERVER_NAME": "localhost"}):107 pass108105 app.config.update(SERVER_NAME='localhost:80')106 with app.test_request_context('/', environ_overrides={'SERVER_NAME': 'localhost:80'}):109 app.config.update(SERVER_NAME="localhost:80")110 with app.test_request_context(111 "/", environ_overrides={"SERVER_NAME": "localhost:80"}112 ):113 pass114115116def test_context_binding(app):111 @app.route('/')117 @app.route("/")118 def index():113 return 'Hello %s!' % flask.request.args['name']119 return "Hello %s!" % flask.request.args["name"]120115 @app.route('/meh')121 @app.route("/meh")122 def meh():123 return flask.request.url124119 with app.test_request_context('/?name=World'):120 assert index() == 'Hello World!'121 with app.test_request_context('/meh'):122 assert meh() == 'http://localhost/meh'125 with app.test_request_context("/?name=World"):126 assert index() == "Hello World!"127 with app.test_request_context("/meh"):128 assert meh() == "http://localhost/meh"129 assert flask._request_ctx_stack.top is None130131132def test_context_test(app):
8 unmodified lines
141 ctx.pop()142143144def test_manual_context_binding(app):139 @app.route('/')145 @app.route("/")146 def index():141 return 'Hello %s!' % flask.request.args['name']147 return "Hello %s!" % flask.request.args["name"]148143 ctx = app.test_request_context('/?name=World')149 ctx = app.test_request_context("/?name=World")150 ctx.push()145 assert index() == 'Hello World!'151 assert index() == "Hello World!"152 ctx.pop()153 with pytest.raises(RuntimeError):154 index()155156151@pytest.mark.skipif(greenlet is None, reason='greenlet not installed')157@pytest.mark.skipif(greenlet is None, reason="greenlet not installed")158class TestGreenletContextCopying(object):153159 def test_greenlet_context_copying(self, app, client):160 greenlets = []161157 @app.route('/')162 @app.route("/")163 def index():159 flask.session['fizz'] = 'buzz'164 flask.session["fizz"] = "buzz"165 reqctx = flask._request_ctx_stack.top.copy()166167 def g():168 assert not flask.request169 assert not flask.current_app170 with reqctx:171 assert flask.request172 assert flask.current_app == app168 assert flask.request.path == '/'169 assert flask.request.args['foo'] == 'bar'170 assert flask.session.get('fizz') == 'buzz'173 assert flask.request.path == "/"174 assert flask.request.args["foo"] == "bar"175 assert flask.session.get("fizz") == "buzz"176 assert not flask.request177 return 42178179 greenlets.append(greenlet(g))175 return 'Hello World!'180 return "Hello World!"181177 rv = client.get('/?foo=bar')178 assert rv.data == b'Hello World!'182 rv = client.get("/?foo=bar")183 assert rv.data == b"Hello World!"184185 result = greenlets[0].run()186 assert result == 42187188 def test_greenlet_context_copying_api(self, app, client):189 greenlets = []190186 @app.route('/')191 @app.route("/")192 def index():188 flask.session['fizz'] = 'buzz'193 flask.session["fizz"] = "buzz"194 reqctx = flask._request_ctx_stack.top.copy()195196 @flask.copy_current_request_context197 def g():198 assert flask.request199 assert flask.current_app == app195 assert flask.request.path == '/'196 assert flask.request.args['foo'] == 'bar'197 assert flask.session.get('fizz') == 'buzz'200 assert flask.request.path == "/"201 assert flask.request.args["foo"] == "bar"202 assert flask.session.get("fizz") == "buzz"203 return 42204205 greenlets.append(greenlet(g))201 return 'Hello World!'206 return "Hello World!"207203 rv = client.get('/?foo=bar')204 assert rv.data == b'Hello World!'208 rv = client.get("/?foo=bar")209 assert rv.data == b"Hello World!"210211 result = greenlets[0].run()212 assert result == 42213
10 unmodified lines
224 session_interface = FailingSessionInterface()225226 app = CustomFlask(__name__)227223 @app.route('/')228 @app.route("/")229 def index():230 # shouldn't get here231 assert False232228 response = app.test_client().get('/')233 response = app.test_client().get("/")234 assert response.status_code == 500235 assert not flask.request236 assert not flask.current_app237
5 unmodified lines
243 # because werkzeug enforces latin1 on Python 2.244 # However it works when actually passed to the server.245246 from flask.testing import make_test_environ_builder247248 builder = make_test_environ_builder(app)249 environ = builder.get_environ()250251 # use a non-printable character in the Host - this is key to this test246 environ['HTTP_HOST'] = u'\x8a'252 environ["HTTP_HOST"] = u"\x8a"253254 with app.request_context(environ):255 response = app.full_dispatch_request()256 assert response.status_code == 400
1 unmodified line
258259def test_environ_for_valid_idna_completes():260 app = flask.Flask(__name__)261256 @app.route('/')262 @app.route("/")263 def index():258 return 'Hello World!'264 return "Hello World!"265266 # We cannot use app.test_client() for the Unicode-rich Host header,267 # because werkzeug enforces latin1 on Python 2.268 # However it works when actually passed to the server.269270 from flask.testing import make_test_environ_builder271272 builder = make_test_environ_builder(app)273 environ = builder.get_environ()274275 # these characters are all IDNA-compatible269 environ['HTTP_HOST'] = u'ąśźäüжŠßя.com'276 environ["HTTP_HOST"] = u"ąśźäüжŠßя.com"277278 with app.request_context(environ):279 response = app.full_dispatch_request()280
2 unmodified lines
283284def test_normal_environ_completes():285 app = flask.Flask(__name__)286280 @app.route('/')287 @app.route("/")288 def index():282 return 'Hello World!'289 return "Hello World!"290284 response = app.test_client().get('/', headers={'host': 'xn--on-0ia.com'})291 response = app.test_client().get("/", headers={"host": "xn--on-0ia.com"})292 assert response.status_code == 200
modified:tests/test_signals.py+51 added-47 removed
17 unmodified lines
1819import flask2021pytestmark = pytest.mark.skipif(22 blinker is None,23 reason='Signals require the blinker library.'22 blinker is None, reason="Signals require the blinker library."23)242526def test_template_rendered(app, client):28 @app.route('/')27 @app.route("/")28 def index():30 return flask.render_template('simple_template.html', whiskey=42)29 return flask.render_template("simple_template.html", whiskey=42)3031 recorded = []3233 def record(sender, template, context):34 recorded.append((template, context))3536 flask.template_rendered.connect(record, app)37 try:39 client.get('/')38 client.get("/")39 assert len(recorded) == 140 template, context = recorded[0]42 assert template.name == 'simple_template.html'43 assert context['whiskey'] == 4241 assert template.name == "simple_template.html"42 assert context["whiskey"] == 4243 finally:44 flask.template_rendered.disconnect(record, app)454647def test_before_render_template():48 app = flask.Flask(__name__)4951 @app.route('/')50 @app.route("/")51 def index():53 return flask.render_template('simple_template.html', whiskey=42)52 return flask.render_template("simple_template.html", whiskey=42)5354 recorded = []5556 def record(sender, template, context):58 context['whiskey'] = 4357 context["whiskey"] = 4358 recorded.append((template, context))5960 flask.before_render_template.connect(record, app)61 try:63 rv = app.test_client().get('/')62 rv = app.test_client().get("/")63 assert len(recorded) == 164 template, context = recorded[0]66 assert template.name == 'simple_template.html'67 assert context['whiskey'] == 4368 assert rv.data == b'<h1>43</h1>'65 assert template.name == "simple_template.html"66 assert context["whiskey"] == 4367 assert rv.data == b"<h1>43</h1>"68 finally:69 flask.before_render_template.disconnect(record, app)7071
1 unmodified line
73 app = flask.Flask(__name__)74 calls = []7576 def before_request_signal(sender):78 calls.append('before-signal')77 calls.append("before-signal")7879 def after_request_signal(sender, response):81 assert response.data == b'stuff'82 calls.append('after-signal')80 assert response.data == b"stuff"81 calls.append("after-signal")8283 @app.before_request84 def before_request_handler():86 calls.append('before-handler')85 calls.append("before-handler")8687 @app.after_request88 def after_request_handler(response):90 calls.append('after-handler')91 response.data = 'stuff'89 calls.append("after-handler")90 response.data = "stuff"91 return response9294 @app.route('/')93 @app.route("/")94 def index():96 calls.append('handler')97 return 'ignored anyway'95 calls.append("handler")96 return "ignored anyway"9798 flask.request_started.connect(before_request_signal, app)99 flask.request_finished.connect(after_request_signal, app)100101 try:103 rv = app.test_client().get('/')104 assert rv.data == b'stuff'102 rv = app.test_client().get("/")103 assert rv.data == b"stuff"104106 assert calls == ['before-signal', 'before-handler', 'handler',107 'after-handler', 'after-signal']105 assert calls == [106 "before-signal",107 "before-handler",108 "handler",109 "after-handler",110 "after-signal",111 ]112 finally:113 flask.request_started.disconnect(before_request_signal, app)114 flask.request_finished.disconnect(after_request_signal, app)115
1 unmodified line
117def test_request_exception_signal():118 app = flask.Flask(__name__)119 recorded = []120117 @app.route('/')121 @app.route("/")122 def index():123 1 // 0124125 def record(sender, exception):126 recorded.append(exception)127128 flask.got_request_exception.connect(record, app)129 try:126 assert app.test_client().get('/').status_code == 500130 assert app.test_client().get("/").status_code == 500131 assert len(recorded) == 1132 assert isinstance(recorded[0], ZeroDivisionError)133 finally:134 flask.got_request_exception.disconnect(record, app)
3 unmodified lines
138 app = flask.Flask(__name__)139 recorded = []140141 def record_push(sender, **kwargs):138 recorded.append('push')142 recorded.append("push")143144 def record_pop(sender, **kwargs):141 recorded.append('pop')145 recorded.append("pop")146143 @app.route('/')147 @app.route("/")148 def index():145 return 'Hello'149 return "Hello"150151 flask.appcontext_pushed.connect(record_push, app)152 flask.appcontext_popped.connect(record_pop, app)153 try:154 with app.test_client() as c:151 rv = c.get('/')152 assert rv.data == b'Hello'153 assert recorded == ['push']154 assert recorded == ['push', 'pop']155 rv = c.get("/")156 assert rv.data == b"Hello"157 assert recorded == ["push"]158 assert recorded == ["push", "pop"]159 finally:160 flask.appcontext_pushed.disconnect(record_push, app)161 flask.appcontext_popped.disconnect(record_pop, app)162163164def test_flash_signal(app):161 @app.route('/')165 @app.route("/")166 def index():163 flask.flash('This is a flash message', category='notice')164 return flask.redirect('/other')167 flask.flash("This is a flash message", category="notice")168 return flask.redirect("/other")169170 recorded = []171172 def record(sender, message, category):
2 unmodified lines
175 flask.message_flashed.connect(record, app)176 try:177 client = app.test_client()178 with client.session_transaction():175 client.get('/')179 client.get("/")180 assert len(recorded) == 1181 message, category = recorded[0]178 assert message == 'This is a flash message'179 assert category == 'notice'182 assert message == "This is a flash message"183 assert category == "notice"184 finally:185 flask.message_flashed.disconnect(record, app)186187
1 unmodified line
189 app = flask.Flask(__name__)190 recorded = []191192 def record_teardown(sender, **kwargs):189 recorded.append(('tear_down', kwargs))193 recorded.append(("tear_down", kwargs))194191 @app.route('/')195 @app.route("/")196 def index():197 1 // 0198199 flask.appcontext_tearing_down.connect(record_teardown, app)200 try:201 with app.test_client() as c:198 rv = c.get('/')202 rv = c.get("/")203 assert rv.status_code == 500204 assert recorded == []201 assert recorded == [('tear_down', {'exc': None})]205 assert recorded == [("tear_down", {"exc": None})]206 finally:207 flask.appcontext_tearing_down.disconnect(record_teardown, app)
modified:tests/test_subclassing.py+4 added-4 removed
21 unmodified lines
2223 out = StringIO()24 app = SuppressedFlask(__name__)2526 @app.route('/')26 @app.route("/")27 def index():28 raise Exception('test')28 raise Exception("test")2930 rv = app.test_client().get('/', errors_stream=out)30 rv = app.test_client().get("/", errors_stream=out)31 assert rv.status_code == 50032 assert b'Internal Server Error' in rv.data32 assert b"Internal Server Error" in rv.data33 assert not out.getvalue()
modified:tests/test_templating.py+162 added-154 removed
18 unmodified lines
1920def test_context_processing(app, client):21 @app.context_processor22 def context_processor():23 return {'injected_value': 42}23 return {"injected_value": 42}2425 @app.route('/')25 @app.route("/")26 def index():27 return flask.render_template('context_template.html', value=23)27 return flask.render_template("context_template.html", value=23)2829 rv = client.get('/')30 assert rv.data == b'<p>23|42'29 rv = client.get("/")30 assert rv.data == b"<p>23|42"313233def test_original_win(app, client):34 @app.route('/')34 @app.route("/")35 def index():36 return flask.render_template_string('{{ config }}', config=42)36 return flask.render_template_string("{{ config }}", config=42)3738 rv = client.get('/')39 assert rv.data == b'42'38 rv = client.get("/")39 assert rv.data == b"42"404142def test_request_less_rendering(app, app_ctx):43 app.config['WORLD_NAME'] = 'Special World'43 app.config["WORLD_NAME"] = "Special World"4445 @app.context_processor46 def context_processor():47 return dict(foo=42)4849 rv = flask.render_template_string('Hello {{ config.WORLD_NAME }} '50 '{{ foo }}')51 assert rv == 'Hello Special World 42'49 rv = flask.render_template_string("Hello {{ config.WORLD_NAME }} " "{{ foo }}")50 assert rv == "Hello Special World 42"515253def test_standard_context(app, client):55 @app.route('/')54 @app.route("/")55 def index():56 flask.g.foo = 2358 flask.session['test'] = 'aha'59 return flask.render_template_string('''57 flask.session["test"] = "aha"58 return flask.render_template_string(59 """60 {{ request.args.foo }}61 {{ g.foo }}62 {{ config.DEBUG }}63 {{ session.test }}64 ''')64 """65 )6666 rv = client.get('/?foo=42')67 assert rv.data.split() == [b'42', b'23', b'False', b'aha']67 rv = client.get("/?foo=42")68 assert rv.data.split() == [b"42", b"23", b"False", b"aha"]697071def test_escaping(app, client):71 text = '<p>Hello World!'72 text = "<p>Hello World!"7373 @app.route('/')74 @app.route("/")75 def index():75 return flask.render_template('escaping_template.html', text=text,76 html=flask.Markup(text))76 return flask.render_template(77 "escaping_template.html", text=text, html=flask.Markup(text)78 )7978 lines = client.get('/').data.splitlines()80 lines = client.get("/").data.splitlines()81 assert lines == [80 b'&lt;p&gt;Hello World!',81 b'<p>Hello World!',82 b'<p>Hello World!',83 b'<p>Hello World!',84 b'&lt;p&gt;Hello World!',85 b'<p>Hello World!'82 b"&lt;p&gt;Hello World!",83 b"<p>Hello World!",84 b"<p>Hello World!",85 b"<p>Hello World!",86 b"&lt;p&gt;Hello World!",87 b"<p>Hello World!",88 ]899091def test_no_escaping(app, client):90 text = '<p>Hello World!'92 text = "<p>Hello World!"9392 @app.route('/')94 @app.route("/")95 def index():94 return flask.render_template('non_escaping_template.txt', text=text,95 html=flask.Markup(text))96 return flask.render_template(97 "non_escaping_template.txt", text=text, html=flask.Markup(text)98 )9997 lines = client.get('/').data.splitlines()100 lines = client.get("/").data.splitlines()101 assert lines == [99 b'<p>Hello World!',100 b'<p>Hello World!',101 b'<p>Hello World!',102 b'<p>Hello World!',103 b'&lt;p&gt;Hello World!',104 b'<p>Hello World!',105 b'<p>Hello World!',106 b'<p>Hello World!'102 b"<p>Hello World!",103 b"<p>Hello World!",104 b"<p>Hello World!",105 b"<p>Hello World!",106 b"&lt;p&gt;Hello World!",107 b"<p>Hello World!",108 b"<p>Hello World!",109 b"<p>Hello World!",110 ]111112113def test_escaping_without_template_filename(app, client, req_ctx):111 assert flask.render_template_string(112 '{{ foo }}', foo='<test>') == '&lt;test&gt;'113 assert flask.render_template('mail.txt', foo='<test>') == '<test> Mail'114 assert flask.render_template_string("{{ foo }}", foo="<test>") == "&lt;test&gt;"115 assert flask.render_template("mail.txt", foo="<test>") == "<test> Mail"116117118def test_macros(app, req_ctx):117 macro = flask.get_template_attribute('_macro.html', 'hello')118 assert macro('World') == 'Hello World!'119 macro = flask.get_template_attribute("_macro.html", "hello")120 assert macro("World") == "Hello World!"121122123def test_template_filter(app):124 @app.template_filter()125 def my_reverse(s):126 return s[::-1]127126 assert 'my_reverse' in app.jinja_env.filters.keys()127 assert app.jinja_env.filters['my_reverse'] == my_reverse128 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'128 assert "my_reverse" in app.jinja_env.filters.keys()129 assert app.jinja_env.filters["my_reverse"] == my_reverse130 assert app.jinja_env.filters["my_reverse"]("abcd") == "dcba"131132133def test_add_template_filter(app):134 def my_reverse(s):135 return s[::-1]136137 app.add_template_filter(my_reverse)136 assert 'my_reverse' in app.jinja_env.filters.keys()137 assert app.jinja_env.filters['my_reverse'] == my_reverse138 assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba'138 assert "my_reverse" in app.jinja_env.filters.keys()139 assert app.jinja_env.filters["my_reverse"] == my_reverse140 assert app.jinja_env.filters["my_reverse"]("abcd") == "dcba"141142143def test_template_filter_with_name(app):142 @app.template_filter('strrev')144 @app.template_filter("strrev")145 def my_reverse(s):146 return s[::-1]147146 assert 'strrev' in app.jinja_env.filters.keys()147 assert app.jinja_env.filters['strrev'] == my_reverse148 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'148 assert "strrev" in app.jinja_env.filters.keys()149 assert app.jinja_env.filters["strrev"] == my_reverse150 assert app.jinja_env.filters["strrev"]("abcd") == "dcba"151152153def test_add_template_filter_with_name(app):154 def my_reverse(s):155 return s[::-1]156155 app.add_template_filter(my_reverse, 'strrev')156 assert 'strrev' in app.jinja_env.filters.keys()157 assert app.jinja_env.filters['strrev'] == my_reverse158 assert app.jinja_env.filters['strrev']('abcd') == 'dcba'157 app.add_template_filter(my_reverse, "strrev")158 assert "strrev" in app.jinja_env.filters.keys()159 assert app.jinja_env.filters["strrev"] == my_reverse160 assert app.jinja_env.filters["strrev"]("abcd") == "dcba"161162163def test_template_filter_with_template(app, client):164 @app.template_filter()165 def super_reverse(s):166 return s[::-1]167166 @app.route('/')168 @app.route("/")169 def index():168 return flask.render_template('template_filter.html', value='abcd')170 return flask.render_template("template_filter.html", value="abcd")171170 rv = client.get('/')171 assert rv.data == b'dcba'172 rv = client.get("/")173 assert rv.data == b"dcba"174175176def test_add_template_filter_with_template(app, client):177 def super_reverse(s):178 return s[::-1]179180 app.add_template_filter(super_reverse)181180 @app.route('/')182 @app.route("/")183 def index():182 return flask.render_template('template_filter.html', value='abcd')184 return flask.render_template("template_filter.html", value="abcd")185184 rv = client.get('/')185 assert rv.data == b'dcba'186 rv = client.get("/")187 assert rv.data == b"dcba"188189190def test_template_filter_with_name_and_template(app, client):189 @app.template_filter('super_reverse')191 @app.template_filter("super_reverse")192 def my_reverse(s):193 return s[::-1]194193 @app.route('/')195 @app.route("/")196 def index():195 return flask.render_template('template_filter.html', value='abcd')197 return flask.render_template("template_filter.html", value="abcd")198197 rv = client.get('/')198 assert rv.data == b'dcba'199 rv = client.get("/")200 assert rv.data == b"dcba"201202203def test_add_template_filter_with_name_and_template(app, client):204 def my_reverse(s):205 return s[::-1]206205 app.add_template_filter(my_reverse, 'super_reverse')207 app.add_template_filter(my_reverse, "super_reverse")208207 @app.route('/')209 @app.route("/")210 def index():209 return flask.render_template('template_filter.html', value='abcd')211 return flask.render_template("template_filter.html", value="abcd")212211 rv = client.get('/')212 assert rv.data == b'dcba'213 rv = client.get("/")214 assert rv.data == b"dcba"215216217def test_template_test(app):218 @app.template_test()219 def boolean(value):220 return isinstance(value, bool)221220 assert 'boolean' in app.jinja_env.tests.keys()221 assert app.jinja_env.tests['boolean'] == boolean222 assert app.jinja_env.tests['boolean'](False)222 assert "boolean" in app.jinja_env.tests.keys()223 assert app.jinja_env.tests["boolean"] == boolean224 assert app.jinja_env.tests["boolean"](False)225226227def test_add_template_test(app):228 def boolean(value):229 return isinstance(value, bool)230231 app.add_template_test(boolean)230 assert 'boolean' in app.jinja_env.tests.keys()231 assert app.jinja_env.tests['boolean'] == boolean232 assert app.jinja_env.tests['boolean'](False)232 assert "boolean" in app.jinja_env.tests.keys()233 assert app.jinja_env.tests["boolean"] == boolean234 assert app.jinja_env.tests["boolean"](False)235236237def test_template_test_with_name(app):236 @app.template_test('boolean')238 @app.template_test("boolean")239 def is_boolean(value):240 return isinstance(value, bool)241240 assert 'boolean' in app.jinja_env.tests.keys()241 assert app.jinja_env.tests['boolean'] == is_boolean242 assert app.jinja_env.tests['boolean'](False)242 assert "boolean" in app.jinja_env.tests.keys()243 assert app.jinja_env.tests["boolean"] == is_boolean244 assert app.jinja_env.tests["boolean"](False)245246247def test_add_template_test_with_name(app):248 def is_boolean(value):249 return isinstance(value, bool)250249 app.add_template_test(is_boolean, 'boolean')250 assert 'boolean' in app.jinja_env.tests.keys()251 assert app.jinja_env.tests['boolean'] == is_boolean252 assert app.jinja_env.tests['boolean'](False)251 app.add_template_test(is_boolean, "boolean")252 assert "boolean" in app.jinja_env.tests.keys()253 assert app.jinja_env.tests["boolean"] == is_boolean254 assert app.jinja_env.tests["boolean"](False)255256257def test_template_test_with_template(app, client):258 @app.template_test()259 def boolean(value):260 return isinstance(value, bool)261260 @app.route('/')262 @app.route("/")263 def index():262 return flask.render_template('template_test.html', value=False)264 return flask.render_template("template_test.html", value=False)265264 rv = client.get('/')265 assert b'Success!' in rv.data266 rv = client.get("/")267 assert b"Success!" in rv.data268269270def test_add_template_test_with_template(app, client):271 def boolean(value):272 return isinstance(value, bool)273274 app.add_template_test(boolean)275274 @app.route('/')276 @app.route("/")277 def index():276 return flask.render_template('template_test.html', value=False)278 return flask.render_template("template_test.html", value=False)279278 rv = client.get('/')279 assert b'Success!' in rv.data280 rv = client.get("/")281 assert b"Success!" in rv.data282283284def test_template_test_with_name_and_template(app, client):283 @app.template_test('boolean')285 @app.template_test("boolean")286 def is_boolean(value):287 return isinstance(value, bool)288287 @app.route('/')289 @app.route("/")290 def index():289 return flask.render_template('template_test.html', value=False)291 return flask.render_template("template_test.html", value=False)292291 rv = client.get('/')292 assert b'Success!' in rv.data293 rv = client.get("/")294 assert b"Success!" in rv.data295296297def test_add_template_test_with_name_and_template(app, client):298 def is_boolean(value):299 return isinstance(value, bool)300299 app.add_template_test(is_boolean, 'boolean')301 app.add_template_test(is_boolean, "boolean")302301 @app.route('/')303 @app.route("/")304 def index():303 return flask.render_template('template_test.html', value=False)305 return flask.render_template("template_test.html", value=False)306305 rv = client.get('/')306 assert b'Success!' in rv.data307 rv = client.get("/")308 assert b"Success!" in rv.data309310311def test_add_template_global(app, app_ctx):312 @app.template_global()313 def get_stuff():314 return 42315314 assert 'get_stuff' in app.jinja_env.globals.keys()315 assert app.jinja_env.globals['get_stuff'] == get_stuff316 assert app.jinja_env.globals['get_stuff'](), 42316 assert "get_stuff" in app.jinja_env.globals.keys()317 assert app.jinja_env.globals["get_stuff"] == get_stuff318 assert app.jinja_env.globals["get_stuff"](), 42319318 rv = flask.render_template_string('{{ get_stuff() }}')319 assert rv == '42'320 rv = flask.render_template_string("{{ get_stuff() }}")321 assert rv == "42"322323324def test_custom_template_loader(client):325 class MyFlask(flask.Flask):326 def create_global_jinja_loader(self):327 from jinja2 import DictLoader326 return DictLoader({'index.html': 'Hello Custom World!'})328329 return DictLoader({"index.html": "Hello Custom World!"})330331 app = MyFlask(__name__)332330 @app.route('/')333 @app.route("/")334 def index():332 return flask.render_template('index.html')335 return flask.render_template("index.html")336337 c = app.test_client()335 rv = c.get('/')336 assert rv.data == b'Hello Custom World!'338 rv = c.get("/")339 assert rv.data == b"Hello Custom World!"340341342def test_iterable_loader(app, client):343 @app.context_processor344 def context_processor():342 return {'whiskey': 'Jameson'}345 return {"whiskey": "Jameson"}346344 @app.route('/')347 @app.route("/")348 def index():349 return flask.render_template(347 ['no_template.xml', # should skip this one348 'simple_template.html', # should render this349 'context_template.html'],350 value=23)350 [351 "no_template.xml", # should skip this one352 "simple_template.html", # should render this353 "context_template.html",354 ],355 value=23,356 )357352 rv = client.get('/')353 assert rv.data == b'<h1>Jameson</h1>'358 rv = client.get("/")359 assert rv.data == b"<h1>Jameson</h1>"360361362def test_templates_auto_reload(app):363 # debug is False, config option is None364 assert app.debug is False359 assert app.config['TEMPLATES_AUTO_RELOAD'] is None365 assert app.config["TEMPLATES_AUTO_RELOAD"] is None366 assert app.jinja_env.auto_reload is False367 # debug is False, config option is False368 app = flask.Flask(__name__)363 app.config['TEMPLATES_AUTO_RELOAD'] = False369 app.config["TEMPLATES_AUTO_RELOAD"] = False370 assert app.debug is False371 assert app.jinja_env.auto_reload is False372 # debug is False, config option is True373 app = flask.Flask(__name__)368 app.config['TEMPLATES_AUTO_RELOAD'] = True374 app.config["TEMPLATES_AUTO_RELOAD"] = True375 assert app.debug is False376 assert app.jinja_env.auto_reload is True377 # debug is True, config option is None378 app = flask.Flask(__name__)373 app.config['DEBUG'] = True374 assert app.config['TEMPLATES_AUTO_RELOAD'] is None379 app.config["DEBUG"] = True380 assert app.config["TEMPLATES_AUTO_RELOAD"] is None381 assert app.jinja_env.auto_reload is True382 # debug is True, config option is False383 app = flask.Flask(__name__)378 app.config['DEBUG'] = True379 app.config['TEMPLATES_AUTO_RELOAD'] = False384 app.config["DEBUG"] = True385 app.config["TEMPLATES_AUTO_RELOAD"] = False386 assert app.jinja_env.auto_reload is False387 # debug is True, config option is True388 app = flask.Flask(__name__)383 app.config['DEBUG'] = True384 app.config['TEMPLATES_AUTO_RELOAD'] = True389 app.config["DEBUG"] = True390 app.config["TEMPLATES_AUTO_RELOAD"] = True391 assert app.jinja_env.auto_reload is True392393394def test_templates_auto_reload_debug_run(app, monkeypatch):395 def run_simple_mock(*args, **kwargs):396 pass397391 monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock)398 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)399400 app.run()401 assert app.templates_auto_reload == False402 assert app.jinja_env.auto_reload == False
12 unmodified lines
415 def handle(x, record):416 called.append(True)417 text = str(record.msg)418 assert '1: trying loader of application "blueprintapp"' in text412 assert ('2: trying loader of blueprint "admin" '413 '(blueprintapp.apps.admin)') in text414 assert ('trying loader of blueprint "frontend" '415 '(blueprintapp.apps.frontend)') in text416 assert 'Error: the template could not be found' in text417 assert ('looked up from an endpoint that belongs to '418 'the blueprint "frontend"') in text419 assert 'See http://flask.pocoo.org/docs/blueprints/#templates' in text419 assert (420 '2: trying loader of blueprint "admin" ' "(blueprintapp.apps.admin)"421 ) in text422 assert (423 'trying loader of blueprint "frontend" ' "(blueprintapp.apps.frontend)"424 ) in text425 assert "Error: the template could not be found" in text426 assert (427 "looked up from an endpoint that belongs to " 'the blueprint "frontend"'428 ) in text429 assert "See http://flask.pocoo.org/docs/blueprints/#templates" in text430431 with app.test_client() as c:422 monkeypatch.setitem(app.config, 'EXPLAIN_TEMPLATE_LOADING', True)423 monkeypatch.setattr(424 logging.getLogger('flask'), 'handlers', [_TestHandler()]425 )432 monkeypatch.setitem(app.config, "EXPLAIN_TEMPLATE_LOADING", True)433 monkeypatch.setattr(logging.getLogger("flask"), "handlers", [_TestHandler()])434435 with pytest.raises(TemplateNotFound) as excinfo:428 c.get('/missing')436 c.get("/missing")437430 assert 'missing_template.html' in str(excinfo.value)438 assert "missing_template.html" in str(excinfo.value)439440 assert len(called) == 1441442
9 unmodified lines
modified:tests/test_testing.py+112 added-112 removed
19 unmodified lines
20from flask.testing import make_test_environ_builder, FlaskCliRunner212223def test_environ_defaults_from_config(app, client):24 app.config['SERVER_NAME'] = 'example.com:1234'25 app.config['APPLICATION_ROOT'] = '/foo'24 app.config["SERVER_NAME"] = "example.com:1234"25 app.config["APPLICATION_ROOT"] = "/foo"2627 @app.route('/')27 @app.route("/")28 def index():29 return flask.request.url3031 ctx = app.test_request_context()32 assert ctx.request.url == 'http://example.com:1234/foo/'32 assert ctx.request.url == "http://example.com:1234/foo/"3334 rv = client.get('/')35 assert rv.data == b'http://example.com:1234/foo/'34 rv = client.get("/")35 assert rv.data == b"http://example.com:1234/foo/"363738def test_environ_defaults(app, client, app_ctx, req_ctx):39 @app.route('/')39 @app.route("/")40 def index():41 return flask.request.url4243 ctx = app.test_request_context()44 assert ctx.request.url == 'http://localhost/'44 assert ctx.request.url == "http://localhost/"45 with client:46 rv = client.get('/')47 assert rv.data == b'http://localhost/'46 rv = client.get("/")47 assert rv.data == b"http://localhost/"484950def test_environ_base_default(app, client, app_ctx):51 @app.route('/')51 @app.route("/")52 def index():53 flask.g.user_agent = flask.request.headers["User-Agent"]54 return flask.request.remote_addr5556 rv = client.get('/')57 assert rv.data == b'127.0.0.1'58 assert flask.g.user_agent == 'werkzeug/' + werkzeug.__version__56 rv = client.get("/")57 assert rv.data == b"127.0.0.1"58 assert flask.g.user_agent == "werkzeug/" + werkzeug.__version__596061def test_environ_base_modified(app, client, app_ctx):62 @app.route('/')62 @app.route("/")63 def index():64 flask.g.user_agent = flask.request.headers["User-Agent"]65 return flask.request.remote_addr6667 client.environ_base['REMOTE_ADDR'] = '0.0.0.0'68 client.environ_base['HTTP_USER_AGENT'] = 'Foo'69 rv = client.get('/')70 assert rv.data == b'0.0.0.0'71 assert flask.g.user_agent == 'Foo'67 client.environ_base["REMOTE_ADDR"] = "0.0.0.0"68 client.environ_base["HTTP_USER_AGENT"] = "Foo"69 rv = client.get("/")70 assert rv.data == b"0.0.0.0"71 assert flask.g.user_agent == "Foo"7273 client.environ_base['REMOTE_ADDR'] = '0.0.0.1'74 client.environ_base['HTTP_USER_AGENT'] = 'Bar'75 rv = client.get('/')76 assert rv.data == b'0.0.0.1'77 assert flask.g.user_agent == 'Bar'73 client.environ_base["REMOTE_ADDR"] = "0.0.0.1"74 client.environ_base["HTTP_USER_AGENT"] = "Bar"75 rv = client.get("/")76 assert rv.data == b"0.0.0.1"77 assert flask.g.user_agent == "Bar"787980def test_client_open_environ(app, client, request):81 @app.route('/index')81 @app.route("/index")82 def index():83 return flask.request.remote_addr8485 builder = make_test_environ_builder(app, path='/index', method='GET')85 builder = make_test_environ_builder(app, path="/index", method="GET")86 request.addfinalizer(builder.close)8788 rv = client.open(builder)89 assert rv.data == b'127.0.0.1'89 assert rv.data == b"127.0.0.1"9091 environ = builder.get_environ()92 client.environ_base['REMOTE_ADDR'] = '127.0.0.2'92 client.environ_base["REMOTE_ADDR"] = "127.0.0.2"93 rv = client.open(environ)94 assert rv.data == b'127.0.0.2'94 assert rv.data == b"127.0.0.2"959697def test_specify_url_scheme(app, client):98 @app.route('/')98 @app.route("/")99 def index():100 return flask.request.url101102 ctx = app.test_request_context(url_scheme='https')103 assert ctx.request.url == 'https://localhost/'102 ctx = app.test_request_context(url_scheme="https")103 assert ctx.request.url == "https://localhost/"104105 rv = client.get('/', url_scheme='https')106 assert rv.data == b'https://localhost/'105 rv = client.get("/", url_scheme="https")106 assert rv.data == b"https://localhost/"107108109def test_path_is_url(app):110 eb = make_test_environ_builder(app, 'https://example.com/')111 assert eb.url_scheme == 'https'112 assert eb.host == 'example.com'113 assert eb.script_root == ''114 assert eb.path == '/'110 eb = make_test_environ_builder(app, "https://example.com/")111 assert eb.url_scheme == "https"112 assert eb.host == "example.com"113 assert eb.script_root == ""114 assert eb.path == "/"115116117def test_blueprint_with_subdomain():118 app = flask.Flask(__name__, subdomain_matching=True)119 app.config['SERVER_NAME'] = 'example.com:1234'120 app.config['APPLICATION_ROOT'] = '/foo'119 app.config["SERVER_NAME"] = "example.com:1234"120 app.config["APPLICATION_ROOT"] = "/foo"121 client = app.test_client()122123 bp = flask.Blueprint('company', __name__, subdomain='xxx')123 bp = flask.Blueprint("company", __name__, subdomain="xxx")124125 @bp.route('/')125 @bp.route("/")126 def index():127 return flask.request.url128129 app.register_blueprint(bp)130131 ctx = app.test_request_context('/', subdomain='xxx')132 assert ctx.request.url == 'http://xxx.example.com:1234/foo/'131 ctx = app.test_request_context("/", subdomain="xxx")132 assert ctx.request.url == "http://xxx.example.com:1234/foo/"133 assert ctx.request.blueprint == bp.name134135 rv = client.get('/', subdomain='xxx')136 assert rv.data == b'http://xxx.example.com:1234/foo/'135 rv = client.get("/", subdomain="xxx")136 assert rv.data == b"http://xxx.example.com:1234/foo/"137138139def test_redirect_keep_session(app, client, app_ctx):140 @app.route('/', methods=['GET', 'POST'])140 @app.route("/", methods=["GET", "POST"])141 def index():142 if flask.request.method == 'POST':143 return flask.redirect('/getsession')144 flask.session['data'] = 'foo'145 return 'index'142 if flask.request.method == "POST":143 return flask.redirect("/getsession")144 flask.session["data"] = "foo"145 return "index"146147 @app.route('/getsession')147 @app.route("/getsession")148 def get_session():149 return flask.session.get('data', '<missing>')149 return flask.session.get("data", "<missing>")150151 with client:152 rv = client.get('/getsession')153 assert rv.data == b'<missing>'152 rv = client.get("/getsession")153 assert rv.data == b"<missing>"154155 rv = client.get('/')156 assert rv.data == b'index'157 assert flask.session.get('data') == 'foo'158 rv = client.post('/', data={}, follow_redirects=True)159 assert rv.data == b'foo'155 rv = client.get("/")156 assert rv.data == b"index"157 assert flask.session.get("data") == "foo"158 rv = client.post("/", data={}, follow_redirects=True)159 assert rv.data == b"foo"160161 # This support requires a new Werkzeug version162 if not hasattr(client, 'redirect_client'):163 assert flask.session.get('data') == 'foo'162 if not hasattr(client, "redirect_client"):163 assert flask.session.get("data") == "foo"164165 rv = client.get('/getsession')166 assert rv.data == b'foo'165 rv = client.get("/getsession")166 assert rv.data == b"foo"167168169def test_session_transactions(app, client):170 @app.route('/')170 @app.route("/")171 def index():172 return text_type(flask.session['foo'])172 return text_type(flask.session["foo"])173174 with client:175 with client.session_transaction() as sess:176 assert len(sess) == 0177 sess['foo'] = [42]177 sess["foo"] = [42]178 assert len(sess) == 1179 rv = client.get('/')180 assert rv.data == b'[42]'179 rv = client.get("/")180 assert rv.data == b"[42]"181 with client.session_transaction() as sess:182 assert len(sess) == 1183 assert sess['foo'] == [42]183 assert sess["foo"] == [42]184185186def test_session_transactions_no_null_sessions():187 app = flask.Flask(__name__)
2 unmodified lines
190 with app.test_client() as c:191 with pytest.raises(RuntimeError) as e:192 with c.session_transaction() as sess:193 pass194 assert 'Session backend did not open a session' in str(e.value)194 assert "Session backend did not open a session" in str(e.value)195196197def test_session_transactions_keep_context(app, client, req_ctx):198 rv = client.get('/')198 rv = client.get("/")199 req = flask.request._get_current_object()200 assert req is not None201 with client.session_transaction():202 assert req is flask.request._get_current_object()
3 unmodified lines
206 c = app.test_client(use_cookies=False)207 with pytest.raises(RuntimeError) as e:208 with c.session_transaction() as s:209 pass210 assert 'cookies' in str(e.value)210 assert "cookies" in str(e.value)211212213def test_test_client_context_binding(app, client):214 app.testing = False215216 @app.route('/')216 @app.route("/")217 def index():218 flask.g.value = 42219 return 'Hello World!'219 return "Hello World!"220221 @app.route('/other')221 @app.route("/other")222 def other():223 1 // 0224225 with client:226 resp = client.get('/')226 resp = client.get("/")227 assert flask.g.value == 42228 assert resp.data == b'Hello World!'228 assert resp.data == b"Hello World!"229 assert resp.status_code == 200230231 resp = client.get('/other')232 assert not hasattr(flask.g, 'value')233 assert b'Internal Server Error' in resp.data231 resp = client.get("/other")232 assert not hasattr(flask.g, "value")233 assert b"Internal Server Error" in resp.data234 assert resp.status_code == 500235 flask.g.value = 23236237 try:238 flask.g.value239 except (AttributeError, RuntimeError):240 pass241 else:242 raise AssertionError('some kind of exception expected')242 raise AssertionError("some kind of exception expected")243244245def test_reuse_client(client):246 c = client247248 with c:249 assert client.get('/').status_code == 404249 assert client.get("/").status_code == 404250251 with c:252 assert client.get('/').status_code == 404252 assert client.get("/").status_code == 404253254255def test_test_client_calls_teardown_handlers(app, client):256 called = []
3 unmodified lines
260 called.append(error)261262 with client:263 assert called == []264 client.get('/')264 client.get("/")265 assert called == []266 assert called == [None]267268 del called[:]269 with client:270 assert called == []271 client.get('/')271 client.get("/")272 assert called == []273 client.get('/')273 client.get("/")274 assert called == [None]275 assert called == [None, None]276277278def test_full_url_request(app, client):279 @app.route('/action', methods=['POST'])279 @app.route("/action", methods=["POST"])280 def action():281 return 'x'281 return "x"282283 with client:284 rv = client.post('http://domain.com/action?vodka=42', data={'gin': 43})284 rv = client.post("http://domain.com/action?vodka=42", data={"gin": 43})285 assert rv.status_code == 200286 assert 'gin' in flask.request.form287 assert 'vodka' in flask.request.args286 assert "gin" in flask.request.form287 assert "vodka" in flask.request.args288289290def test_json_request_and_response(app, client):291 @app.route('/echo', methods=['POST'])291 @app.route("/echo", methods=["POST"])292 def echo():293 return jsonify(flask.request.get_json())294295 with client:296 json_data = {'drink': {'gin': 1, 'tonic': True}, 'price': 10}297 rv = client.post('/echo', json=json_data)296 json_data = {"drink": {"gin": 1, "tonic": True}, "price": 10}297 rv = client.post("/echo", json=json_data)298299 # Request should be in JSON300 assert flask.request.is_json301 assert flask.request.get_json() == json_data
5 unmodified lines
307308309def test_subdomain():310 app = flask.Flask(__name__, subdomain_matching=True)311 app.config['SERVER_NAME'] = 'example.com'311 app.config["SERVER_NAME"] = "example.com"312 client = app.test_client()313314 @app.route('/', subdomain='<company_id>')314 @app.route("/", subdomain="<company_id>")315 def view(company_id):316 return company_id317318 with app.test_request_context():319 url = flask.url_for('view', company_id='xxx')319 url = flask.url_for("view", company_id="xxx")320321 with client:322 response = client.get(url)323324 assert 200 == response.status_code325 assert b'xxx' == response.data325 assert b"xxx" == response.data326327328def test_nosubdomain(app, client):329 app.config['SERVER_NAME'] = 'example.com'329 app.config["SERVER_NAME"] = "example.com"330331 @app.route('/<company_id>')331 @app.route("/<company_id>")332 def view(company_id):333 return company_id334335 with app.test_request_context():336 url = flask.url_for('view', company_id='xxx')336 url = flask.url_for("view", company_id="xxx")337338 with client:339 response = client.get(url)340341 assert 200 == response.status_code342 assert b'xxx' == response.data342 assert b"xxx" == response.data343344345def test_cli_runner_class(app):346 runner = app.test_cli_runner()
7 unmodified lines
354 assert isinstance(runner, SubRunner)355356357def test_cli_invoke(app):358 @app.cli.command('hello')358 @app.cli.command("hello")359 def hello_command():360 click.echo('Hello, World!')360 click.echo("Hello, World!")361362 runner = app.test_cli_runner()363 # invoke with command name364 result = runner.invoke(args=['hello'])365 assert 'Hello' in result.output364 result = runner.invoke(args=["hello"])365 assert "Hello" in result.output366 # invoke with command object367 result = runner.invoke(hello_command)368 assert 'Hello' in result.output368 assert "Hello" in result.output369370371def test_cli_custom_obj(app):372 class NS(object):
2 unmodified lines
375 def create_app():376 NS.called = True377 return app378379 @app.cli.command('hello')379 @app.cli.command("hello")380 def hello_command():381 click.echo('Hello, World!')381 click.echo("Hello, World!")382383 script_info = ScriptInfo(create_app=create_app)384 runner = app.test_cli_runner()385 runner.invoke(hello_command, obj=script_info)
1 unmodified line
modified:tests/test_user_error_handler.py+43 added-49 removed
5 unmodified lines
6:copyright: © 2010 by the Pallets team.7:license: BSD, see LICENSE for more details.8"""910from werkzeug.exceptions import (11 Forbidden,12 InternalServerError,13 HTTPException,14 NotFound15 )10from werkzeug.exceptions import Forbidden, InternalServerError, HTTPException, NotFound11import flask121314def test_error_handler_no_match(app, client):2015 class CustomException(Exception):16 pass1718 @app.errorhandler(CustomException)19 def custom_exception_handler(e):20 assert isinstance(e, CustomException)27 return 'custom'21 return "custom"2223 @app.errorhandler(500)24 def handle_500(e):25 return type(e).__name__2633 @app.route('/custom')27 @app.route("/custom")28 def custom_test():29 raise CustomException()3037 @app.route('/keyerror')31 @app.route("/keyerror")32 def key_error():33 raise KeyError()3435 app.testing = False42 assert client.get('/custom').data == b'custom'43 assert client.get('/keyerror').data == b'KeyError'36 assert client.get("/custom").data == b"custom"37 assert client.get("/keyerror").data == b"KeyError"383940def test_error_handler_subclass(app):41 class ParentException(Exception):
7 unmodified lines
4950 @app.errorhandler(ParentException)51 def parent_exception_handler(e):52 assert isinstance(e, ParentException)59 return 'parent'53 return "parent"5455 @app.errorhandler(ChildExceptionRegistered)56 def child_exception_handler(e):57 assert isinstance(e, ChildExceptionRegistered)64 return 'child-registered'58 return "child-registered"5966 @app.route('/parent')60 @app.route("/parent")61 def parent_test():62 raise ParentException()6370 @app.route('/child-unregistered')64 @app.route("/child-unregistered")65 def unregistered_test():66 raise ChildExceptionUnregistered()6774 @app.route('/child-registered')68 @app.route("/child-registered")69 def registered_test():70 raise ChildExceptionRegistered()7172 c = app.test_client()7380 assert c.get('/parent').data == b'parent'81 assert c.get('/child-unregistered').data == b'parent'82 assert c.get('/child-registered').data == b'child-registered'74 assert c.get("/parent").data == b"parent"75 assert c.get("/child-unregistered").data == b"parent"76 assert c.get("/child-registered").data == b"child-registered"777879def test_error_handler_http_subclass(app):80 class ForbiddenSubclassRegistered(Forbidden):
4 unmodified lines
8586 @app.errorhandler(403)87 def code_exception_handler(e):88 assert isinstance(e, Forbidden)95 return 'forbidden'89 return "forbidden"9091 @app.errorhandler(ForbiddenSubclassRegistered)92 def subclass_exception_handler(e):93 assert isinstance(e, ForbiddenSubclassRegistered)100 return 'forbidden-registered'94 return "forbidden-registered"95102 @app.route('/forbidden')96 @app.route("/forbidden")97 def forbidden_test():98 raise Forbidden()99106 @app.route('/forbidden-registered')100 @app.route("/forbidden-registered")101 def registered_test():102 raise ForbiddenSubclassRegistered()103110 @app.route('/forbidden-unregistered')104 @app.route("/forbidden-unregistered")105 def unregistered_test():106 raise ForbiddenSubclassUnregistered()107108 c = app.test_client()109116 assert c.get('/forbidden').data == b'forbidden'117 assert c.get('/forbidden-unregistered').data == b'forbidden'118 assert c.get('/forbidden-registered').data == b'forbidden-registered'110 assert c.get("/forbidden").data == b"forbidden"111 assert c.get("/forbidden-unregistered").data == b"forbidden"112 assert c.get("/forbidden-registered").data == b"forbidden-registered"113114115def test_error_handler_blueprint(app):122 bp = flask.Blueprint('bp', __name__)116 bp = flask.Blueprint("bp", __name__)117118 @bp.errorhandler(500)119 def bp_exception_handler(e):126 return 'bp-error'120 return "bp-error"121128 @bp.route('/error')122 @bp.route("/error")123 def bp_test():124 raise InternalServerError()125126 @app.errorhandler(500)127 def app_exception_handler(e):134 return 'app-error'128 return "app-error"129136 @app.route('/error')130 @app.route("/error")131 def app_test():132 raise InternalServerError()133140 app.register_blueprint(bp, url_prefix='/bp')134 app.register_blueprint(bp, url_prefix="/bp")135136 c = app.test_client()137144 assert c.get('/error').data == b'app-error'145 assert c.get('/bp/error').data == b'bp-error'138 assert c.get("/error").data == b"app-error"139 assert c.get("/bp/error").data == b"bp-error"140141142def test_default_error_handler():149 bp = flask.Blueprint('bp', __name__)143 bp = flask.Blueprint("bp", __name__)144145 @bp.errorhandler(HTTPException)146 def bp_exception_handler(e):147 assert isinstance(e, HTTPException)148 assert isinstance(e, NotFound)155 return 'bp-default'149 return "bp-default"150151 @bp.errorhandler(Forbidden)152 def bp_exception_handler(e):153 assert isinstance(e, Forbidden)160 return 'bp-forbidden'154 return "bp-forbidden"155162 @bp.route('/undefined')156 @bp.route("/undefined")157 def bp_registered_test():158 raise NotFound()159166 @bp.route('/forbidden')160 @bp.route("/forbidden")161 def bp_forbidden_test():162 raise Forbidden()163164 app = flask.Flask(__name__)
1 unmodified line
166 @app.errorhandler(HTTPException)167 def catchall_errorhandler(e):168 assert isinstance(e, HTTPException)169 assert isinstance(e, NotFound)176 return 'default'170 return "default"171172 @app.errorhandler(Forbidden)173 def catchall_errorhandler(e):174 assert isinstance(e, Forbidden)181 return 'forbidden'175 return "forbidden"176183 @app.route('/forbidden')177 @app.route("/forbidden")178 def forbidden():179 raise Forbidden()180181 @app.route("/slash/")182 def slash():183 return "slash"184191 app.register_blueprint(bp, url_prefix='/bp')185 app.register_blueprint(bp, url_prefix="/bp")186187 c = app.test_client()194 assert c.get('/bp/undefined').data == b'bp-default'195 assert c.get('/bp/forbidden').data == b'bp-forbidden'196 assert c.get('/undefined').data == b'default'197 assert c.get('/forbidden').data == b'forbidden'188 assert c.get("/bp/undefined").data == b"bp-default"189 assert c.get("/bp/forbidden").data == b"bp-forbidden"190 assert c.get("/undefined").data == b"default"191 assert c.get("/forbidden").data == b"forbidden"192 # Don't handle RequestRedirect raised when adding slash.193 assert c.get("/slash", follow_redirects=True).data == b"slash"
modified:tests/test_views.py+70 added-72 removed
18 unmodified lines
1920def common_test(app):21 c = app.test_client()2223 assert c.get('/').data == b'GET'24 assert c.post('/').data == b'POST'25 assert c.put('/').status_code == 40526 meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])27 assert sorted(meths) == ['GET', 'HEAD', 'OPTIONS', 'POST']23 assert c.get("/").data == b"GET"24 assert c.post("/").data == b"POST"25 assert c.put("/").status_code == 40526 meths = parse_set_header(c.open("/", method="OPTIONS").headers["Allow"])27 assert sorted(meths) == ["GET", "HEAD", "OPTIONS", "POST"]282930def test_basic_view(app):31 class Index(flask.views.View):32 methods = ['GET', 'POST']32 methods = ["GET", "POST"]3334 def dispatch_request(self):35 return flask.request.method3637 app.add_url_rule('/', view_func=Index.as_view('index'))37 app.add_url_rule("/", view_func=Index.as_view("index"))38 common_test(app)394041def test_method_based_view(app):42 class Index(flask.views.MethodView):43 def get(self):44 return 'GET'44 return "GET"4546 def post(self):47 return 'POST'47 return "POST"4849 app.add_url_rule('/', view_func=Index.as_view('index'))49 app.add_url_rule("/", view_func=Index.as_view("index"))5051 common_test(app)5253
6 unmodified lines
60 1 // 06162 class Other(Index):63 def get(self):64 return 'GET'64 return "GET"6566 def post(self):67 return 'POST'67 return "POST"6869 view = Index.as_view('index')69 view = Index.as_view("index")70 view.view_class = Other71 app.add_url_rule('/', view_func=view)71 app.add_url_rule("/", view_func=view)72 common_test(app)737475def test_view_inheritance(app, client):76 class Index(flask.views.MethodView):77 def get(self):78 return 'GET'78 return "GET"7980 def post(self):81 return 'POST'81 return "POST"8283 class BetterIndex(Index):84 def delete(self):85 return 'DELETE'85 return "DELETE"8687 app.add_url_rule('/', view_func=BetterIndex.as_view('index'))87 app.add_url_rule("/", view_func=BetterIndex.as_view("index"))8889 meths = parse_set_header(client.open('/', method='OPTIONS').headers['Allow'])90 assert sorted(meths) == ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST']89 meths = parse_set_header(client.open("/", method="OPTIONS").headers["Allow"])90 assert sorted(meths) == ["DELETE", "GET", "HEAD", "OPTIONS", "POST"]919293def test_view_decorators(app, client):94 def add_x_parachute(f):95 def new_function(*args, **kwargs):96 resp = flask.make_response(f(*args, **kwargs))97 resp.headers['X-Parachute'] = 'awesome'97 resp.headers["X-Parachute"] = "awesome"98 return resp99100 return new_function101102 class Index(flask.views.View):103 decorators = [add_x_parachute]104105 def dispatch_request(self):106 return 'Awesome'106 return "Awesome"107108 app.add_url_rule('/', view_func=Index.as_view('index'))109 rv = client.get('/')110 assert rv.headers['X-Parachute'] == 'awesome'111 assert rv.data == b'Awesome'108 app.add_url_rule("/", view_func=Index.as_view("index"))109 rv = client.get("/")110 assert rv.headers["X-Parachute"] == "awesome"111 assert rv.data == b"Awesome"112113114def test_view_provide_automatic_options_attr():115 app = flask.Flask(__name__)
1 unmodified line
117 class Index1(flask.views.View):118 provide_automatic_options = False119120 def dispatch_request(self):121 return 'Hello World!'121 return "Hello World!"122123 app.add_url_rule('/', view_func=Index1.as_view('index'))123 app.add_url_rule("/", view_func=Index1.as_view("index"))124 c = app.test_client()125 rv = c.open('/', method='OPTIONS')125 rv = c.open("/", method="OPTIONS")126 assert rv.status_code == 405127128 app = flask.Flask(__name__)129130 class Index2(flask.views.View):131 methods = ['OPTIONS']131 methods = ["OPTIONS"]132 provide_automatic_options = True133134 def dispatch_request(self):135 return 'Hello World!'135 return "Hello World!"136137 app.add_url_rule('/', view_func=Index2.as_view('index'))137 app.add_url_rule("/", view_func=Index2.as_view("index"))138 c = app.test_client()139 rv = c.open('/', method='OPTIONS')140 assert sorted(rv.allow) == ['OPTIONS']139 rv = c.open("/", method="OPTIONS")140 assert sorted(rv.allow) == ["OPTIONS"]141142 app = flask.Flask(__name__)143144 class Index3(flask.views.View):145 def dispatch_request(self):146 return 'Hello World!'146 return "Hello World!"147148 app.add_url_rule('/', view_func=Index3.as_view('index'))148 app.add_url_rule("/", view_func=Index3.as_view("index"))149 c = app.test_client()150 rv = c.open('/', method='OPTIONS')151 assert 'OPTIONS' in rv.allow150 rv = c.open("/", method="OPTIONS")151 assert "OPTIONS" in rv.allow152153154def test_implicit_head(app, client):155 class Index(flask.views.MethodView):156 def get(self):157 return flask.Response('Blub', headers={158 'X-Method': flask.request.method159 })157 return flask.Response("Blub", headers={"X-Method": flask.request.method})158161 app.add_url_rule('/', view_func=Index.as_view('index'))162 rv = client.get('/')163 assert rv.data == b'Blub'164 assert rv.headers['X-Method'] == 'GET'165 rv = client.head('/')166 assert rv.data == b''167 assert rv.headers['X-Method'] == 'HEAD'159 app.add_url_rule("/", view_func=Index.as_view("index"))160 rv = client.get("/")161 assert rv.data == b"Blub"162 assert rv.headers["X-Method"] == "GET"163 rv = client.head("/")164 assert rv.data == b""165 assert rv.headers["X-Method"] == "HEAD"166167168def test_explicit_head(app, client):169 class Index(flask.views.MethodView):170 def get(self):173 return 'GET'171 return "GET"172173 def head(self):176 return flask.Response('', headers={'X-Method': 'HEAD'})174 return flask.Response("", headers={"X-Method": "HEAD"})175178 app.add_url_rule('/', view_func=Index.as_view('index'))179 rv = client.get('/')180 assert rv.data == b'GET'181 rv = client.head('/')182 assert rv.data == b''183 assert rv.headers['X-Method'] == 'HEAD'176 app.add_url_rule("/", view_func=Index.as_view("index"))177 rv = client.get("/")178 assert rv.data == b"GET"179 rv = client.head("/")180 assert rv.data == b""181 assert rv.headers["X-Method"] == "HEAD"182183184def test_endpoint_override(app):185 app.debug = True186187 class Index(flask.views.View):190 methods = ['GET', 'POST']188 methods = ["GET", "POST"]189190 def dispatch_request(self):191 return flask.request.method192195 app.add_url_rule('/', view_func=Index.as_view('index'))193 app.add_url_rule("/", view_func=Index.as_view("index"))194195 with pytest.raises(AssertionError):198 app.add_url_rule('/', view_func=Index.as_view('index'))196 app.add_url_rule("/", view_func=Index.as_view("index"))197198 # But these tests should still pass. We just log a warning.199 common_test(app)200201202def test_multiple_inheritance(app, client):203 class GetView(flask.views.MethodView):204 def get(self):207 return 'GET'205 return "GET"206207 class DeleteView(flask.views.MethodView):208 def delete(self):211 return 'DELETE'209 return "DELETE"210211 class GetDeleteView(GetView, DeleteView):212 pass213216 app.add_url_rule('/', view_func=GetDeleteView.as_view('index'))214 app.add_url_rule("/", view_func=GetDeleteView.as_view("index"))215218 assert client.get('/').data == b'GET'219 assert client.delete('/').data == b'DELETE'220 assert sorted(GetDeleteView.methods) == ['DELETE', 'GET']216 assert client.get("/").data == b"GET"217 assert client.delete("/").data == b"DELETE"218 assert sorted(GetDeleteView.methods) == ["DELETE", "GET"]219220221def test_remove_method_from_parent(app, client):222 class GetView(flask.views.MethodView):223 def get(self):226 return 'GET'224 return "GET"225226 class OtherView(flask.views.MethodView):227 def post(self):230 return 'POST'228 return "POST"229230 class View(GetView, OtherView):233 methods = ['GET']231 methods = ["GET"]232235 app.add_url_rule('/', view_func=View.as_view('index'))233 app.add_url_rule("/", view_func=View.as_view("index"))234237 assert client.get('/').data == b'GET'238 assert client.post('/').status_code == 405239 assert sorted(View.methods) == ['GET']235 assert client.get("/").data == b"GET"236 assert client.post("/").status_code == 405237 assert sorted(View.methods) == ["GET"]
added:.pre-commit-config.yaml+5 added
1repos:2 - repo: https://github.com/python/black3 rev: 19.3b04 hooks:5 - id: black
modified:setup.py+53 added-59 removed
4 unmodified lines
5from collections import OrderedDict67from setuptools import setup89with io.open('README.rst', 'rt', encoding='utf8') as f:9with io.open("README.rst", "rt", encoding="utf8") as f:10 readme = f.read()1112with io.open('flask/__init__.py', 'rt', encoding='utf8') as f:13 version = re.search(r'__version__ = \'(.*?)\'', f.read()).group(1)12with io.open("flask/__init__.py", "rt", encoding="utf8") as f:13 version = re.search(r"__version__ = \"(.*?)\"", f.read()).group(1)1415setup(16 name='Flask',16 name="Flask",17 version=version,18 url='https://www.palletsprojects.com/p/flask/',19 project_urls=OrderedDict((20 ('Documentation', 'http://flask.pocoo.org/docs/'),21 ('Code', 'https://github.com/pallets/flask'),22 ('Issue tracker', 'https://github.com/pallets/flask/issues'),23 )),24 license='BSD',25 author='Armin Ronacher',26 author_email='armin.ronacher@active-4.com',27 maintainer='Pallets team',28 maintainer_email='contact@palletsprojects.com',29 description='A simple framework for building complex web applications.',18 url="https://www.palletsprojects.com/p/flask/",19 project_urls=OrderedDict(20 (21 ("Documentation", "http://flask.pocoo.org/docs/"),22 ("Code", "https://github.com/pallets/flask"),23 ("Issue tracker", "https://github.com/pallets/flask/issues"),24 )25 ),26 license="BSD",27 author="Armin Ronacher",28 author_email="armin.ronacher@active-4.com",29 maintainer="Pallets team",30 maintainer_email="contact@palletsprojects.com",31 description="A simple framework for building complex web applications.",32 long_description=readme,31 packages=['flask', 'flask.json'],33 packages=["flask", "flask.json"],34 include_package_data=True,35 zip_safe=False,34 platforms='any',35 python_requires='>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*',36 platforms="any",37 python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*",38 install_requires=[37 'Werkzeug>=0.14',38 'Jinja2>=2.10.1',39 'itsdangerous>=0.24',40 'click>=5.1',39 "Werkzeug>=0.14",40 "Jinja2>=2.10.1",41 "itsdangerous>=0.24",42 "click>=5.1",43 ],44 extras_require={43 'dotenv': ['python-dotenv'],44 'dev': [45 'pytest>=3',46 'coverage',47 'tox',48 'sphinx',49 'pallets-sphinx-themes',50 'sphinxcontrib-log-cabinet',45 "dotenv": ["python-dotenv"],46 "dev": [47 "pytest>=3",48 "coverage",49 "tox",50 "sphinx",51 "pallets-sphinx-themes",52 "sphinxcontrib-log-cabinet",53 ],52 'docs': [53 'sphinx',54 'pallets-sphinx-themes',55 'sphinxcontrib-log-cabinet',56 ]54 "docs": ["sphinx", "pallets-sphinx-themes", "sphinxcontrib-log-cabinet"],55 },56 classifiers=[59 'Development Status :: 5 - Production/Stable',60 'Environment :: Web Environment',61 'Framework :: Flask',62 'Intended Audience :: Developers',63 'License :: OSI Approved :: BSD License',64 'Operating System :: OS Independent',65 'Programming Language :: Python',66 'Programming Language :: Python :: 2',67 'Programming Language :: Python :: 2.7',68 'Programming Language :: Python :: 3',69 'Programming Language :: Python :: 3.4',70 'Programming Language :: Python :: 3.5',71 'Programming Language :: Python :: 3.6',72 'Programming Language :: Python :: 3.7',73 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',74 'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',75 'Topic :: Software Development :: Libraries :: Application Frameworks',76 'Topic :: Software Development :: Libraries :: Python Modules',57 "Development Status :: 5 - Production/Stable",58 "Environment :: Web Environment",59 "Framework :: Flask",60 "Intended Audience :: Developers",61 "License :: OSI Approved :: BSD License",62 "Operating System :: OS Independent",63 "Programming Language :: Python",64 "Programming Language :: Python :: 2",65 "Programming Language :: Python :: 2.7",66 "Programming Language :: Python :: 3",67 "Programming Language :: Python :: 3.4",68 "Programming Language :: Python :: 3.5",69 "Programming Language :: Python :: 3.6",70 "Programming Language :: Python :: 3.7",71 "Topic :: Internet :: WWW/HTTP :: Dynamic Content",72 "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",73 "Topic :: Software Development :: Libraries :: Application Frameworks",74 "Topic :: Software Development :: Libraries :: Python Modules",75 ],78 entry_points={79 'console_scripts': [80 'flask = flask.cli:main',81 ],82 },76 entry_points={"console_scripts": ["flask = flask.cli:main"]},77)
modified:tox.ini+5 added
35 unmodified lines
3637 # pytest-cov doesn't seem to play nice with -p38 coverage run -p -m pytest tests examples3940[testenv:stylecheck]41deps = pre-commit42skip_install = true43commands = pre-commit run --all-files --show-diff-on-failure4445[testenv:docs-html]46deps =47 -r docs/requirements.txt48commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html
17 unmodified lines