diff options
author | Maximilian Hils <git@maximilianhils.com> | 2016-08-23 00:39:30 -0700 |
---|---|---|
committer | GitHub <noreply@github.com> | 2016-08-23 00:39:30 -0700 |
commit | 06c499f76ebde90cee49871d9c4be1891f53f6c2 (patch) | |
tree | 59a76a43a8e3348f04ce09136c1ed703dde34a3f /netlib | |
parent | 798ce96bd0d22b642f8508c5d9a8e131bedb4896 (diff) | |
parent | f27028f58e50492c8c8e15e47278bf444d692246 (diff) | |
download | mitmproxy-06c499f76ebde90cee49871d9c4be1891f53f6c2.tar.gz mitmproxy-06c499f76ebde90cee49871d9c4be1891f53f6c2.tar.bz2 mitmproxy-06c499f76ebde90cee49871d9c4be1891f53f6c2.zip |
Merge pull request #1500 from mhils/simple-response-creation
Introduce Response.make for simple response creation
Diffstat (limited to 'netlib')
-rw-r--r-- | netlib/http/response.py | 54 |
1 files changed, 49 insertions, 5 deletions
diff --git a/netlib/http/response.py b/netlib/http/response.py index 85f54940..7866c142 100644 --- a/netlib/http/response.py +++ b/netlib/http/response.py @@ -1,14 +1,19 @@ from __future__ import absolute_import, print_function, division -from email.utils import parsedate_tz, formatdate, mktime_tz -import time import six - +import time +from email.utils import parsedate_tz, formatdate, mktime_tz +from netlib import human +from netlib import multidict from netlib.http import cookies from netlib.http import headers as nheaders from netlib.http import message -from netlib import multidict -from netlib import human +from netlib.http import status_codes +from typing import AnyStr # noqa +from typing import Dict # noqa +from typing import Iterable # noqa +from typing import Tuple # noqa +from typing import Union # noqa class ResponseData(message.MessageData): @@ -54,6 +59,45 @@ class Response(message.Message): details=details ) + @classmethod + def make( + cls, + status_code=200, # type: int + content=b"", # type: AnyStr + headers=() # type: Union[Dict[AnyStr, AnyStr], Iterable[Tuple[bytes, bytes]]] + ): + """ + Simplified API for creating response objects. + """ + resp = cls( + b"HTTP/1.1", + status_code, + status_codes.RESPONSES.get(status_code, "").encode(), + (), + None + ) + # Assign this manually to update the content-length header. + if isinstance(content, bytes): + resp.content = content + elif isinstance(content, str): + resp.text = content + else: + raise TypeError("Expected content to be str or bytes, but is {}.".format( + type(content).__name__ + )) + + # Headers can be list or dict, we differentiate here. + if isinstance(headers, dict): + resp.headers = nheaders.Headers(**headers) + elif isinstance(headers, Iterable): + resp.headers = nheaders.Headers(headers) + else: + raise TypeError("Expected headers to be an iterable or dict, but is {}.".format( + type(headers).__name__ + )) + + return resp + @property def status_code(self): """ |