Search code examples
pythonpostgresqlpsycopg2unpackiterable-unpacking

How to fix "can't adapt error" when saving binary data using python psycopg2


I ran across this bug three times today in one of our projects. Putting the problem and solution online for future reference.

impost psycopg2

con = connect(...)

def save(long_blob):
     cur = con.cursor() 
     long_data = struct.unpack('<L', long_blob)
     cur.execute('insert into blob_records( blob_data ) values (%s)', [long_data])

This will fail with the error "can't adapt" from psycopg2.


Solution

  • The problem is struct.unpack returns a tuple result, even if there is only one value to unpack. You need to make sure you grab the first item from the tuple, even if there is only one item. Otherwise psycopg2 sql argument parsing will fail trying to convert the tuple to a string giving the "can't adapt" error message.

    impost psycopg2
    
    con = connect(...)
    
    def save(long_blob):
         cur = con.cursor() 
         long_data = struct.unpack('<L', long_blob)
    
         # grab the first result of the tuple
         long_data = long_data[0]
    
         cur.execute('insert into blob_records( blob_data ) values (%s)', [long_data])