diff options
| author | Jordan Cook <jordan.cook@pioneer.com> | 2022-03-19 11:55:20 -0500 |
|---|---|---|
| committer | Jordan Cook <jordan.cook@pioneer.com> | 2022-03-29 12:17:43 -0500 |
| commit | b3646b03bc05f5b05f4384eb9a2b4796fa59cb34 (patch) | |
| tree | 77d3dfbcb5213deb4d59972301f7b6302343748b /requests_cache/_utils.py | |
| parent | 4b524f7298093bb4c27cb3419d4ddafc7e42891e (diff) | |
| download | requests-cache-b3646b03bc05f5b05f4384eb9a2b4796fa59cb34.tar.gz | |
Split datetime-related utility functions into a separate module
Diffstat (limited to 'requests_cache/_utils.py')
| -rw-r--r-- | requests_cache/_utils.py | 24 |
1 files changed, 22 insertions, 2 deletions
diff --git a/requests_cache/_utils.py b/requests_cache/_utils.py index b3dfaee..b0067cd 100644 --- a/requests_cache/_utils.py +++ b/requests_cache/_utils.py @@ -1,7 +1,7 @@ -"""Miscellaneous minor utility functions that don't really belong anywhere else""" +"""Minor internal utility functions that don't really belong anywhere else""" from inspect import signature from logging import getLogger -from typing import Any, Callable, Dict, Iterable, Iterator, List +from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional logger = getLogger('requests_cache') @@ -18,6 +18,18 @@ def coalesce(*values: Any, default=None) -> Any: return next((v for v in values if v is not None), default) +def decode(value, encoding='utf-8') -> str: + """Decode a value from bytes, if hasn't already been. + Note: ``PreparedRequest.body`` is always encoded in utf-8. + """ + return value.decode(encoding) if isinstance(value, bytes) else value + + +def encode(value, encoding='utf-8') -> bytes: + """Encode a value to bytes, if it hasn't already been""" + return value if isinstance(value, bytes) else str(value).encode(encoding) + + def get_placeholder_class(original_exception: Exception = None): """Create a placeholder type for a class that does not have dependencies installed. This allows delaying ImportErrors until init time, rather than at import time. @@ -46,3 +58,11 @@ def get_valid_kwargs(func: Callable, kwargs: Dict, extras: Iterable[str] = None) params = list(signature(func).parameters) params.extend(extras or []) return {k: v for k, v in kwargs.items() if k in params and v is not None} + + +def try_int(value: Any) -> Optional[int]: + """Convert a value to an int, if possible, otherwise ``None``""" + try: + return int(value) + except (TypeError, ValueError): + return None |
