|
| 1 | +from functools import wraps |
| 2 | +from typing import List, Union, Dict, Callable |
| 3 | + |
| 4 | + |
| 5 | +def parse_response(expected: str) -> Callable: |
| 6 | + """ |
| 7 | + Decorator for a function that returns a requests.Response object. |
| 8 | + This decorator parses that response depending on the value of <expected>. |
| 9 | +
|
| 10 | + If the response indicates the request failed (status >= 400) a dictionary |
| 11 | + containing the response status and message will be returned. Otherwise, |
| 12 | + the content will be parsed and a dictionary or list will be returned if |
| 13 | + expected == 'json', a string will be returned if expected == 'text' and |
| 14 | + a binary string will be returned if expected == 'content'. |
| 15 | +
|
| 16 | + This also updates the return annotation for the wrapped function according |
| 17 | + to the expected return value type. |
| 18 | + """ |
| 19 | + |
| 20 | + def _parser(f): |
| 21 | + @wraps(f) |
| 22 | + def _f(*args, **kwargs): |
| 23 | + response = f(*args, **kwargs) |
| 24 | + if not response.ok or expected == "json": |
| 25 | + return response.json() |
| 26 | + if expected == "content": |
| 27 | + return response.content |
| 28 | + if expected == "text": |
| 29 | + return response.text |
| 30 | + return response.json() |
| 31 | + |
| 32 | + f.__annotations__["return"] = _get_expected_return(expected) |
| 33 | + return _f |
| 34 | + |
| 35 | + return _parser |
| 36 | + |
| 37 | + |
| 38 | +def _get_expected_return(expected: str) -> type: |
| 39 | + if expected == "json": |
| 40 | + return Union[Dict[str, str], List[Dict[str, str]]] |
| 41 | + elif expected == "content": |
| 42 | + return Union[Dict[str, str], bytes] |
| 43 | + elif expected == "text": |
| 44 | + return Union[Dict[str, str], bytes] |
| 45 | + return Dict[str, str] |
0 commit comments