类型 'Response' 的对象不可 JSON 序列化


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='123',
user='123',
password='123',
db='123',
charset='123',
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(PhotoData['PhotoData'], "Photo.jpg")
return send_file("Photo.jpg", mimetype = "image/jpg"), 200

我正在尝试使用 Pymysql Flask restful 设置图像服务器,它说 TypeError: 类型为"Response"的对象不可 JSON 序列化//Werkzeug Debugger

有人可以帮忙吗?

我将在这里猜测您正在使用Flask-RESTful,并且您的Resource对象应该是该库定义的REST资源。

如果是这样,如文档中所述:

开箱即用,Flask-RESTful 仅配置为支持 JSON。我们做出这个决定是为了让 API 维护者完全控制 API 格式支持;因此,一年后,您不必支持人们使用您甚至不知道存在的API的CSV表示形式。若要向 API 添加其他媒体类型,需要在API对象上声明支持的表示形式。

大概这是你缺少的部分。

当您调用send_file时,这将返回一个flask.Response对象,该对象知道如何执行X-Sendfile(如果配置正确(或发送二进制数据(如果配置不正确(。 无论哪种方式,这都不是您可以或想要使用 JSON 编码的内容。

有关配置 Flask-RESTFUL 以处理除 JSON 之外的其他类型的响应的示例,请参阅响应格式,但我认为它会像这样简单:

@api.representation('image/jpeg')
def output_response(resp, code, headers):
# This function expects an already-created flask.Response object,
# which is a little unusual, but since that's the way you're trying
# to use it, let's take advantage of that (and hope it works; I've
# never tried it...)
resp.headers.extend(headers or {})
return resp

最新更新