Browse Source

Added request.Session usage (#268)

* Added request session

* Added vim to .gitignore

* Added requests.Session doc

* Added tests
master
Anthony Monthe 2 years ago
committed by Lorenzo Setale
parent
commit
d0221b5785
  1. 3
      .gitignore
  2. 45
      README.md
  3. 10
      digitalocean/baseapi.py
  4. 12
      digitalocean/tests/test_baseapi.py

3
.gitignore

@ -41,3 +41,6 @@ MANIFEST
.cache
.venv
*.sw[pon]
.eggs

45
README.md

@ -22,7 +22,8 @@
- [Add SSHKey into DigitalOcean Account](#add-sshkey-into-digitalocean-account)
- [Creating a new droplet with all your SSH keys](#creating-a-new-droplet-with-all-your-ssh-keys)
- [Creating a Firewall](#creating-a-firewall)
- [Getting account requests/hour limits status](#getting-account-requests-hour-limits-status)
- [Getting account requests/hour limits status](#getting-account-requestshour-limits-status)
- [Session customization](#session-customization)
- [Testing](#testing)
- [Test using Docker](#test-using-docker)
- [Testing using pytest manually](#testing-using-pytest-manually)
@ -240,6 +241,48 @@ print(manager.ratelimit_limit)
**[⬆ back to top](#table-of-contents)**
## Session customization
You can take advandtage of the [requests](http://docs.python-requests.org/en/master/) library and configure the HTTP client under python-digitalocean.
### Configure retries in case of connection error
This example shows how to configure your client to retry 3 times in case of `ConnectionError`:
```python
import digitalocean
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
retry = Retry(connect=3)
adapter = HTTPAdapter(max_retries=retry)
manager._session.mount('https://', adapter)
```
See [`Retry`](https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html#urllib3.util.retry.Retry) object reference to get more details about all retries options.
### Configure a hook on specified answer
This example shows how to launch custom actions if a HTTP 500 occurs:
```python
import digitalocean
def handle_response(response, *args, **kwargs):
if response.status_code == 500:
# Make a lot things from the raw response
pass
return response
manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
manager._session.hooks['response'].append(handle_response)
```
See [event hooks documentation](http://docs.python-requests.org/en/master/user/advanced/?highlight=HTTPAdapter#event-hooks) to get more details about this feature.
**[⬆ back to top](#table-of-contents)**
## Testing
### Test using Docker

10
digitalocean/baseapi.py

@ -50,6 +50,8 @@ class BaseAPI(object):
self.end_point = "https://api.digitalocean.com/v2/"
self._log = logging.getLogger(__name__)
self._session = requests.Session()
for attr in kwargs.keys():
setattr(self, attr, kwargs[attr])
@ -83,12 +85,12 @@ class BaseAPI(object):
identity = lambda x: x
json_dumps = lambda x: json.dumps(x)
lookup = {
GET: (requests.get, {}, 'params', identity),
POST: (requests.post, {'Content-type': 'application/json'}, 'data',
GET: (self._session.get, {}, 'params', identity),
POST: (self._session.post, {'Content-type': 'application/json'}, 'data',
json_dumps),
PUT: (requests.put, {'Content-type': 'application/json'}, 'data',
PUT: (self._session.put, {'Content-type': 'application/json'}, 'data',
json_dumps),
DELETE: (requests.delete,
DELETE: (self._session.delete,
{'content-type': 'application/json'},
'data', json_dumps),
}

12
digitalocean/tests/test_baseapi.py

@ -29,3 +29,15 @@ class TestBaseAPI(BaseTest):
self.assertEqual(responses.calls[0].request.headers['User-Agent'],
self.user_agent)
@responses.activate
def test_customize_session(self):
data = self.load_from_file('account/account.json')
url = self.base_url + 'account/'
responses.add(responses.GET, url,
body=data,
status=200,
content_type='application/json')
self.manager._session.proxies['https'] = 'https://127.0.0.1:3128'
self.manager.get_account()
Loading…
Cancel
Save