1
0
Эх сурвалжийг харах

Allow pretty printing storage json (#3396)

* added flags to allow pretty printing storage json

* code review

* don't indent by default

* add documentation

---------

Co-authored-by: Shriv Seshan <5642476+stevesdawg@users.noreply.github.com>
Co-authored-by: Falko Schindler <falko@zauberzeug.com>
Shriv 9 сар өмнө
parent
commit
df177dfa44

+ 5 - 2
nicegui/json/builtin_wrapper.py

@@ -11,7 +11,10 @@ except ImportError:
     has_numpy = False
 
 
-def dumps(obj: Any, sort_keys: bool = False, separators: Optional[Tuple[str, str]] = None):
+def dumps(obj: Any,
+          sort_keys: bool = False,
+          separators: Optional[Tuple[str, str]] = None, *,
+          indent: bool = True) -> str:
     """Serializes a Python object to a JSON-encoded string.
 
     This implementation uses Python's default json module, but extends it in order to support NumPy arrays.
@@ -22,7 +25,7 @@ def dumps(obj: Any, sort_keys: bool = False, separators: Optional[Tuple[str, str
         obj,
         sort_keys=sort_keys,
         separators=separators,
-        indent=None,
+        indent=2 if indent else None,
         allow_nan=False,
         ensure_ascii=False,
         cls=NumpyJsonEncoder)

+ 8 - 1
nicegui/json/orjson_wrapper.py

@@ -14,7 +14,10 @@ except ImportError:
 ORJSON_OPTS = orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_NON_STR_KEYS
 
 
-def dumps(obj: Any, sort_keys: bool = False, separators: Optional[Tuple[str, str]] = None):
+def dumps(obj: Any,
+          sort_keys: bool = False,
+          separators: Optional[Tuple[str, str]] = None, *,
+          indent: bool = True) -> str:
     """Serializes a Python object to a JSON-encoded string.
 
     By default, this function supports serializing NumPy arrays, which Python's json module does not.
@@ -33,6 +36,10 @@ def dumps(obj: Any, sort_keys: bool = False, separators: Optional[Tuple[str, str
     if sort_keys:
         opts |= orjson.OPT_SORT_KEYS
 
+    # flag for pretty-printing with indentation
+    if indent:
+        opts |= orjson.OPT_INDENT_2
+
     return orjson.dumps(obj, option=opts, default=_orjson_converter).decode('utf-8')
 
 

+ 3 - 2
nicegui/storage.py

@@ -49,9 +49,10 @@ class ReadOnlyDict(MutableMapping):
 
 class PersistentDict(observables.ObservableDict):
 
-    def __init__(self, filepath: Path, encoding: Optional[str] = None) -> None:
+    def __init__(self, filepath: Path, encoding: Optional[str] = None, *, indent: bool = False) -> None:
         self.filepath = filepath
         self.encoding = encoding
+        self.indent = indent
         try:
             data = json.loads(filepath.read_text(encoding)) if filepath.exists() else {}
         except Exception:
@@ -68,7 +69,7 @@ class PersistentDict(observables.ObservableDict):
 
         async def backup() -> None:
             async with aiofiles.open(self.filepath, 'w', encoding=self.encoding) as f:
-                await f.write(json.dumps(self))
+                await f.write(json.dumps(self, indent=self.indent))
         if core.loop:
             background_tasks.create_lazy(backup(), name=self.filepath.stem)
         else:

+ 7 - 0
website/documentation/content/storage_documentation.py

@@ -152,3 +152,10 @@ def short_term_memory():
         ui.button('Update content',
                   on_click=lambda: cache.update(count=cache['count'] + 1))
         ui.button('Reload page', on_click=ui.navigate.reload)
+
+
+doc.text('Indentation', '''
+    By default, the general and user storage data is stored in JSON format without indentation.
+    You can change this to an indentation of 2 spaces by setting
+    `app.storage.general.indent = True` or `app.storage.user.indent = True`.
+''')