Problem with psycopg2, bytea, and memoryview

Antoine Pitrou solipsis at pitrou.net
Wed Jul 31 05:50:37 EDT 2013


Frank Millman <frank <at> chagford.com> writes:
> 
> I have some binary data (a gzipped xml object) that I want to store in a 
> database. For PostgreSQL I use a column with datatype 'bytea', which is 
> their recommended way of storing binary strings.
> 
> I use psycopg2 to access the database. It returns binary data in the form of 
> a python 'memoryview'.
> 
[...]
> 
> Using MS SQL Server and pyodbc, it returns a byte string, not a memoryview, 
> and it does compare equal with the original.
> 
> I can hack my program to use tobytes(), but it would add complication, and 
> it would be database-specific. I would prefer a cleaner solution.

Just cast the result to bytes (`bytes(row[1])`). It will work both with bytes
and memoryview objcts.

Regards

Antoine.





More information about the Python-list mailing list