Skip to content

Commit

Permalink
Changing the status code of a response after it has been prepared rai…
Browse files Browse the repository at this point in the history
…ses a RuntimeError
  • Loading branch information
arthurdarcet committed Dec 13, 2016
1 parent b7757cd commit d729e4c
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
3 changes: 3 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ CHANGES
- Avoid a race when application might start accepting incoming requests
but startup signals are not processed yet e98e8c6

- Raise a `RuntimeError` when trying to change the status of the HTTP response
after the headers have been sent

-

- Fix bug with https proxy acquired cleanup #1340
Expand Down
6 changes: 5 additions & 1 deletion aiohttp/web_reqrep.py
Original file line number Diff line number Diff line change
Expand Up @@ -509,7 +509,6 @@ def __init__(self, *, status=200, reason=None, headers=None):
self._compression_force = False
self._headers = CIMultiDict()
self._cookies = SimpleCookie()
self.set_status(status, reason)

self._req = None
self._resp_impl = None
Expand All @@ -522,6 +521,8 @@ def __init__(self, *, status=200, reason=None, headers=None):
self._headers.extend(headers)
self._headers.setdefault(hdrs.CONTENT_TYPE, 'application/octet-stream')

self.set_status(status, reason)

@property
def prepared(self):
return self._resp_impl is not None
Expand Down Expand Up @@ -552,6 +553,9 @@ def reason(self):
return self._reason

def set_status(self, status, reason=None):
if self.prepared:
raise RuntimeError("Cannot change the response status code after "
"the headers have been sent")
self._status = int(status)
if reason is None:
reason = ResponseImpl.calc_reason(status)
Expand Down
8 changes: 8 additions & 0 deletions tests/test_web_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -905,6 +905,14 @@ def test_drain_before_start():
yield from resp.drain()


@asyncio.coroutine
def test_changing_status_after_prepare_raises():
resp = StreamResponse()
yield from resp.prepare(make_request('GET', '/'))
with pytest.raises(RuntimeError):
resp.set_status(400)


def test_nonstr_text_in_ctor():
with pytest.raises(TypeError):
Response(text=b'data')
Expand Down

0 comments on commit d729e4c

Please sign in to comment.