Вы можете использовать функцию колбы send_file
, которая принимает либо имя файла, либо файлоподобный объект, чтобы создать маршрут для изображения и использовать другой маршрут, чтобы показать изображение внутри шаблона.
Вы можете сохранить график на графике так:
nx.draw(G)
with open(filepath, 'wb') as img:
plt.savefig(img)
plt.clf()
В качестве более полного примера вот что я сделал некоторое время назад, приложение для колб, которое отображает полный график n-th
с маршрутом /<int:nodes>
:
server.py
from flask import Flask, render_template, send_file
import matplotlib.pyplot as plt
from io import BytesIO
import networkx as nx
app = Flask(__name__)
@app.route('/<int:nodes>')
def ind(nodes):
return render_template("image.html", nodes=nodes)
@app.route('/graph/<int:nodes>')
def graph(nodes):
G = nx.complete_graph(nodes)
nx.draw(G)
img = BytesIO() # file-like object for the image
plt.savefig(img) # save the image to the stream
img.seek(0) # writing moved the cursor to the end of the file, reset
plt.clf() # clear pyplot
return send_file(img, mimetype='image/png')
if __name__ == '__main__':
app.run(debug=True)
шаблоны / image.html
<html>
<head>
<title>Graph</title>
</head>
<body>
<h1>Graph</h1>
<img
src="{{ url_for('graph', nodes=nodes) }}"
alt="Complete Graph with {{ nodes }} nodes"
height="200"
/>
</body>
</html>