Browse Source

Clean up json dumps (#642)

Xiaojing Chen 2 years ago
parent
commit
ae5b6426aa
4 changed files with 20 additions and 10 deletions
  1. 3 3
      pynecone/components/tags/tag.py
  2. 2 2
      pynecone/event.py
  3. 12 0
      pynecone/utils.py
  4. 3 5
      tests/test_event.py

+ 3 - 3
pynecone/components/tags/tag.py

@@ -68,7 +68,7 @@ class Tag(Base):
             if not prop.is_local or prop.is_string:
                 return str(prop)
             if issubclass(prop.type_, str):
-                return json.dumps(prop.full_name, ensure_ascii=False)
+                return utils.json_dumps(prop.full_name)
             prop = prop.full_name
 
         # Handle event props.
@@ -88,7 +88,7 @@ class Tag(Base):
         elif isinstance(prop, str):
             if utils.is_wrapped(prop, "{"):
                 return prop
-            return json.dumps(prop, ensure_ascii=False)
+            return utils.json_dumps(prop)
 
         elif isinstance(prop, Figure):
             prop = json.loads(to_json(prop))["data"]  # type: ignore
@@ -103,7 +103,7 @@ class Tag(Base):
                 }
 
             # Dump the prop as JSON.
-            prop = json.dumps(prop, ensure_ascii=False)
+            prop = utils.json_dumps(prop)
 
             # This substitution is necessary to unwrap var values.
             prop = re.sub('"{', "", prop)

+ 2 - 2
pynecone/event.py

@@ -2,9 +2,9 @@
 from __future__ import annotations
 
 import inspect
-import json
 from typing import Any, Callable, Dict, List, Set, Tuple
 
+from pynecone import utils
 from pynecone.base import Base
 from pynecone.var import BaseVar, Var
 
@@ -67,7 +67,7 @@ class EventHandler(Base):
 
             # Otherwise, convert to JSON.
             try:
-                values.append(json.dumps(arg, ensure_ascii=False))
+                values.append(utils.json_dumps(arg))
             except TypeError as e:
                 raise TypeError(
                     f"Arguments to event handlers must be Vars or JSON-serializable. Got {arg} of type {type(arg)}."

+ 12 - 0
pynecone/utils.py

@@ -1576,5 +1576,17 @@ def is_backend_variable(name: str) -> bool:
     return name.startswith("_") and not name.startswith("__")
 
 
+def json_dumps(obj: Any):
+    """Serialize ``obj`` to a JSON formatted ``str``, ensure_ascii=False.
+
+    Args:
+        obj: The obj to be fromatted
+
+    Returns:
+        str: The result of the json dumps
+    """
+    return json.dumps(obj, ensure_ascii=False)
+
+
 # Store this here for performance.
 StateBases = get_base_class(StateVar)

+ 3 - 5
tests/test_event.py

@@ -1,8 +1,6 @@
-import json
-
 import pytest
 
-from pynecone import event
+from pynecone import event, utils
 from pynecone.event import Event, EventHandler, EventSpec
 from pynecone.var import Var
 
@@ -59,8 +57,8 @@ def test_call_event_handler():
     assert event_spec.handler == handler
     assert event_spec.local_args == ()
     assert event_spec.args == (
-        ("arg1", json.dumps(first, ensure_ascii=False)),
-        ("arg2", json.dumps(second, ensure_ascii=False)),
+        ("arg1", utils.json_dumps(first)),
+        ("arg2", utils.json_dumps(second)),
     )
 
     handler = EventHandler(fn=test_fn_with_args)