使用 Flask Pymysql 服务图像 "GET" 请求,错误显示需要一个类似字节的对象,而不是 'dict'
Using Flask Pymysql to serve image "GET" request , Error shows a bytes-like object is required, not 'dict'
def write_file(data, filename):
with open(filename, 'wb') as f:
f.write(data)
class DownloadPhoto(Resource):
def get(self,PhotoDefaultID):
connection_DownloadPhoto = pymysql.connect(host='*******',
user='root',
password='*****',
db='*******',
charset='******',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection_DownloadPhoto.cursor() as cursor_DownloadPhoto:
DownloadPhoto = "SELECT `PhotoData` FROM `app_phototable` WHERE `PhotoDefaultID` IN (%s)"
cursor_DownloadPhoto.execute(DownloadPhoto, PhotoDefaultID)
PhotoData = cursor_DownloadPhoto.fetchone()
connection_DownloadPhoto.commit()
finally:
connection_DownloadPhoto.close()
#write_file(data=PhotoData, filename="PhotoFile")
write_file(PhotoData, "PhotoFile")
return send_file(filename_or_fp= "PhotoFile", mimetype="image/jpeg"), 200
代码在这里,调试显示"TypeError: a bytes-like object is required, not 'dict' // Werkzeug Debugger"
PhotoData
实际上是dict
类型。您应该将游标结果视为带有字段的行。即
row = cursor_DownloadPhoto.fetchone()
PhotoData = row['PhotoData']
或者粗略地说:
write_file(PhotoData['PhotoData'], "PhotoFile")
def write_file(data, filename):
with open(filename, 'wb') as f:
f.write(data)
class DownloadPhoto(Resource):
def get(self,PhotoDefaultID):
connection_DownloadPhoto = pymysql.connect(host='*******',
user='root',
password='*****',
db='*******',
charset='******',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection_DownloadPhoto.cursor() as cursor_DownloadPhoto:
DownloadPhoto = "SELECT `PhotoData` FROM `app_phototable` WHERE `PhotoDefaultID` IN (%s)"
cursor_DownloadPhoto.execute(DownloadPhoto, PhotoDefaultID)
PhotoData = cursor_DownloadPhoto.fetchone()
connection_DownloadPhoto.commit()
finally:
connection_DownloadPhoto.close()
#write_file(data=PhotoData, filename="PhotoFile")
write_file(PhotoData, "PhotoFile")
return send_file(filename_or_fp= "PhotoFile", mimetype="image/jpeg"), 200
代码在这里,调试显示"TypeError: a bytes-like object is required, not 'dict' // Werkzeug Debugger"
PhotoData
实际上是dict
类型。您应该将游标结果视为带有字段的行。即
row = cursor_DownloadPhoto.fetchone()
PhotoData = row['PhotoData']
或者粗略地说:
write_file(PhotoData['PhotoData'], "PhotoFile")