willingc

requests and json

May 6th, 2014
451
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.15 KB | None | 0 0
  1. # Test for json post requests
  2.  
  3. import requests
  4. import json
  5.  
  6.  
  7. url = 'http://httpbin.org/post'
  8.  
  9. json_dict = {'life': '42'}
  10.  
  11. r = requests.post(url, json.dumps(json_dict))
  12. print r
  13.  
  14. # Question 1: How to recognize that {'life': '42'} is json?
  15. # Question 2: models.py - where to handle the conversion of {'life': '42'}
  16. #                         to data that can be used by 'request'
  17. #                         request('post', url, **kwargs)
  18. #
  19. # where possible **kwargs params are:
  20. #     :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
  21. #     :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
  22. #     :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
  23. #     :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
  24. #     :param files: (optional) Dictionary of 'name': file-like-objects (or {'name': ('filename', fileobj)}) for multipart encoding upload.
  25.  
  26.  
  27. # ------------------------------------------
  28. # *** requests.post will construct a request
  29. # ------------------------------------------
  30. r = request('post', url, json.dumps(json_dict))
  31.  
  32. # def request(method, url, **kwargs):
  33. #     """Constructs and sends a :class:`Request <Request>`.
  34. #     Returns :class:`Response <Response>` object.
  35. #
  36. #     :param method: method for the new :class:`Request` object.
  37. #     :param url: URL for the new :class:`Request` object.
  38. #     :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
  39. #     :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
  40. #     :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
  41. #     :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
  42. #     :param files: (optional) Dictionary of 'name': file-like-objects (or {'name': ('filename', fileobj)}) for multipart encoding upload.
  43. #     :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
  44. #     :param timeout: (optional) Float describing the timeout of the request in seconds.
  45. #     :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
  46. #     :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
  47. #     :param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided.
  48. #     :param stream: (optional) if ``False``, the response content will be immediately downloaded.
  49. #     :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
  50.  
  51.  
  52. # *** data and headers seem tp be the important items for json
  53.  
  54. def prepare_body(self, data, files):
  55.  
  56.     # *** data
  57.     json.dumps({'life': '42'})
  58.  
  59.     # *** header
  60.          # content-length
  61.          # content-type
  62.  
  63.  
  64. # ----------------------------------------------
  65. # json for the complement of request -- response
  66. # ----------------------------------------------
  67. def json(self, **kwargs):
  68.         """Returns the json-encoded content of a response, if any.
  69.  
  70.        :param \*\*kwargs: Optional arguments that ``json.loads`` takes.
  71.        """
  72.  
  73.         if not self.encoding and len(self.content) > 3:
  74.             # No encoding set. JSON RFC 4627 section 3 states we should expect
  75.             # UTF-8, -16 or -32. Detect which one to use; If the detection or
  76.             # decoding fails, fall back to `self.text` (using chardet to make
  77.             # a best guess).
  78.             encoding = guess_json_utf(self.content)
  79.             if encoding is not None:
  80.                 try:
  81.                     return json.loads(self.content.decode(encoding), **kwargs)
  82.                 except UnicodeDecodeError:
  83.                     # Wrong UTF codec detected; usually because it's not UTF-8
  84.                     # but some other 8-bit codec.  This is an RFC violation,
  85.                     # and the server didn't bother to tell us what codec *was*
  86.                     # used.
  87.                     pass
  88.         return json.loads(self.text, **kwargs)
Advertisement
Add Comment
Please, Sign In to add comment