Skip to content

Commit d94e4e2

Browse files
committed
python: update KVS api to work with modern KVS
Problem: The KVS python interface writes all data to the KVS in JSON and reads all data back assuming it is formatted in JSON. This appears to be legacy implementation from the days that all data in the KVS was required to be formatted in JSON. There are still some benefits to doing this, for example Python lists/dicts can be written/read back easily. However, there are clear problems with this, most notably data written in non-JSON format cannot be read from the KVS via the Python interface at all. Solution: With the goal of not breaking current code, support the following compromise. If data that is read back is not in JSON format, return it as a string if all the data is UTF-8 valid. If it is not UTF-8 valid, return it in a Python bytes object. If data cannot be written in JSON, write it as binary data if the data is a bytes object. Fixes #5198
1 parent a1fe4dd commit d94e4e2

File tree

1 file changed

+15
-3
lines changed
  • src/bindings/python/flux

1 file changed

+15
-3
lines changed

src/bindings/python/flux/kvs.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,12 @@ def get_key_direct(flux_handle, key):
3535
if valp[0] == ffi.NULL:
3636
return None
3737

38-
ret = json.loads(ffi.string(valp[0]).decode("utf-8"))
38+
try:
39+
ret = json.loads(ffi.string(valp[0]).decode("utf-8"))
40+
except json.decoder.JSONDecodeError:
41+
ret = ffi.string(valp[0]).decode("utf-8")
42+
except UnicodeDecodeError:
43+
ret = ffi.string(valp[0])
3944
RAW.flux_future_destroy(future)
4045
return ret
4146

@@ -78,10 +83,17 @@ def get(flux_handle, key):
7883

7984

8085
def put(flux_handle, key, value):
81-
json_str = json.dumps(value)
8286
if flux_handle.aux_txn is None:
8387
flux_handle.aux_txn = RAW.flux_kvs_txn_create()
84-
return RAW.flux_kvs_txn_put(flux_handle.aux_txn, 0, key, json_str)
88+
try:
89+
json_str = json.dumps(value)
90+
return RAW.flux_kvs_txn_put(flux_handle.aux_txn, 0, key, json_str)
91+
except TypeError:
92+
if isinstance(value, bytes):
93+
return RAW.flux_kvs_txn_put_raw(
94+
flux_handle.aux_txn, 0, key, value, len(value)
95+
)
96+
raise TypeError
8597

8698

8799
def put_mkdir(flux_handle, key):

0 commit comments

Comments
 (0)