Skip to content

Commit

Permalink
Allow pretty printing storage json (#3396)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
3 people authored Jul 26, 2024
1 parent 63deabf commit df177df
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 5 deletions.
7 changes: 5 additions & 2 deletions nicegui/json/builtin_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@
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.
Expand All @@ -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)
Expand Down
9 changes: 8 additions & 1 deletion nicegui/json/orjson_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@
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.
Expand All @@ -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')


Expand Down
5 changes: 3 additions & 2 deletions nicegui/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,10 @@ def __len__(self) -> int:

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:
Expand All @@ -68,7 +69,7 @@ def backup(self) -> None:

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:
Expand Down
7 changes: 7 additions & 0 deletions website/documentation/content/storage_documentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
''')

0 comments on commit df177df

Please sign in to comment.