"can't escape _io.BufferedRandom to binary" 尝试将图像插入 BYTEA 列时
"can't escape _io.BufferedRandom to binary" when trying to insert image to BYTEA column
所以我尝试通过 bottle 上传图像,并使用 psycopg2 将其插入 postgres BYTEA
列,但我 运行 遇到此错误:
TypeError: can't escape _io.BufferedRandom to binary
来自将插入数据的 cursor.excute()
行。
这是我的代码:
@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
我做错了什么?
我想知道问题是否出在 psycopg2.Binary
需要一个字符串但正在接收一个类似文件的对象。您是否尝试过这些方法?
binary = psycopg2.Binary(upload.file.read())
注意:您可能需要先查找文件的开头,因为(我猜)上一行的 Image.open
调用将消耗 upload.file
中的所有字节。
所以我尝试通过 bottle 上传图像,并使用 psycopg2 将其插入 postgres BYTEA
列,但我 运行 遇到此错误:
TypeError: can't escape _io.BufferedRandom to binary
来自将插入数据的 cursor.excute()
行。
这是我的代码:
@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
我做错了什么?
我想知道问题是否出在 psycopg2.Binary
需要一个字符串但正在接收一个类似文件的对象。您是否尝试过这些方法?
binary = psycopg2.Binary(upload.file.read())
注意:您可能需要先查找文件的开头,因为(我猜)上一行的 Image.open
调用将消耗 upload.file
中的所有字节。