Created
October 27, 2015 16:35
-
-
Save jeffdeville/6fd6de93721a15ab217f to your computer and use it in GitHub Desktop.
Decorating for python apis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def log(func): | |
@wraps(func) | |
def log_wrapper(func): | |
log_input(func.__name__, url, **new_kwargs) | |
try: | |
resp = func(url, **new_kwargs) | |
log_output(resp) | |
except Exception, e: | |
log_exception(e, resp) | |
raise e | |
return log_wrapper | |
def set_defaults(func, headers=None, timeout=(5, 30), should_log=True): | |
@wraps(func) | |
def defaults_wrapper(url, **kwargs): | |
new_kwargs = kwargs.copy() | |
if headers: | |
new_kwargs.update({'headers': headers}) | |
if 'timeout' not in new_kwargs: | |
new_kwargs['timeout'] = timeout | |
return func(url, **new_kwargs) | |
return defaults_wrapper | |
# Note that the order of these will matter! | |
# If you log before you set_defaults, you won't get the full curl command | |
# Also, IF we choose to put extract json as a wrapper, we'll have to be aware that it changes | |
# what is being returned, which kind of breaks the ethos of decorators. I think extract_json | |
# may actually belong in the method itself, like this. This is because it's not really an orthogonal | |
# operation | |
@handle_connection_errors | |
@log | |
@set_defaults(headers=settings.HEADERS) | |
def request(method, url, **kwargs): | |
response = requests.request(url, **kwargs) | |
try: | |
retval = response.json() | |
return retval | |
except Exception: | |
logger.error("Expected a JSON response, but got '%s'" % response.text) | |
raise JsonFormatError("Couldn't convert output to JSON", response) | |
def get(url, **kwargs): | |
requests('get', url, **kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment