refactor make_response to be easier to follow
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* be explicit about how tuples are unpacked * allow bytes for status value * allow Headers for headers value * use TypeError instead of ValueError * errors are more descriptive * document that view must not return None * update documentation about return values * test more response types * test error messages closes #1676
authored by David Lord · committed by David Lord · parent 46f8366 · Browse files · 3 files·+203 added−106 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+203 added−106 removed
- tests:+96 added−47 removed
- other:+107 added−59 removed
Provenance
- Commit
697f7b9- Tree
2c93857- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
46f8366
3 files changed+203 added−106 removed
modified:flask/app.py+103 added-59 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 import os12 import sys13-from threading import Lock13 from datetime import timedelta15-from itertools import chain14 from functools import update_wrapper15+from itertools import chain16+from threading import Lock17 18-from werkzeug.datastructures import ImmutableDict19-from werkzeug.routing import Map, Rule, RequestRedirect, BuildError20-from werkzeug.exceptions import HTTPException, InternalServerError, \21- MethodNotAllowed, BadRequest, default_exceptions18+from werkzeug.datastructures import ImmutableDict, Headers19+from werkzeug.exceptions import BadRequest, HTTPException, \20+ InternalServerError, MethodNotAllowed, default_exceptions21+from werkzeug.routing import BuildError, Map, RequestRedirect, Rule22 23-from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \24- locked_cached_property, _endpoint_from_view_func, find_package, \25- get_debug_flag26-from . import json, cli27-from .wrappers import Request, Response28-from .config import ConfigAttribute, Config29-from .ctx import RequestContext, AppContext, _AppCtxGlobals30-from .globals import _request_ctx_stack, request, session, g23+from . import cli, json24+from ._compat import integer_types, reraise, string_types, text_type25+from .config import Config, ConfigAttribute26+from .ctx import AppContext, RequestContext, _AppCtxGlobals27+from .globals import _request_ctx_stack, g, request, session28+from .helpers import _PackageBoundObject, \29+ _endpoint_from_view_func, find_package, get_debug_flag, \30+ get_flashed_messages, locked_cached_property, url_for31 from .sessions import SecureCookieSessionInterface32+from .signals import appcontext_tearing_down, got_request_exception, \33+ request_finished, request_started, request_tearing_down34 from .templating import DispatchingJinjaLoader, Environment, \33- _default_template_ctx_processor34-from .signals import request_started, request_finished, got_request_exception, \35- request_tearing_down, appcontext_tearing_down36-from ._compat import reraise, string_types, text_type, integer_types35+ _default_template_ctx_processor36+from .wrappers import Request, Response37 38 # a lock used for logger initialization39 _logger_lock = Lock()40 1673 unmodified lines1714 """1715 return False1716 1717 def make_response(self, rv):1718- """Converts the return value from a view function to a real1719- response object that is an instance of :attr:`response_class`.1718+ """Convert the return value from a view function to an instance of1719+ :attr:`response_class`.1720 1721- The following types are allowed for `rv`:1721+ :param rv: the return value from the view function. The view function1722+ must return a response. Returning ``None``, or the view ending1723+ without returning, is not allowed. The following types are allowed1724+ for ``view_rv``:1725 1723- .. tabularcolumns:: |p{3.5cm}|p{9.5cm}|1726+ ``str`` (``unicode`` in Python 2)1727+ A response object is created with the string encoded to UTF-81728+ as the body.1729+ 1730+ ``bytes`` (``str`` in Python 2)1731+ A response object is created with the bytes as the body.1732+ 1733+ ``tuple``1734+ Either ``(body, status, headers)``, ``(body, status)``, or1735+ ``(body, headers)``, where ``body`` is any of the other types1736+ allowed here, ``status`` is a string or an integer, and1737+ ``headers`` is a dictionary or a list of ``(key, value)``1738+ tuples. If ``body`` is a :attr:`response_class` instance,1739+ ``status`` overwrites the exiting value and ``headers`` are1740+ extended.1741+ 1742+ :attr:`response_class`1743+ The object is returned unchanged.1744+ 1745+ other :class:`~werkzeug.wrappers.Response` class1746+ The object is coerced to :attr:`response_class`.1747+ 1748+ :func:`callable`1749+ The function is called as a WSGI application. The result is1750+ used to create a response object.1751 1725- ======================= ===========================================1726- :attr:`response_class` the object is returned unchanged1727- :class:`str` a response object is created with the1728- string as body1729- :class:`unicode` a response object is created with the1730- string encoded to utf-8 as body1731- a WSGI function the function is called as WSGI application1732- and buffered as response object1733- :class:`tuple` A tuple in the form ``(response, status,1734- headers)`` or ``(response, headers)``1735- where `response` is any of the1736- types defined here, `status` is a string1737- or an integer and `headers` is a list or1738- a dictionary with header values.1739- ======================= ===========================================1740-1741- :param rv: the return value from the view function1742-1752 .. versionchanged:: 0.91753 Previously a tuple was interpreted as the arguments for the1754 response object.1755 """1747- status_or_headers = headers = None1748- if isinstance(rv, tuple):1749- rv, status_or_headers, headers = rv + (None,) * (3 - len(rv))1756 1751- if rv is None:1752- raise ValueError('View function did not return a response')1757+ status = headers = None1758 1754- if isinstance(status_or_headers, (dict, list)):1755- headers, status_or_headers = status_or_headers, None1759+ # unpack tuple returns1760+ if isinstance(rv, (tuple, list)):1761+ len_rv = len(rv)1762 1763+ # a 3-tuple is unpacked directly1764+ if len_rv == 3:1765+ rv, status, headers = rv1766+ # decide if a 2-tuple has status or headers1767+ elif len_rv == 2:1768+ if isinstance(rv[1], (Headers, dict, tuple, list)):1769+ rv, headers = rv1770+ else:1771+ rv, status = rv1772+ # other sized tuples are not allowed1773+ else:1774+ raise TypeError(1775+ 'The view function did not return a valid response tuple.'1776+ ' The tuple must have the form (body, status, headers),'1777+ ' (body, status), or (body, headers).'1778+ )1779+1780+ # the body must not be None1781+ if rv is None:1782+ raise TypeError(1783+ 'The view function did not return a valid response. The'1784+ ' function either returned None or ended without a return'1785+ ' statement.'1786+ )1787+1788+ # make sure the body is an instance of the response class1789 if not isinstance(rv, self.response_class):1758- # When we create a response object directly, we let the constructor1759- # set the headers and status. We do this because there can be1760- # some extra logic involved when creating these objects with1761- # specific values (like default content type selection).1790 if isinstance(rv, (text_type, bytes, bytearray)):1763- rv = self.response_class(rv, headers=headers,1764- status=status_or_headers)1765- headers = status_or_headers = None1791+ # let the response class set the status and headers instead of1792+ # waiting to do it manually, so that the class can handle any1793+ # special logic1794+ rv = self.response_class(rv, status=status, headers=headers)1795+ status = headers = None1796 else:1797+ # evaluate a WSGI callable, or coerce a different response1798+ # class to the correct type1799+ try:1767- rv = self.response_class.force_type(rv, request.environ)1800+ rv = self.response_class.force_type(rv, request.environ)1801+ except TypeError as e:1802+ new_error = TypeError(1803+ '{e}\nThe view function did not return a valid'1804+ ' response. The return type must be a string, tuple,'1805+ ' Response instance, or WSGI callable, but it was a'1806+ ' {rv.__class__.__name__}.'.format(e=e, rv=rv)1807+ )1808+ reraise(TypeError, new_error, sys.exc_info()[2])1809 1810+ # prefer the status if it was provided1769- if status_or_headers is not None:1770- if isinstance(status_or_headers, string_types):1771- rv.status = status_or_headers1811+ if status is not None:1812+ if isinstance(status, (text_type, bytes, bytearray)):1813+ rv.status = status1814 else:1773- rv.status_code = status_or_headers1815+ rv.status_code = status1816+1817+ # extend existing headers with provided headers1818 if headers:1819 rv.headers.extend(headers)1820 1821 return rv253 unmodified linesmodified:tests/test_basic.py+96 added-47 removed
973 unmodified lines974 assert 'no file contents were transmitted' in str(e.value)975 assert 'This was submitted: "index.txt"' in str(e.value)976 977 978-def test_response_creation():978+def test_response_types():979 app = flask.Flask(__name__)980+ app.testing = True981 981- @app.route('/unicode')982- def from_unicode():982+ @app.route('/text')983+ def from_text():984 return u'Hällo Wörld'985 985- @app.route('/string')986- def from_string():986+ @app.route('/bytes')987+ def from_bytes():988 return u'Hällo Wörld'.encode('utf-8')989 989- @app.route('/args')990- def from_tuple():990+ @app.route('/full_tuple')991+ def from_full_tuple():992 return 'Meh', 400, {993 'X-Foo': 'Testing',994 'Content-Type': 'text/plain; charset=utf-8'995 }996 996- @app.route('/two_args')997- def from_two_args_tuple():997+ @app.route('/text_headers')998+ def from_text_headers():999 return 'Hello', {1000 'X-Foo': 'Test',1001 'Content-Type': 'text/plain; charset=utf-8'1002 }1003 1003- @app.route('/args_status')1004- def from_status_tuple():1004+ @app.route('/text_status')1005+ def from_text_status():1006 return 'Hi, status!', 4001007 1007- @app.route('/args_header')1008- def from_response_instance_status_tuple():1009- return flask.Response('Hello world', 404), {1008+ @app.route('/response_headers')1009+ def from_response_headers():1010+ return flask.Response('Hello world', 404, {'X-Foo': 'Baz'}), {1011 "X-Foo": "Bar",1012 "X-Bar": "Foo"1013 }1014 1015+ @app.route('/response_status')1016+ def from_response_status():1017+ return app.response_class('Hello world', 400), 5001018+1019+ @app.route('/wsgi')1020+ def from_wsgi():1021+ return NotFound()1022+1023 c = app.test_client()1015- assert c.get('/unicode').data == u'Hällo Wörld'.encode('utf-8')1016- assert c.get('/string').data == u'Hällo Wörld'.encode('utf-8')1017- rv = c.get('/args')1024+1025+ assert c.get('/text').data == u'Hällo Wörld'.encode('utf-8')1026+ assert c.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')1027+1028+ rv = c.get('/full_tuple')1029 assert rv.data == b'Meh'1030 assert rv.headers['X-Foo'] == 'Testing'1031 assert rv.status_code == 4001032 assert rv.mimetype == 'text/plain'1022- rv2 = c.get('/two_args')1023- assert rv2.data == b'Hello'1024- assert rv2.headers['X-Foo'] == 'Test'1025- assert rv2.status_code == 2001026- assert rv2.mimetype == 'text/plain'1027- rv3 = c.get('/args_status')1028- assert rv3.data == b'Hi, status!'1029- assert rv3.status_code == 4001030- assert rv3.mimetype == 'text/html'1031- rv4 = c.get('/args_header')1032- assert rv4.data == b'Hello world'1033- assert rv4.headers['X-Foo'] == 'Bar'1034- assert rv4.headers['X-Bar'] == 'Foo'1035- assert rv4.status_code == 4041033 1034+ rv = c.get('/text_headers')1035+ assert rv.data == b'Hello'1036+ assert rv.headers['X-Foo'] == 'Test'1037+ assert rv.status_code == 2001038+ assert rv.mimetype == 'text/plain'1039 1040+ rv = c.get('/text_status')1041+ assert rv.data == b'Hi, status!'1042+ assert rv.status_code == 4001043+ assert rv.mimetype == 'text/html'1044+1045+ rv = c.get('/response_headers')1046+ assert rv.data == b'Hello world'1047+ assert rv.headers.getlist('X-Foo') == ['Baz', 'Bar']1048+ assert rv.headers['X-Bar'] == 'Foo'1049+ assert rv.status_code == 4041050+1051+ rv = c.get('/response_status')1052+ assert rv.data == b'Hello world'1053+ assert rv.status_code == 5001054+1055+ rv = c.get('/wsgi')1056+ assert b'Not Found' in rv.data1057+ assert rv.status_code == 4041058+1059+1060+def test_response_type_errors():1061+ app = flask.Flask(__name__)1062+ app.testing = True1063+1064+ @app.route('/none')1065+ def from_none():1066+ pass1067+1068+ @app.route('/small_tuple')1069+ def from_small_tuple():1070+ return 'Hello',1071+1072+ @app.route('/large_tuple')1073+ def from_large_tuple():1074+ return 'Hello', 234, {'X-Foo': 'Bar'}, '???'1075+1076+ @app.route('/bad_type')1077+ def from_bad_type():1078+ return True1079+1080+ @app.route('/bad_wsgi')1081+ def from_bad_wsgi():1082+ return lambda: None1083+1084+ c = app.test_client()1085+1086+ with pytest.raises(TypeError) as e:1087+ c.get('/none')1088+ assert 'returned None' in str(e)1089+1090+ with pytest.raises(TypeError) as e:1091+ c.get('/small_tuple')1092+ assert 'tuple must have the form' in str(e)1093+1094+ pytest.raises(TypeError, c.get, '/large_tuple')1095+1096+ with pytest.raises(TypeError) as e:1097+ c.get('/bad_type')1098+ assert 'it was a bool' in str(e)1099+1100+ pytest.raises(TypeError, c.get, '/bad_wsgi')1101+1102+1103 def test_make_response():1104 app = flask.Flask(__name__)1105 with app.test_request_context():1106 rv = flask.make_response()229 unmodified lines1336 # Providing host_matching=True without static_host but with static_folder=None should not error.1337 flask.Flask(__name__, host_matching=True, static_folder=None)1338 1339 1275-def test_none_response():1276- app = flask.Flask(__name__)1277- app.testing = True1278-1279- @app.route('/')1280- def test():1281- return None1282- try:1283- app.test_client().get('/')1284- except ValueError as e:1285- assert str(e) == 'View function did not return a response'1286- pass1287- else:1288- assert "Expected ValueError"1289-1290-1340 def test_request_locals():1341 assert repr(flask.g) == '<LocalProxy unbound>'1342 assert not flask.g1343 507 unmodified linesmodified:CHANGES+4 added
27 unmodified lines28 - Errors caused while opening the session at the beginning of the request are29 handled by the app's error handlers. (`#2254`_)30 - Blueprints gained ``json_encoder`` and ``json_decoder`` attributes to31 override the app's encoder and decoder. (`#1898`_)32+- ``Flask.make_response`` raises ``TypeError`` instead of ``ValueError`` for33+ bad response types. The error messages have been improved to describe why the34+ type is invalid. (`#2256`_)35 36 .. _#1489: https://github.com/pallets/flask/pull/148937 .. _#1898: https://github.com/pallets/flask/pull/189838 .. _#1936: https://github.com/pallets/flask/pull/193639 .. _#2017: https://github.com/pallets/flask/pull/201740 .. _#2223: https://github.com/pallets/flask/pull/222341 .. _#2254: https://github.com/pallets/flask/pull/225442+.. _#2256: https://github.com/pallets/flask/pull/225643 44 Version 0.12.145 --------------46 608 unmodified lines