Explorar el Código

Move timeout check into context manager

Matthias Vogelgesang hace 9 años
padre
commit
e428a690f3
Se han modificado 1 ficheros con 13 adiciones y 12 borrados
  1. 13 12
      dm/client.py

+ 13 - 12
dm/client.py

@@ -1,6 +1,7 @@
 import os
 import requests
 import logging
+import contextlib
 from xml.etree import ElementTree
 from requests_oauthlib import OAuth1
 from .models import (Object, Download, Ingest, Investigation, User,
@@ -27,6 +28,14 @@ def check_response(response):
         raise ArbitraryError(response)
 
 
+@contextlib.contextmanager
+def check_timeouts():
+    try:
+        yield
+    except requests.exceptions.Timeout:
+        raise Timeout()
+
+
 class Client(object):
     def __init__(self, base_url=BASE_URL, key=KEY, secret=SECRET,
                  token=TOKEN, token_secret=TOKEN_SECRET):
@@ -98,37 +107,29 @@ class Client(object):
     def delete(self, url):
         self.log.debug("DELETE {}".format(url))
 
-        try:
+        with check_timeouts():
             response = self.session.delete(url, timeout=5)
             check_response(response)
-        except requests.exceptions.Timeout:
-            raise Timeout
 
     def get(self, url, **params):
         self.log.debug("GET {}".format(url))
 
-        try:
+        with check_timeouts():
             response = self.session.get(url, params=params, timeout=5)
             check_response(response)
             return ElementTree.fromstring(response.text)
-        except requests.exceptions.Timeout:
-            raise Timeout()
 
     def post(self, url, **params):
         self.log.debug("POST {}".format(url))
 
-        try:
+        with check_timeouts():
             response = self.session.post(url, data=params, timeout=5)
             check_response(response)
             return ElementTree.fromstring(response.text)
-        except requests.exceptions.Timeout:
-            raise Timeout()
 
     def put(self, url, **params):
         self.log.debug("PUT {}".format(url))
 
-        try:
+        with check_timeouts():
             response = self.session.put(url, data=params, timeout=5)
             check_response(response)
-        except requests.exceptions.Timeout:
-            raise Timeout()