public inbox for [email protected]
help / color / mirror / Atom feedFrom: Daniele Varrazzo <[email protected]>
To: Hans Ginzel <[email protected]>
Cc: [email protected]
Subject: Re: register_adapter Json with custom JSONEncoder
Date: Mon, 13 Jul 2020 17:15:19 +0100
Message-ID: <CA+mi_8bPLhcgA3KgyZ-g+=oSkUBjaB-JoZD5oAKVjPqbm8iiog@mail.gmail.com> (raw)
In-Reply-To: <[email protected]>
References: <[email protected]>
Hello,
On Mon, 13 Jul 2020 at 16:49, Hans Ginzel <[email protected]> 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
view thread (3+ messages) latest in thread
reply
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients using the --to and --cc options:
reply via email
To: [email protected]
Cc: [email protected], [email protected], [email protected]
Subject: Re: register_adapter Json with custom JSONEncoder
In-Reply-To: <CA+mi_8bPLhcgA3KgyZ-g+=oSkUBjaB-JoZD5oAKVjPqbm8iiog@mail.gmail.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by agora; see mirroring instructions
for how to clone and mirror all data and code used for this inbox