0b5c75c13c8d2f0eaaea3889d72eadd7d493e826
[sdc/sdc-distribution-client.git] /
1 from __future__ import absolute_import
2 from ..packages.six.moves import http_client as httplib
3
4 from ..exceptions import HeaderParsingError
5
6
7 def is_fp_closed(obj):
8     """
9     Checks whether a given file-like object is closed.
10
11     :param obj:
12         The file-like object to check.
13     """
14
15     try:
16         # Check via the official file-like-object way.
17         return obj.closed
18     except AttributeError:
19         pass
20
21     try:
22         # Check if the object is a container for another file-like object that
23         # gets released on exhaustion (e.g. HTTPResponse).
24         return obj.fp is None
25     except AttributeError:
26         pass
27
28     raise ValueError("Unable to determine whether fp is closed.")
29
30
31 def assert_header_parsing(headers):
32     """
33     Asserts whether all headers have been successfully parsed.
34     Extracts encountered errors from the result of parsing headers.
35
36     Only works on Python 3.
37
38     :param headers: Headers to verify.
39     :type headers: `httplib.HTTPMessage`.
40
41     :raises urllib3.exceptions.HeaderParsingError:
42         If parsing errors are found.
43     """
44
45     # This will fail silently if we pass in the wrong kind of parameter.
46     # To make debugging easier add an explicit check.
47     if not isinstance(headers, httplib.HTTPMessage):
48         raise TypeError('expected httplib.Message, got {0}.'.format(
49             type(headers)))
50
51     defects = getattr(headers, 'defects', None)
52     get_payload = getattr(headers, 'get_payload', None)
53
54     unparsed_data = None
55     if get_payload:  # Platform-specific: Python 3.
56         unparsed_data = get_payload()
57
58     if defects or unparsed_data:
59         raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data)
60
61
62 def is_response_to_head(response):
63     """
64     Checks whether the request of a response has been a HEAD-request.
65     Handles the quirks of AppEngine.
66
67     :param conn:
68     :type conn: :class:`httplib.HTTPResponse`
69     """
70     # FIXME: Can we do this somehow without accessing private httplib _method?
71     method = response._method
72     if isinstance(method, int):  # Platform-specific: Appengine
73         return method == 3
74     return method.upper() == 'HEAD'