Reputation: 21932
So I'm trying to upload an image through bottle, and insert it into postgres BYTEA
column with psycopg2, but I'm running into this error:
TypeError: can't escape _io.BufferedRandom to binary
From the cursor.excute()
line that would insert the data.
Here's my code:
@route('/images', method='POST')
def upload_image():
upload = request.files.get('image')
img = Image.open(upload.file) # Pillow
binary = psycopg2.Binary(upload.file)
cursor = connection.cursor()
id = cursor.execute(
'''
INSERT INTO image (filename, data, width, height)
VALUES (%s, %s, %s, %s)
RETURNING id
''',
(upload.filename, binary, img.width, img.height)
)
return id
What am I doing wrong?
Upvotes: 3
Views: 3291
Reputation: 18168
I'm wondering whether the problem is that psycopg2.Binary
expects a string but is receiving a file-like object. Have you tried something along these lines?
binary = psycopg2.Binary(upload.file.read())
Note: You may need to seek to the beginning of the file first, since (I'm guessing) the Image.open
call on the previous line will consume all the bytes in upload.file
.
Upvotes: 2