Development of an internal social media platform with personalised dashboards for students
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.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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: # Platform-specific: Python 3.
  47. unparsed_data = get_payload()
  48. if defects or unparsed_data:
  49. raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data)
  50. def is_response_to_head(response):
  51. """
  52. Checks whether the request of a response has been a HEAD-request.
  53. Handles the quirks of AppEngine.
  54. :param conn:
  55. :type conn: :class:`httplib.HTTPResponse`
  56. """
  57. # FIXME: Can we do this somehow without accessing private httplib _method?
  58. method = response._method
  59. if isinstance(method, int): # Platform-specific: Appengine
  60. return method == 3
  61. return method.upper() == 'HEAD'