“Response”类型的对象不是JSON可序列化的

问题描述 投票:0回答:1
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

有人可以帮忙吗?

python pymysql
1个回答
0
投票

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

如果是这样,as explained in the docs

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

据推测,这是你缺少的部分。

当你调用send_file时,它会返回一个flask.Response对象,如果配置正确则知道如何执行X-Sendfile,否则返回二进制数据。无论哪种方式,这都不是你可以或想要用JSON编码的东西。

有关配置Flask-RESTFUL以处理除JSON之外的其他类型响应的示例,请参阅Response Formats,但我认为它将如此简单:

@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
© www.soinside.com 2019 - 2024. All rights reserved.