Skip to content

Commit aa0c809

Browse files
committed
add set_file and set_path
1 parent f82ab33 commit aa0c809

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

redis/commands/json/commands.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
from .decoders import decode_dict_keys
66
from .path import Path
7+
from json import loads, JSONDecodeError
8+
import os
79

810

911
class JSONCommands:
@@ -213,6 +215,43 @@ def set(self, name, path, obj, nx=False, xx=False, decode_keys=False):
213215
pieces.append("XX")
214216
return self.execute_command("JSON.SET", *pieces)
215217

218+
def set_file(self, name, path, file_name, nx=False, xx=False, decode_keys=False):
219+
"""
220+
Set the JSON value at key ``name`` under the ``path`` to the contents of the json file ``file_name``.
221+
222+
``nx`` if set to True, set ``value`` only if it does not exist.
223+
``xx`` if set to True, set ``value`` only if it exists.
224+
``decode_keys`` If set to True, the keys of ``obj`` will be decoded
225+
with utf-8.
226+
227+
"""
228+
try:
229+
file_content = loads(file_name)
230+
except JSONDecodeError:
231+
raise JSONDecodeError("Inappropriate file type, set_file() requires json file")
232+
233+
return self.set(name, path, file_content, nx, xx, decode_keys)
234+
235+
236+
def set_path(self, json_path, root_directory , nx=False, xx=False, decode_keys=False):
237+
"""
238+
239+
"""
240+
set_files_result = {}
241+
for root, dirs, files in os.walk(root_directory):
242+
for file in files:
243+
try:
244+
file_name = file.rsplit('.')[0]
245+
file_path = os.path.join(root, file)
246+
self.set_file(file_name, json_path, file_path, nx, xx, decode_keys)
247+
set_files_result[os.path.join(root, file)] = True
248+
except JSONDecodeError:
249+
set_files_result[os.path.join(root, file)] = False
250+
251+
return set_files_result
252+
253+
254+
216255
def strlen(self, name, path=None):
217256
"""Return the length of the string JSON value under ``path`` at key
218257
``name``.

tests/test_json.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1392,3 +1392,15 @@ def test_custom_decoder(client):
13921392
assert client.exists("foo") == 0
13931393
assert not isinstance(cj.__encoder__, json.JSONEncoder)
13941394
assert not isinstance(cj.__decoder__, json.JSONDecoder)
1395+
1396+
1397+
@pytest.mark.redismod
1398+
def test_set_file(client):
1399+
import tempfile
1400+
import json
1401+
1402+
jsonfile = tempfile.NamedTemporaryFile(suffix=".json")
1403+
with open(jsonfile.name, 'w+') as fp:
1404+
fp.write(json.dumps({"hello": "world"}))
1405+
1406+
assert client.json().set("test", Path.rootPath(), jsonfile.name)

0 commit comments

Comments
 (0)