Re: Problem with memoryview - Mailing list psycopg

From Daniele Varrazzo
Subject Re: Problem with memoryview
Date
Msg-id CA+mi_8Zy50LYof=FfO9qybeQJfoLPpUXCand8CBvapS=XoCkGg@mail.gmail.com
Whole thread Raw
In response to Problem with memoryview  ("Frank Millman" <frank@chagford.com>)
List psycopg
On Wed, Jul 31, 2013 at 3:08 PM, Frank Millman <frank@chagford.com> wrote:
>
> The following refers to Python 3.3.
>
> I know that if you create a column of type 'bytea', psycopg2 accepts a
> variety of inputs, but always returns a 'memoryview'.
>
> I would like to know if it is possible, through some customisation option,
> to tell it to return 'bytes'.

Yes: you can easily create a typecaster converting bytea data to bytes:

    def bytea2bytes(value, cur):
        m = psycopg2.BINARY(value, cur)
        if m is not None:
            return m.tobytes()

    BYTEA2BYTES = psycopg2.extensions.new_type(
        psycopg2.BINARY.values, 'BYTEA2BYTES', bytea2bytes)
    psycopg2.extensions.register_type(BYTEA2BYTES)

    cur.execute("select 'abcdef'::bytea")
    cur.fetchone()[0]    # returns b'abcdef'

This would change the behaviour of bytea globally; you can limit the
scope of the change to a single connection or cursor passing this
object as parameter to register_type(): check the function docs for
details.

Hope it helps,


-- Daniele


psycopg by date:

Previous
From: "Frank Millman"
Date:
Subject: Problem with memoryview
Next
From: "Frank Millman"
Date:
Subject: Fw: Problem with psycopg2, bytea, and memoryview