Re: register_adapter Json with custom JSONEncoder - Mailing list psycopg

From Daniele Varrazzo
Subject Re: register_adapter Json with custom JSONEncoder
Date
Msg-id CA+mi_8bPLhcgA3KgyZ-g+=oSkUBjaB-JoZD5oAKVjPqbm8iiog@mail.gmail.com
Whole thread Raw
In response to register_adapter Json with custom JSONEncoder  (Hans Ginzel <hans@matfyz.cz>)
Responses Re: register_adapter Json with custom JSONEncoder
List psycopg
Hello,

On Mon, 13 Jul 2020 at 16:49, Hans Ginzel <hans@matfyz.cz> wrote:
[...]

> But I need to use custom JSONEncoder because of bson.ObectId type
> # https://stackoverflow.com/a/16586277/2556118

This doc page has more examples:
https://www.psycopg.org/docs/extras.html#json-adaptation


> There is a parameter dumps in Json.__init__(self, adapted, dumps=None),
> but how to set it when used with register_adapter(),

You can use a partial function for instance, of the like of: `lambda
obj: Json(obj, dumps=mydumps)`.


> https://www.psycopg.org/docs/extensions.html#psycopg2.extensions.register_adapter?
>
> Should I write myself the whole Json class?

No, if you really want you can subclass the one we provide and only
override `_dumps()`: the one psycopg2 provides consists in pretty
much:

    class Json(object):
        def __init__(self, adapted, dumps=None):
            self.adapted = adapted
           self._dumps = dumps or json.dumps

        def dumps(self, obj):
            return self._dumps(obj)

so you can either create your instances using a wrapper in
register_adapter, or subclass the _dumps() method of the class: as you
can see it is equivalent. I guess the first method is better as you
don't need to care about the implementation of the `Json` class.


-- Daniele



psycopg by date:

Previous
From: Hans Ginzel
Date:
Subject: register_adapter Json with custom JSONEncoder
Next
From: Hans Ginzel
Date:
Subject: Re: register_adapter Json with custom JSONEncoder