Skip to content

Commit 7bef42a

Browse files
redjaxredjax
redjax
authored andcommitted
Fix utils, update .gitignore:
Add try/except for importing fastapi utils. Fix imports in all __init__.py files. Add new operations to msgpack_utils. Add serialize/deserialize simple bytestring. Fix diskcache always creating a cache by adding get_cache() function and a default cache conf dict.
1 parent c56ab5a commit 7bef42a

File tree

10 files changed

+149
-91
lines changed

10 files changed

+149
-91
lines changed

.gitignore

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
## Temporarily ignore .ipynb
2-
*.ipynb
2+
# *.ipynb
33

44
# Byte-compiled / optimized / DLL files
55
__pycache__/
@@ -141,6 +141,8 @@ venv.bak/
141141
!*.*.*example*
142142
!*.*.*example*.*
143143

144+
.serialize
145+
144146
# Spyder project settings
145147
.spyderproject
146148
.spyproject

red_utils/__init__.py

+6
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,9 @@
44
from . import httpx_utils
55
from . import loguru_utils
66
from . import msgpack_utils
7+
8+
## Only import fastapi utils if fastapi and uvicorn are installed
9+
try:
10+
from . import fastapi_utils
11+
except:
12+
pass

red_utils/diskcache_utils/__init__.py

+21-7
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,29 @@
11
from __future__ import annotations
22

3+
from typing import Any
4+
35
from .constants import (
46
default_cache_dir,
57
default_timeout_dict,
68
valid_key_types,
79
valid_tag_types,
810
valid_val_types,
911
)
10-
from .operations import convert_to_seconds
12+
13+
from .operations import (
14+
convert_to_seconds,
15+
get_cache,
16+
check_cache,
17+
get_cache_size,
18+
delete_val,
19+
get_val,
20+
set_expire,
21+
set_val,
22+
cache_tag_index,
23+
check_exists,
24+
clear_cache,
25+
)
26+
1127
from .validators import (
1228
validate_cache,
1329
validate_expire,
@@ -19,12 +35,10 @@
1935
validate_val,
2036
)
2137

22-
from diskcache import Cache
23-
2438
## Define a default cache object
25-
default_cache: Cache = Cache(
26-
directory=default_cache_dir,
27-
timeout=convert_to_seconds(
39+
default_cache_conf: dict[str, Any] = {
40+
"directory": default_cache_dir,
41+
"timeout": convert_to_seconds(
2842
unit=default_timeout_dict["unit"], amount=default_timeout_dict["amount"]
2943
),
30-
)
44+
}

red_utils/diskcache_utils/operations.py

+35-10
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030

3131
from diskcache import Cache
3232

33+
3334
def convert_to_seconds(unit: str = None, amount: int = None) -> int:
3435
## Allowed strings for conversion
3536
valid_time_units: list[int] = ["seconds", "hours", "minutes", "days", "weeks"]
@@ -68,8 +69,32 @@ def convert_to_seconds(unit: str = None, amount: int = None) -> int:
6869
return _amount
6970

7071

72+
# def get_cache(
73+
# cache_dir: str = default_cache_dir,
74+
# index: bool = True,
75+
# ) -> diskcache.core.Cache:
76+
# """Prepare and return a diskcache.Cache object."""
77+
# if not cache_dir:
78+
# raise ValueError("Missing cache directory")
79+
80+
# if not isinstance(cache_dir, Union[str, Path]):
81+
# raise TypeError(f"cache_dir must be of type str or Path, not {type(cache_dir)}")
82+
83+
# try:
84+
# _cache: diskcache.core.Cache = Cache(directory=cache_dir)
85+
86+
# if index:
87+
# cache_tag_index(cache=_cache)
88+
89+
# return _cache
90+
91+
# except Exception as exc:
92+
# raise Exception(f"Unhandled exception creating cache. Details: {exc}")
93+
94+
7195
def get_cache(
7296
cache_dir: str = default_cache_dir,
97+
cache_conf: dict = None,
7398
index: bool = True,
7499
) -> diskcache.core.Cache:
75100
"""Prepare and return a diskcache.Cache object."""
@@ -79,8 +104,17 @@ def get_cache(
79104
if not isinstance(cache_dir, Union[str, Path]):
80105
raise TypeError(f"cache_dir must be of type str or Path, not {type(cache_dir)}")
81106

107+
if not cache_conf:
108+
raise ValueError(f"Missing cache")
109+
110+
if not isinstance(cache_conf, dict):
111+
raise TypeError(
112+
f"Invalid type for [cache_conf]: ({type(cache_conf)}). Must be of type dict."
113+
)
114+
82115
try:
83-
_cache: diskcache.core.Cache = Cache(directory=cache_dir)
116+
# _cache: diskcache.core.Cache = Cache(directory=cache_dir)
117+
_cache: diskcache.core.Cache = Cache(**cache_conf)
84118

85119
if index:
86120
cache_tag_index(cache=_cache)
@@ -91,15 +125,6 @@ def get_cache(
91125
raise Exception(f"Unhandled exception creating cache. Details: {exc}")
92126

93127

94-
## Define a default cache object
95-
default_cache: Cache = Cache(
96-
directory=default_cache_dir,
97-
timeout=convert_to_seconds(
98-
unit=default_timeout_dict["unit"], amount=default_timeout_dict["amount"]
99-
),
100-
)
101-
102-
103128
def clear_cache(cache: Cache = None) -> bool:
104129
validate_cache(cache)
105130

red_utils/httpx_utils/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,4 @@
55
from .validators import validate_client, validate_headers, validate_method
66
from .operations import merge_headers, update_headers, get_req_client, make_request
77

8-
from validators import validate_client, validate_headers, validate_method
8+
from .validators import validate_client, validate_headers, validate_method

red_utils/loguru_utils/__init__.py

-1
Original file line numberDiff line numberDiff line change
@@ -21,5 +21,4 @@
2121
default_trace_log_file_sink,
2222
)
2323

24-
from .uvicorn_override import setup_uvicorn_logging
2524
from .validators import validate_compression_str, validate_level, validate_logger

red_utils/loguru_utils/uvicorn_override.py

-64
This file was deleted.

red_utils/main.py

Whitespace-only changes.

red_utils/msgpack_utils/__init__.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
11
from __future__ import annotations
22

33
from .constants import default_serialize_dir
4-
from .operations import msgpack_deserialize, msgpack_serialize
4+
from .operations import (
5+
msgpack_deserialize,
6+
msgpack_serialize,
7+
msgpack_serialize_file,
8+
msgpack_deserialize_file,
9+
)

red_utils/msgpack_utils/operations.py

+77-6
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,43 @@ def ensure_path(dir: Union[str, Path] = None) -> bool:
4646
return True
4747

4848

49-
def msgpack_serialize(
49+
def msgpack_serialize(_json: dict = None) -> dict[str, Union[bool, str, bytes, None]]:
50+
"""Serialize a Python dict to a msgpack string.
51+
52+
Return object will be a dict with 2 keys, 'success' and 'detail.'
53+
Success is a bool indicator of serialize success.
54+
Detail contains the 'message' key with the bytestring, as well as other
55+
optional details to be returned.
56+
"""
57+
if not _json:
58+
raise ValueError("Missing Python dict data to serialize")
59+
60+
try:
61+
packed = msgpack.packb(_json)
62+
63+
print(f"Packed message type ({type(packed)})")
64+
65+
return_obj = {"success": True, "detail": {"message": packed}}
66+
67+
except Exception as exc:
68+
return_obj = {"success": False, "detail": {"message": f"{exc}"}}
69+
70+
return return_obj
71+
72+
73+
def msgpack_serialize_file(
5074
_json: dict = None, output_dir: str = default_serialize_dir, filename: str = None
5175
) -> dict[str, Union[bool, str, dict[str, Union[str, dict]]]]:
76+
"""Serialize a Python dict to a msgpack file.
77+
78+
Accepts a dict input, with an optional output_dir and filename. Serialize the
79+
msgpack data to file at output_dir/filename.
80+
81+
Return object will be a dict with 2 keys, 'success' and 'detail.'
82+
Success is a bool indicator of serialize success.
83+
Detail contains the 'message' key with the bytestring, as well as other
84+
optional details to be returned.
85+
"""
5286
if not _json:
5387
raise ValueError("Missing Python dict data to serialize")
5488

@@ -59,6 +93,8 @@ def msgpack_serialize(
5993

6094
if filename.endswith(".msgpack"):
6195
filename.replace(".msgpack", "")
96+
else:
97+
filename = f"{filename}.msgpack"
6298

6399
dir_exist = ensure_path(output_dir)
64100

@@ -76,18 +112,21 @@ def msgpack_serialize(
76112
}
77113

78114
except Exception as exc:
79-
# log.error(
80-
# {"exception": "Unhandled exception writing msgpack."}, exc_info=True
81-
# )
82-
83115
return_obj = {"success": False, "detail": {"message": f"{exc}"}}
84116

85117
return return_obj
86118

87119

88-
def msgpack_deserialize(
120+
def msgpack_deserialize_file(
89121
filename: str = None,
90122
) -> dict[str, Union[bool, str, dict[str, Union[str, dict]]]]:
123+
"""Load serialized msgpack string from a file and return.
124+
125+
Return object will be a dict with 2 keys, 'success' and 'detail.'
126+
Success is a bool indicator of serialize success.
127+
Detail contains the 'message' key with the bytestring, as well as other
128+
optional details to be returned.
129+
"""
91130
if not filename:
92131
raise ValueError("Must pass a file name/path to deserialize")
93132

@@ -113,3 +152,35 @@ def msgpack_deserialize(
113152
return_obj = {"success": False, "detail": {"message": f"{exc}"}}
114153

115154
return return_obj
155+
156+
157+
def msgpack_deserialize(
158+
packed_str: bytes = None,
159+
) -> dict[str, Union[bool, str, dict[str, Union[str, dict]]]]:
160+
"""Load serialized msgpack string.
161+
162+
Returns a dict with"""
163+
if not packed_str:
164+
raise ValueError("Must pass a bytestring to deserialize")
165+
166+
if not isinstance(packed_str, bytes):
167+
raise TypeError(
168+
f"Invalid type for [packed_str]: ({type(packed_str)}). Must be of type bytestring"
169+
)
170+
171+
try:
172+
unpacked = msgpack.unpackb(packed_str)
173+
174+
return_obj = {
175+
"success": True,
176+
"detail": {
177+
"message": unpacked,
178+
},
179+
}
180+
181+
except Exception as exc:
182+
# log.error({"exception": "Unhandled exception reading msgpack."}, exc_info=True)
183+
184+
return_obj = {"success": False, "detail": {"message": f"{exc}"}}
185+
186+
return return_obj

0 commit comments

Comments
 (0)