Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 15th, 2012  |  syntax: None  |  size: 1.74 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. When to use __getattr__
  2. myDict = {'value': 1}
  3.        
  4. myDict['value']
  5.        
  6. class DictAsMember(dict):
  7.     def __getattr__(self, name):
  8.         value = self[name]
  9.         if isinstance(value, dict):
  10.             value = DictAsMember(value)
  11.         return value
  12.  
  13. my_dict = DictAsMember()
  14. my_dict['property'] = {'sub_property': 1}
  15.  
  16. print(my_dict.property.sub_property) # 1 will be printed
  17.        
  18. class requests_wrapper():
  19.     client = requests.session(headers={'Authorization':'myauthtoken'})
  20.     base_path = "http://www.example.com"
  21.  
  22.     def _make_path_request(self, http_method, path, **kwargs):
  23.         """
  24.         Use the http_method string to find the requests.Session instance's
  25.         method.
  26.         """
  27.         method_to_call = getattr(self.client, http_method.lower())
  28.         return method_to_call(self.base_path + path, **kwargs)
  29.  
  30.     def path_get(self, path, **kwargs):
  31.         """
  32.         Sends a GET request to base_path + path.
  33.         """
  34.         return self._make_path_request('get', path, **kwargs)
  35.  
  36.     def path_post(self, path, **kwargs):
  37.         """
  38.         Sends a POST request to base_path + path.
  39.         """
  40.         return self._make_path_request('post', path, **kwargs)
  41.  
  42.     def path_put(self, path, **kwargs):
  43.         """
  44.         Sends a PUT request to base_path + path.
  45.         """
  46.         return self._make_path_request('put', path, **kwargs)
  47.  
  48.     def path_delete(self, path, **kwargs):
  49.         """
  50.         Sends a DELETE request to base_path + path.
  51.         """
  52.         return self._make_path_request('delete', path, **kwargs)
  53.        
  54. # Initialize
  55. myclient = requests_wrapper()
  56. # Make a get request to http://www.example.com/api/spam/eggs
  57. response = myclient.path_get("/api/spam/eggs")
  58. # Print the response JSON data
  59. if response.ok:
  60.     print response.json