简体   繁体   中英

Object of type 'Response' is not JSON serializable

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

I`m trying to set a image server using Pymysql Flask restful and it says that TypeError: Object of type 'Response' is not JSON serializable // Werkzeug Debugger

Anybody Can Help?

I'm going to go out on a limb here and guess that you're using Flask-RESTful, and that your Resource object is supposed to be a REST resource, as defined by that library.

If so, as explained in the docs :

Out of the box, Flask-RESTful is only configured to support JSON. We made this decision to give API maintainers full control of over API format support; so a year down the road you don't have to support people using the CSV representation of your API you didn't even know existed. To add additional mediatypes to your API, you'll need to declare your supported representations on the Api object.

Presumably this is the part you're missing.

When you call send_file , that returns a flask.Response object that knows how to do an X-Sendfile if configured properly or send binary data if not. Either way, that's not something you can, or want to, encode with JSON.

See Response Formats for examples of configuring Flask-RESTFUL to handle other kinds of responses besides JSON, but I think it'll be as simple as this:

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM