Merge branch '1.0.x'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parents 953284a, 99660cc · Browse files · 7 files·+105 added−49 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+105 added−49 removed
- tests:+27 added−0 removed
- other:+78 added−49 removed
Provenance
- Commit
05a4e15- Tree
98a7d10- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
953284a- Parent 2
99660cc
7 files changed+105 added−49 removed
modified:docs/testing.rst+4 added-3 removed
355 unmodified lines356 This however does not make it possible to also modify the session or to357 access the session before a request was fired. Starting with Flask 0.8 we358 provide a so called “session transaction” which simulates the appropriate359 calls to open a session in the context of the test client and to modify360-it. At the end of the transaction the session is stored. This works361-independently of the session backend used::360+it. At the end of the transaction the session is stored and ready to be361+used by the test client. This works independently of the session backend used::362 363 with app.test_client() as c:364 with c.session_transaction() as sess:365 sess['a_key'] = 'a value'366 367- # once this is reached the session was stored367+ # once this is reached the session was stored and ready to be used by the client368+ c.get(...)369 370 Note that in this case you have to use the ``sess`` object instead of the371 :data:`flask.session` proxy. The object however itself will provide the372 same interface.88 unmodified linesmodified:flask/json/__init__.py+62 added-32 removed
95 unmodified lines96 functions of this module but also :attr:`~flask.Request`.97 """98 99 100-def _dump_arg_defaults(kwargs):100+def _dump_arg_defaults(kwargs, app=None):101 """Inject default arguments for dump functions."""102+ if app is None:103+ app = current_app104+102- if current_app:103- bp = current_app.blueprints.get(request.blueprint) if request else None105+ if app:106+ bp = app.blueprints.get(request.blueprint) if request else None107 kwargs.setdefault(105- "cls",106- bp.json_encoder if bp and bp.json_encoder else current_app.json_encoder,108+ "cls", bp.json_encoder if bp and bp.json_encoder else app.json_encoder109 )110 109- if not current_app.config["JSON_AS_ASCII"]:111+ if not app.config["JSON_AS_ASCII"]:112 kwargs.setdefault("ensure_ascii", False)113 112- kwargs.setdefault("sort_keys", current_app.config["JSON_SORT_KEYS"])114+ kwargs.setdefault("sort_keys", app.config["JSON_SORT_KEYS"])115 else:116 kwargs.setdefault("sort_keys", True)117 kwargs.setdefault("cls", JSONEncoder)118 119 118-def _load_arg_defaults(kwargs):120+def _load_arg_defaults(kwargs, app=None):121 """Inject default arguments for load functions."""122+ if app is None:123+ app = current_app124+120- if current_app:121- bp = current_app.blueprints.get(request.blueprint) if request else None125+ if app:126+ bp = app.blueprints.get(request.blueprint) if request else None127 kwargs.setdefault(123- "cls",124- bp.json_decoder if bp and bp.json_decoder else current_app.json_decoder,128+ "cls", bp.json_decoder if bp and bp.json_decoder else app.json_decoder129 )130 else:131 kwargs.setdefault("cls", JSONDecoder)132 40 unmodified lines173 174 return "utf-8"175 176 173-def dumps(obj, **kwargs):174- """Serialize ``obj`` to a JSON formatted ``str`` by using the application's175- configured encoder (:attr:`~flask.Flask.json_encoder`) if there is an176- application on the stack.177+def dumps(obj, app=None, **kwargs):178+ """Serialize ``obj`` to a JSON-formatted string. If there is an179+ app context pushed, use the current app's configured encoder180+ (:attr:`~flask.Flask.json_encoder`), or fall back to the default181+ :class:`JSONEncoder`.182 178- This function can return ``unicode`` strings or ascii-only bytestrings by179- default which coerce into unicode strings automatically. That behavior by180- default is controlled by the ``JSON_AS_ASCII`` configuration variable181- and can be overridden by the simplejson ``ensure_ascii`` parameter.183+ Takes the same arguments as the built-in :func:`json.dumps`, and184+ does some extra configuration based on the application. If the185+ simplejson package is installed, it is preferred.186+187+ :param obj: Object to serialize to JSON.188+ :param app: App instance to use to configure the JSON encoder.189+ Uses ``current_app`` if not given, and falls back to the default190+ encoder when not in an app context.191+ :param kwargs: Extra arguments passed to :func:`json.dumps`.192+193+ .. versionchanged:: 1.0.3194+195+ ``app`` can be passed directly, rather than requiring an app196+ context for configuration.197 """183- _dump_arg_defaults(kwargs)198+ _dump_arg_defaults(kwargs, app=app)199 encoding = kwargs.pop("encoding", None)200 rv = _json.dumps(obj, **kwargs)201 if encoding is not None and isinstance(rv, text_type):202 rv = rv.encode(encoding)203 return rv204 205 191-def dump(obj, fp, **kwargs):206+def dump(obj, fp, app=None, **kwargs):207 """Like :func:`dumps` but writes into a file object."""193- _dump_arg_defaults(kwargs)208+ _dump_arg_defaults(kwargs, app=app)209 encoding = kwargs.pop("encoding", None)210 if encoding is not None:211 fp = _wrap_writer_for_text(fp, encoding)212 _json.dump(obj, fp, **kwargs)213 214 200-def loads(s, **kwargs):201- """Unserialize a JSON object from a string ``s`` by using the application's202- configured decoder (:attr:`~flask.Flask.json_decoder`) if there is an203- application on the stack.215+def loads(s, app=None, **kwargs):216+ """Deserialize an object from a JSON-formatted string ``s``. If217+ there is an app context pushed, use the current app's configured218+ decoder (:attr:`~flask.Flask.json_decoder`), or fall back to the219+ default :class:`JSONDecoder`.220+221+ Takes the same arguments as the built-in :func:`json.loads`, and222+ does some extra configuration based on the application. If the223+ simplejson package is installed, it is preferred.224+225+ :param s: JSON string to deserialize.226+ :param app: App instance to use to configure the JSON decoder.227+ Uses ``current_app`` if not given, and falls back to the default228+ encoder when not in an app context.229+ :param kwargs: Extra arguments passed to :func:`json.dumps`.230+231+ .. versionchanged:: 1.0.3232+233+ ``app`` can be passed directly, rather than requiring an app234+ context for configuration.235 """205- _load_arg_defaults(kwargs)236+ _load_arg_defaults(kwargs, app=app)237 if isinstance(s, bytes):238 encoding = kwargs.pop("encoding", None)239 if encoding is None:240 encoding = detect_encoding(s)241 s = s.decode(encoding)242 return _json.loads(s, **kwargs)243 244 214-def load(fp, **kwargs):215- """Like :func:`loads` but reads from a file object.216- """217- _load_arg_defaults(kwargs)245+def load(fp, app=None, **kwargs):246+ """Like :func:`loads` but reads from a file object."""247+ _load_arg_defaults(kwargs, app=app)248 if not PY2:249 fp = _wrap_reader_for_text(fp, kwargs.pop("encoding", None) or "utf-8")250 return _json.load(fp, **kwargs)251 114 unmodified linesmodified:flask/blueprints.py-1 removed
8 unmodified lines9 :copyright: © 2010 by the Pallets team.10 :license: BSD, see LICENSE for more details.11 """12 from functools import update_wrapper13-from werkzeug.urls import url_join13 14 from .helpers import _PackageBoundObject, _endpoint_from_view_func15 16 490 unmodified linesmodified:flask/cli.py+3 added-5 removed
648 unmodified lines649 click.echo(" * Environment: {0}".format(env))650 651 if env == "production":652 click.secho(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)653+ ' WARNING: This is a development server. '654+ 'Do not use it in a production deployment.', fg='red')655+ click.secho(' Use a production WSGI server instead.', dim=True)656 657 if debug is not None:658 click.echo(" * Debug mode: {0}".format("on" if debug else "off"))659 271 unmodified linesmodified:flask/testing.py+2 added-4 removed
69 unmodified lines70 if url.query:71 sep = b"?" if isinstance(url.query, bytes) else "?"72 path += sep + url.query73 74+ # TODO use EnvironBuilder.json_dumps once we require Werkzeug 0.1575 if "json" in kwargs:76 assert "data" not in kwargs, "Client cannot provide both 'json' and 'data'."77+ kwargs["data"] = json_dumps(kwargs.pop("json"), app=app)78 77- # push a context so flask.json can use app's json attributes78- with app.app_context():79- kwargs["data"] = json_dumps(kwargs.pop("json"))80-79 if "content_type" not in kwargs:80 kwargs["content_type"] = "application/json"81 82 return EnvironBuilder(path, base_url, *args, **kwargs)166 unmodified linesmodified:tests/test_testing.py+27 added
12 unmodified lines13 14 import flask15 import werkzeug16 17+from flask import appcontext_popped18 from flask._compat import text_type19 from flask.cli import ScriptInfo20 from flask.json import jsonify21 from flask.testing import make_test_environ_builder, FlaskCliRunner22 23+try:24+ import blinker25+except ImportError:26+ blinker = None27 28+29 def test_environ_defaults_from_config(app, client):30 app.config["SERVER_NAME"] = "example.com:1234"31 app.config["APPLICATION_ROOT"] = "/foo"32 278 unmodified lines311 assert rv.is_json312 assert rv.get_json() == json_data313 314 315+@pytest.mark.skipif(blinker is None, reason="blinker is not installed")316+def test_client_json_no_app_context(app, client):317+ @app.route("/hello", methods=["POST"])318+ def hello():319+ return "Hello, {}!".format(flask.request.json["name"])320+321+ class Namespace(object):322+ count = 0323+324+ def add(self, app):325+ self.count += 1326+327+ ns = Namespace()328+329+ with appcontext_popped.connected_to(ns.add, app):330+ rv = client.post("/hello", json={"name": "Flask"})331+332+ assert rv.get_data(as_text=True) == "Hello, Flask!"333+ assert ns.count == 1334+335+336 def test_subdomain():337 app = flask.Flask(__name__, subdomain_matching=True)338 app.config["SERVER_NAME"] = "example.com"339 client = app.test_client()74 unmodified linesmodified:CHANGES.rst+7 added-4 removed
28 unmodified lines29 30 Version 1.0.331 -------------32 33-Unreleased33+Released 2019-05-1734 35 - :func:`send_file` encodes filenames as ASCII instead of Latin-136 (ISO-8859-1). This fixes compatibility with Gunicorn, which is37 stricter about header encodings than PEP 3333. (`#2766`_)7 unmodified lines45 - A catch-all error handler registered for ``HTTPException`` will not46 handle ``RoutingException``, which is used internally during47 routing. This fixes the unexpected behavior that had been introduced48 in 1.0. (`#2986`_)49+- Passing the ``json`` argument to ``app.test_client`` does not50+ push/pop an extra app context. (`#2900`_)51 52 .. _#2766: https://github.com/pallets/flask/issues/276653 .. _#2765: https://github.com/pallets/flask/pull/276554 .. _#2825: https://github.com/pallets/flask/pull/282555+.. _#2900: https://github.com/pallets/flask/issues/290056 .. _#2933: https://github.com/pallets/flask/issues/293357 .. _#2986: https://github.com/pallets/flask/pull/298658 59 60 Version 1.0.261 -------------62 60-Released on May 2nd 201863+Released 2018-05-0264 65 - Fix more backwards compatibility issues with merging slashes between66 a blueprint prefix and route. (`#2748`_)67 - Fix error with ``flask routes`` command when there are no routes.5 unmodified lines73 74 Version 1.0.175 -------------76 74-Released on April 29th 201877+Released 2018-04-2978 79 - Fix registering partials (with no ``__name__``) as view functions.80 (`#2730`_)81 - Don't treat lists returned from view functions the same as tuples.17 unmodified lines99 100 Version 1.0101 -----------102 100-Released on April 26th 2018103+Released 2018-04-26104 105 - **Python 2.6 and 3.3 are no longer supported.** (`pallets/meta#24`_)106 - Bump minimum dependency versions to the latest stable versions:107 Werkzeug >= 0.14, Jinja >= 2.10, itsdangerous >= 0.24, Click >= 5.1.865 unmodified lines