Skip to content

Commit

Permalink
Merge pull request #1683 from camptocamp/backport/1648-to-5.0
Browse files Browse the repository at this point in the history
[Backport 5.0] No sort_keys and pretty print by default in JSON renderers
  • Loading branch information
sbrunner authored Dec 6, 2022
2 parents d298df3 + f3ddff5 commit 2962a7f
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 8 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,9 @@ accessed with a good secret, a cookie is stored and the secret can be omitted.
An alternative of using `C2C_SECRET` is to use an authentication on GitHub,
[create the GitHub application](https://github.com/settings/applications/new).

Configure the json renderers with the `C2C_JSON_PRETTY_PRINT` and `C2C_JSON_SORT_KEYS` environment
variables or `c2c.json.pretty_print`and `c2c.json.sort_keys` properties. Default is `false`.

Then it will redirect the user to the github authentication form if not already authenticated
(using `C2C_AUTH_GITHUB_CLIENT_ID`, `C2C_AUTH_GITHUB_CLIENT_SECRET` and `C2C_AUTH_GITHUB_SCOPE`).

Expand Down
4 changes: 0 additions & 4 deletions acceptance_tests/tests/tests/test_json.py

This file was deleted.

30 changes: 26 additions & 4 deletions c2cwsgiutils/pretty_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,24 @@
import ujson
from pyramid.renderers import JSON

from c2cwsgiutils.config_utils import config_bool, env_or_config

def fast_dumps(v: Any, **_kargv: Any) -> str:

class _FastDumps:
"""Dump the json fast using ujson."""
return ujson.dumps(v, ensure_ascii=False, indent=2, sort_keys=True, escape_forward_slashes=False)

def __init__(self, pretty_print: bool, sort_keys: bool) -> None:
self.pretty_print = pretty_print
self.sort_keys = sort_keys

def __call__(self, v: Any, **_kargv: Any) -> str:
return ujson.dumps(
v,
ensure_ascii=False,
indent=2 if self.pretty_print else 0,
sort_keys=self.sort_keys,
escape_forward_slashes=False,
)


def init(config: pyramid.config.Configurator) -> None:
Expand All @@ -19,5 +33,13 @@ def init(config: pyramid.config.Configurator) -> None:

def includeme(config: pyramid.config.Configurator) -> None:
"""Initialize json and fast_json renderer."""
config.add_renderer("json", JSON(indent=2, sort_keys=True))
config.add_renderer("fast_json", JSON(serializer=fast_dumps))

pretty_print = config_bool(
env_or_config(config, "C2C_JSON_PRETTY_PRINT", "c2c.json.pretty_print", "false")
)
sort_keys = config_bool(env_or_config(config, "C2C_JSON_SORT_KEYS", "c2c.json.sort_keys", "false"))

fast_dump = _FastDumps(pretty_print, sort_keys)

config.add_renderer("json", JSON(indent=2 if pretty_print else None, sort_keys=sort_keys))
config.add_renderer("fast_json", JSON(serializer=fast_dump))

0 comments on commit 2962a7f

Please sign in to comment.