基本上,您需要创建一个用作静态图像的视图,然后从该路由中获取图像 url。
我没有你包含的库,所以我将使用matplotlib 和numpy 来模拟你试图尝试的内容。这对您来说不是一个完整的解决方案(它以最简单的工作方式使用 2 个视图和 1 个简单模板),但您应该能够理解所有让您完成页面的基本技术。
我有一些 cmets 和指南,我认为代码本身几乎是不言自明的。
好的,这是视图main.py:
from flask import Flask, render_template, request, send_file
import matplotlib.pyplot as plt
import numpy as np
from StringIO import StringIO
app = Flask(__name__)
@app.route('/plot/')
def plot():
try:
# try to get the query string like ?width=xxx&height=xxx
height = int(request.args.get('height'))
width = int(request.args.get('width'))
except ValueError:
# if height, width not available, set a default value
height, width = 100, 100
# I randomly generate the plot which just based on H x W
# you should be able to generate yours from your library
to_draw = np.random.randint(0, 255, (height, width))
img = plt.imshow(to_draw)
# you can convert the graph to arrays and save to memory
imgIO = StringIO()
img.write_png(imgIO, noscale=True) # save to memory
imgIO.seek(0)
# and send that image as file as static file of url
# like... /plot/?width=100&height=100
return send_file(imgIO, mimetype='image/png')
# this is the main page with the form and user input
@app.route('/', methods=['GET', 'POST'])
def index():
# set the default values
height, width = 100, 100
# handle whenever user make a form POST (click the Plot button)
if request.method == 'POST':
try:
# use this to get the values of user input from the form
height = int(request.form['height'])
width = int(request.form['width'])
except ValueError:
pass
# and pass the context back to the template
# if no form is POST, default values will be sent to template
return render_template('index.html', height=height, width=width)
if __name__ == '__main__':
app.debug = True
app.run()
templates/index.html中的模板:
<html>
<head>
<title>Micro Plot!</title>
</head>
<body>
<h1>Interactive Plot</h1>
<form action="/" name="plot" method="POST">
<p><input type="text" name='height' value="{{ height }}" /></p>
<p><input type="text" name='width' value="{{ width }}" /></p>
<p><input type="submit" value="Plot Now!"></p>
</form>
<img src="{{ url_for('plot', height=height, width=width) }}" />
</body>
</html>
诀窍是设置图像 src 向 url 发送 GET 请求,然后 Flask 的 /plot/ 视图呈现内存中的图像并作为静态反馈。
重点说明:
url_for 然后会像/plot/?width=xxx&height=xxx 一样动态生成 src。
要从视图中的 url 获取 querystring,请使用 request.args.get('KeyName')。
一旦你的情节准备好了,用 Python StringIO 模块将它保存在内存中,并使用 Flask 的 send_file 作为静态内容。
您应该阅读并了解更多关于 Flask 和 HTML 的信息,如果不充分了解这些东西如何协同工作,您就无法构建出真正令人惊叹的东西。
我希望这可以帮助您了解底层技术,祝您好运!