简体   繁体   中英

Deserialize postgres bytea in Python

I'm trying to read a column in a postgres table that is stored as a bytea.

Following the methods outlined here ( How to read and insert bytea columns using psycopg2? )

I'm trying to convert a memoryview into the 'real' value. However this returns the following error message:

c = db.cursor()
c.execute("""select bytea_column from table
where bytearray_id_ = 'abc123';""")
mview = c.fetchone()

TypeError: 'memoryview' object cannot be interpreted as an integer

I've also tried reading the value into a pandas dataframe, and then trying to deserialize the value received there. However this just returns a series and it doesn't seem like much can be done with it.

dataframe = pd.read_sql_query(bytea_query, db_string)

dataframe["bytea"]
0    [b'\xac', b'\xed', b'\x00', b'\x05', b's', b'r...

Is there an alternative way to do this?

The solution ended up being relatively straightforward:

data = dataframe["bytes_"][0]
bytearray = bytearray(data)
bytearray

This returns a bytearray object containing the correct deserialized data from postgres.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM