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

时间:2018-06-13 00:49:26

标签: python pymysql

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设置一个图像服务器,它就是这样     TypeError:“Response”类型的对象不是JSON可序列化的// Werkzeug Debugger

任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分: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