Re: Reporting UnicodeEncodeError info on arbitrary data sent to PG with psycopg3

From: Daniele Varrazzo <daniele(dot)varrazzo(at)gmail(dot)com>
To: "Karl O(dot) Pinc" <kop(at)karlpinc(dot)com>
Cc: "psycopg(at)postgresql(dot)org" <psycopg(at)postgresql(dot)org>
Subject: Re: Reporting UnicodeEncodeError info on arbitrary data sent to PG with psycopg3
Date: 2024-02-14 14:30:33
Message-ID: CA+mi_8Y0jzEZA+3kCnTtWCS8cvWTUFcD=0J+ihiamh=y8GvOxg@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: psycopg

Hello Karl,

On Wed, 14 Feb 2024 at 02:37, Karl O. Pinc <kop(at)karlpinc(dot)com> wrote:

> This does not work. What is wrong with what I'm doing
> and how do I do what I want? (And how am I supposed to
> know why this does not work and what works?) I call the
> dumper because I want to rely on psycopg3's mechanisms
> and not have to query the server for its encoding
> and figure out the PG->Python encoding mappings myself.

Keep in mind that you are playing with objects that are somewhat
internal, so it wouldn't be impossible that these interfaces will
change in the future. It's not planned at the moment and it wouldn't
happen in a minor version anyway.

However, the main problem I see there is that
`conn.adapters.get_dumper()` returns a class. If you want a dumper you
must instantiate it. The following works as you expect:

>>> conn.execute("set client_encoding to 'latin1'")
>>> dumper = conn.adapters.get_dumper(str,
psycopg.adapt.PyFormat.TEXT)(str, conn)
>>> dumper.dump('€')
...
UnicodeEncodeError: 'latin-1' codec can't encode character
'\u20ac' in position 0: ordinal not in range(256)

Note however that if you just want to know the Python codec you can
find it in `conn.info.encoding`
(https://www.psycopg.org/psycopg3/docs/api/objects.html#psycopg.ConnectionInfo.encoding)

>>> conn.info.encoding
'iso8859-1'
>>> "€".encode(conn.info.encoding)
...
UnicodeEncodeError: 'latin-1' codec can't encode character
'\u20ac' in position 0: ordinal not in range(256)

Hope this helps

-- Daniele

In response to

Responses

Browse psycopg by date

  From Date Subject
Next Message Karl O. Pinc 2024-02-14 15:42:03 Re: Reporting UnicodeEncodeError info on arbitrary data sent to PG with psycopg3
Previous Message Karl O. Pinc 2024-02-14 01:37:32 Reporting UnicodeEncodeError info on arbitrary data sent to PG with psycopg3