Skip to content
Myr

Merge pull request #2256 from davidism/refactor-make_response

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

refactor make_response to be easier to follow

authored by David Lord · committed by GitHub · parents 46f8366, 697f7b9 · 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

3 files+203 added−106 removed

modified:flask/app.py+103 added-59 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11import os12import sys13from threading import Lock13from datetime import timedelta15from itertools import chain14from functools import update_wrapper15from itertools import chain16from threading import Lock1718from werkzeug.datastructures import ImmutableDict19from werkzeug.routing import Map, Rule, RequestRedirect, BuildError20from werkzeug.exceptions import HTTPException, InternalServerError, \21 MethodNotAllowed, BadRequest, default_exceptions18from werkzeug.datastructures import ImmutableDict, Headers19from werkzeug.exceptions import BadRequest, HTTPException, \20 InternalServerError, MethodNotAllowed, default_exceptions21from werkzeug.routing import BuildError, Map, RequestRedirect, Rule2223from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \24 locked_cached_property, _endpoint_from_view_func, find_package, \25 get_debug_flag26from . import json, cli27from .wrappers import Request, Response28from .config import ConfigAttribute, Config29from .ctx import RequestContext, AppContext, _AppCtxGlobals30from .globals import _request_ctx_stack, request, session, g23from . import cli, json24from ._compat import integer_types, reraise, string_types, text_type25from .config import Config, ConfigAttribute26from .ctx import AppContext, RequestContext, _AppCtxGlobals27from .globals import _request_ctx_stack, g, request, session28from .helpers import _PackageBoundObject, \29 _endpoint_from_view_func, find_package, get_debug_flag, \30 get_flashed_messages, locked_cached_property, url_for31from .sessions import SecureCookieSessionInterface32from .signals import appcontext_tearing_down, got_request_exception, \33 request_finished, request_started, request_tearing_down34from .templating import DispatchingJinjaLoader, Environment, \33 _default_template_ctx_processor34from .signals import request_started, request_finished, got_request_exception, \35 request_tearing_down, appcontext_tearing_down36from ._compat import reraise, string_types, text_type, integer_types35 _default_template_ctx_processor36from .wrappers import Request, Response3738# a lock used for logger initialization39_logger_lock = Lock()40
1673 unmodified lines
1714 """1715 return False17161717 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`.17201721 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``:17251723 .. 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.17511725 ======================= ===========================================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 ======================= ===========================================17401741 :param rv: the return value from the view function17421752 .. 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))17561751 if rv is None:1752 raise ValueError('View function did not return a response')1757 status = headers = None17581754 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)17621763 # 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 )17791780 # 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 )17871788 # 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])18091810 # 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 = status18161817 # extend existing headers with provided headers1818 if headers:1819 rv.headers.extend(headers)18201821 return rv
253 unmodified lines
modified:tests/test_basic.py+96 added-47 removed
973 unmodified lines
974 assert 'no file contents were transmitted' in str(e.value)975 assert 'This was submitted: "index.txt"' in str(e.value)976977978def test_response_creation():978def test_response_types():979 app = flask.Flask(__name__)980 app.testing = True981981 @app.route('/unicode')982 def from_unicode():982 @app.route('/text')983 def from_text():984 return u'Hällo Wörld'985985 @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')989989 @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 }996996 @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 }10031003 @app.route('/args_status')1004 def from_status_tuple():1004 @app.route('/text_status')1005 def from_text_status():1006 return 'Hi, status!', 40010071007 @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 }10141015 @app.route('/response_status')1016 def from_response_status():1017 return app.response_class('Hello world', 400), 50010181019 @app.route('/wsgi')1020 def from_wsgi():1021 return NotFound()10221023 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')10241025 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')10271028 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 == 40410331034 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'10391040 rv = c.get('/text_status')1041 assert rv.data == b'Hi, status!'1042 assert rv.status_code == 4001043 assert rv.mimetype == 'text/html'10441045 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 == 40410501051 rv = c.get('/response_status')1052 assert rv.data == b'Hello world'1053 assert rv.status_code == 50010541055 rv = c.get('/wsgi')1056 assert b'Not Found' in rv.data1057 assert rv.status_code == 404105810591060def test_response_type_errors():1061 app = flask.Flask(__name__)1062 app.testing = True10631064 @app.route('/none')1065 def from_none():1066 pass10671068 @app.route('/small_tuple')1069 def from_small_tuple():1070 return 'Hello',10711072 @app.route('/large_tuple')1073 def from_large_tuple():1074 return 'Hello', 234, {'X-Foo': 'Bar'}, '???'10751076 @app.route('/bad_type')1077 def from_bad_type():1078 return True10791080 @app.route('/bad_wsgi')1081 def from_bad_wsgi():1082 return lambda: None10831084 c = app.test_client()10851086 with pytest.raises(TypeError) as e:1087 c.get('/none')1088 assert 'returned None' in str(e)10891090 with pytest.raises(TypeError) as e:1091 c.get('/small_tuple')1092 assert 'tuple must have the form' in str(e)10931094 pytest.raises(TypeError, c.get, '/large_tuple')10951096 with pytest.raises(TypeError) as e:1097 c.get('/bad_type')1098 assert 'it was a bool' in str(e)10991100 pytest.raises(TypeError, c.get, '/bad_wsgi')110111021103def test_make_response():1104 app = flask.Flask(__name__)1105 with app.test_request_context():1106 rv = flask.make_response()
229 unmodified lines
1336 # 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)133813391275def test_none_response():1276 app = flask.Flask(__name__)1277 app.testing = True12781279 @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"128912901340def test_request_locals():1341 assert repr(flask.g) == '<LocalProxy unbound>'1342 assert not flask.g1343
507 unmodified lines
modified:CHANGES+4 added
27 unmodified lines
28- 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`_)3536.. _#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/22564344Version 0.12.145--------------46
608 unmodified lines