You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

response.py 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. from __future__ import absolute_import
  2. from ..packages.six.moves import http_client as httplib
  3. from ..exceptions import HeaderParsingError
  4. def is_fp_closed(obj):
  5. """
  6. Checks whether a given file-like object is closed.
  7. :param obj:
  8. The file-like object to check.
  9. """
  10. try:
  11. # Check `isclosed()` first, in case Python3 doesn't set `closed`.
  12. # GH Issue #928
  13. return obj.isclosed()
  14. except AttributeError:
  15. pass
  16. try:
  17. # Check via the official file-like-object way.
  18. return obj.closed
  19. except AttributeError:
  20. pass
  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. raise ValueError("Unable to determine whether fp is closed.")
  28. def assert_header_parsing(headers):
  29. """
  30. Asserts whether all headers have been successfully parsed.
  31. Extracts encountered errors from the result of parsing headers.
  32. Only works on Python 3.
  33. :param headers: Headers to verify.
  34. :type headers: `httplib.HTTPMessage`.
  35. :raises urllib3.exceptions.HeaderParsingError:
  36. If parsing errors are found.
  37. """
  38. # This will fail silently if we pass in the wrong kind of parameter.
  39. # To make debugging easier add an explicit check.
  40. if not isinstance(headers, httplib.HTTPMessage):
  41. raise TypeError('expected httplib.Message, got {0}.'.format(
  42. type(headers)))
  43. defects = getattr(headers, 'defects', None)
  44. get_payload = getattr(headers, 'get_payload', None)
  45. unparsed_data = None
  46. if get_payload:
  47. # get_payload is actually email.message.Message.get_payload;
  48. # we're only interested in the result if it's not a multipart message
  49. if not headers.is_multipart():
  50. payload = get_payload()
  51. if isinstance(payload, (bytes, str)):
  52. unparsed_data = payload
  53. if defects or unparsed_data:
  54. raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data)
  55. def is_response_to_head(response):
  56. """
  57. Checks whether the request of a response has been a HEAD-request.
  58. Handles the quirks of AppEngine.
  59. :param conn:
  60. :type conn: :class:`httplib.HTTPResponse`
  61. """
  62. # FIXME: Can we do this somehow without accessing private httplib _method?
  63. method = response._method
  64. if isinstance(method, int): # Platform-specific: Appengine
  65. return method == 3
  66. return method.upper() == 'HEAD'