- When to use __getattr__
- myDict = {'value': 1}
- myDict['value']
- class DictAsMember(dict):
- def __getattr__(self, name):
- value = self[name]
- if isinstance(value, dict):
- value = DictAsMember(value)
- return value
- my_dict = DictAsMember()
- my_dict['property'] = {'sub_property': 1}
- print(my_dict.property.sub_property) # 1 will be printed
- class requests_wrapper():
- client = requests.session(headers={'Authorization':'myauthtoken'})
- base_path = "http://www.example.com"
- def _make_path_request(self, http_method, path, **kwargs):
- """
- Use the http_method string to find the requests.Session instance's
- method.
- """
- method_to_call = getattr(self.client, http_method.lower())
- return method_to_call(self.base_path + path, **kwargs)
- def path_get(self, path, **kwargs):
- """
- Sends a GET request to base_path + path.
- """
- return self._make_path_request('get', path, **kwargs)
- def path_post(self, path, **kwargs):
- """
- Sends a POST request to base_path + path.
- """
- return self._make_path_request('post', path, **kwargs)
- def path_put(self, path, **kwargs):
- """
- Sends a PUT request to base_path + path.
- """
- return self._make_path_request('put', path, **kwargs)
- def path_delete(self, path, **kwargs):
- """
- Sends a DELETE request to base_path + path.
- """
- return self._make_path_request('delete', path, **kwargs)
- # Initialize
- myclient = requests_wrapper()
- # Make a get request to http://www.example.com/api/spam/eggs
- response = myclient.path_get("/api/spam/eggs")
- # Print the response JSON data
- if response.ok:
- print response.json