|
| 1 | +import os |
| 2 | +from json import JSONDecodeError, loads |
| 3 | + |
1 | 4 | from deprecated import deprecated
|
2 | 5 |
|
3 | 6 | from redis.exceptions import DataError
|
@@ -213,6 +216,54 @@ def set(self, name, path, obj, nx=False, xx=False, decode_keys=False):
|
213 | 216 | pieces.append("XX")
|
214 | 217 | return self.execute_command("JSON.SET", *pieces)
|
215 | 218 |
|
| 219 | + def set_file(self, name, path, file_name, nx=False, xx=False, decode_keys=False): |
| 220 | + """ |
| 221 | + Set the JSON value at key ``name`` under the ``path`` to the content |
| 222 | + of the json file ``file_name``. |
| 223 | +
|
| 224 | + ``nx`` if set to True, set ``value`` only if it does not exist. |
| 225 | + ``xx`` if set to True, set ``value`` only if it exists. |
| 226 | + ``decode_keys`` If set to True, the keys of ``obj`` will be decoded |
| 227 | + with utf-8. |
| 228 | +
|
| 229 | + """ |
| 230 | + |
| 231 | + with open(file_name, "r") as fp: |
| 232 | + file_content = loads(fp.read()) |
| 233 | + |
| 234 | + return self.set(name, path, file_content, nx=nx, xx=xx, decode_keys=decode_keys) |
| 235 | + |
| 236 | + def set_path(self, json_path, root_folder, nx=False, xx=False, decode_keys=False): |
| 237 | + """ |
| 238 | + Iterate over ``root_folder`` and set each JSON file to a value |
| 239 | + under ``json_path`` with the file name as the key. |
| 240 | +
|
| 241 | + ``nx`` if set to True, set ``value`` only if it does not exist. |
| 242 | + ``xx`` if set to True, set ``value`` only if it exists. |
| 243 | + ``decode_keys`` If set to True, the keys of ``obj`` will be decoded |
| 244 | + with utf-8. |
| 245 | +
|
| 246 | + """ |
| 247 | + set_files_result = {} |
| 248 | + for root, dirs, files in os.walk(root_folder): |
| 249 | + for file in files: |
| 250 | + file_path = os.path.join(root, file) |
| 251 | + try: |
| 252 | + file_name = file_path.rsplit(".")[0] |
| 253 | + self.set_file( |
| 254 | + file_name, |
| 255 | + json_path, |
| 256 | + file_path, |
| 257 | + nx=nx, |
| 258 | + xx=xx, |
| 259 | + decode_keys=decode_keys, |
| 260 | + ) |
| 261 | + set_files_result[file_path] = True |
| 262 | + except JSONDecodeError: |
| 263 | + set_files_result[file_path] = False |
| 264 | + |
| 265 | + return set_files_result |
| 266 | + |
216 | 267 | def strlen(self, name, path=None):
|
217 | 268 | """Return the length of the string JSON value under ``path`` at key
|
218 | 269 | ``name``.
|
|
0 commit comments