In my app I want to serve a PNG image generated from a numpy array sent via the POST method, so in the app I came up with there are two routes - the one that serves HTML with the <img />
tag and the other that generates it. Unfortunately the app times out after sending the POST request and a 500 error is displayed instead of the image:
from flask import Flask, request, url_for, Response
import requests
from matplotlib import pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg
import numpy as np
import json
from io import BytesIO
app = Flask(__name__)
@app.route('/img/show')
def show_html():
data = np.random.rand(80).reshape((2, 40))
img = BytesIO(requests.post(request.scheme + '://' + request.host + url_for('img_gen'), json=json.dumps(data.astype(float).tolist())).raw.read())
return '<img src="{}" />'.format(img.getvalue())
@app.route('/img/gen', methods=['POST'])
def img_gen():
data = np.array(json.loads(request.get_json()))
fig = plt.figure()
plt.plot(data[0, :], c='b')
plt.plot(data[1, :]*-1, c='r')
plt.grid()
png = BytesIO()
FigureCanvasAgg(fig).print_png(png)
plt.close(fig)
return Response(png.getvalue(), mimetype='image/png')
if __name__ == '__main__':
app.run()
I checked that the array is correctly passed to and received by the /img/gen
route, but it seems like the app gets stuck at or before the return
line. Gunicorn v3 does not print any error message except for the WORKER TIMEOUT
. I would greatly appreciate if someone pointed the cause of this problem to me.