wainuiomata / sambal

Experimental web admin for Samba and Active Directory domains
https://wainuiomata.com
GNU General Public License v3.0
1 stars 1 forks source link

Jinja2 filter |tojson should use Sambal adapters for datatypes #56

Closed robvdl closed 8 months ago

robvdl commented 8 months ago

Things like Dn, MessageElement etc. will work fine when producing just json using renderer="json"

But when using Jinja2 and using it's builting |tojson filter, we want it to use the same defaults.

This looks like it: https://stackoverflow.com/questions/61544343/how-to-make-tojson-filter-in-jinja2-output-unicode-instead-of-escape-sequences

In particular this comment:

env = jinja2.Environment()
env.policies['json.dumps_kwargs']['ensure_ascii'] = False
robvdl commented 8 months ago

Looking at the Jinja2 source code, we have two settings to play with:

dumps = policies["json.dumps_function"]
kwargs = policies["json.dumps_kwargs"]
robvdl commented 8 months ago

As for the jinja2.Environment() object, I would look at pyramid-jinja2 how to override that.

https://docs.pylonsproject.org/projects/pyramid_jinja2/en/latest/api.html#pyramid_jinja2.get_jinja2_environment

robvdl commented 8 months ago

I think I need to stop using add_adapter and just subclass the JSONEncoder.

I was reading at how add_adapter works internally, it ends up calling __call__ on the renderer, which eventually ends up calling default = _get_default and this then gets passed as the default=default kwarg to json.dumps. It ends up passing a request object as well but we don't need that.

The issue with the |tojson Jinja2 filter is I can't easily share this code, so I end up having to write it twice. Once using adapters, and once by subclassing the encoder.

Because of this, I am choosing to subclass the encoder, even though the preference is to use add_adapter.

I just don't want this double-up code, I'd rather only declare things once.