ubuntu 18.04 - Python 3.6.7 - psycopg2 2.7.6.- Postgresql 10.8
在bytea字段中保存图像时,会导致psycopg2出现以下错误(Spyder3中的测试代码):
连接到PostgreSQL时出现错误无法将JpegImageFile转义为二进制
如果我在Eclipse-pydev中运行相同的代码,报告的错误是类似的,但给出了类型信息:TypeError: can't escape to binary
-Can你明白问题是与Postgresql有关还是与psycopg2有关?-How可以使我们成功地将图像文件保存在Postgresql?-May中,这是库错误吗?
在Postregsql中保存图像需要使用bytea字段类型。该图像需要在十六进制格式或字节转义格式的编码的。如果我们读取一个url图片, it by psycopg2 in Bynary,但是当最后执行INSERT查询时,函数返回上述错误。以下代码可以重现该错误:
import psycopg2
import urllib.request
from PIL import Image
from io import BytesIO
import requests
url = 'https://upload.wikimedia.org/wikipedia/commons/thumb/a/a3/Eq_it-na_pizza-margherita_sep2005_sml.jpg/440px-Eq_it-na_pizza-margherita_sep2005_sml.jpg'
#image = Image.open(urllib.request.urlopen(url))
response = requests.get(url)
image = Image.open(BytesIO(response.content))
#test image correctly read
width, height = image.size
print (width,height)
try:
connection = psycopg2.connect(user = "user",
password = "odoo12", host = "127.0.0.1",
port = "5432",database = "dbname")
cursor = connection.cursor()
query = """INSERT INTO foods (fo_image, fo_url)
VALUES (%s,%s) ;"""
byteImage = psycopg2.Binary(image)
data = (byteImage, url )
cursor.execute(query,data)
except (Exception, psycopg2.Error) as error :
print ("Error while connecting to PostgreSQL", error)
finally:
#closing database connection.
if(connection):
cursor.close()
connection.close()
检查图像的大小并显示正确的信息。改变不同的图像显示相同的结果。哪里出了问题?如何修复它?_
发布于 2019-05-17 06:35:57
我不认为你需要在Python3中使用psycopg2.Binary
。
我怀疑您不是在调用connection.commit()
来提交事务。
https://stackoverflow.com/questions/56175410
复制相似问题