简体   繁体   中英

Populate a Flask image from Matplotlib

Here's what I am trying to do.

I have a template called "index.html", somewhere containing an image like this:

<img class="img-circle" src="/image?imei={{i}}&s={{s}}">

In flask, I have a handler for the /image url like this:

@app.route('/image', methods=['GET'])
def image():
    imei = request.args.get('imei') 
    dt = request.args.get('s').split("/") 
    return someFunction(imei,dt) <-- SHOULD THIS BE RETURN?

someFunction generates a Matplotlib image. The image looks correct while saved to disk, but I do not know how to "return" this image so that it renders correctly in image.html. Here is what I am currently doing following ( Python Matplotlib to smtplib ):

def somefunction(imei,dt)
    ...
    #plt is valid and can be saved to disk
    plt.tight_layout()
    #plt.show() <-- this looks correct when uncommented

    buf = io.BytesIO()
    plt.savefig(buf, format = 'png')
    buf.seek(0)
    print(buf.read()) <-- prints a bunch of stuff
    return buf.read() <-- this does not work

The aformentioned "bunch of stuff" looks like this:

b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x03 \x00\x00\x02X\x08\x06\x00\x00\x00

How do I do this? Currently Flask bombs with: ValueError: View function did not return a response

Try:

@app.route("/image")
def image():
    ret = # create raw image data w/matplotlib

    resp = Response(response=ret,
                    status=200,
                    mimetype="image/png")

    return resp

I have not tried this, it might not work.

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