【问题标题】:Embedding an html page inside Flask在 Flask 中嵌入一个 html 页面
【发布时间】:2015-01-09 22:13:08
【问题描述】:

好的,我已经成功创建了一个显示散景图像的烧瓶页面——现在我必须以某种方式将其放入模板中

https://gist.github.com/cloudformdesign/a0c5f2e8558ea3b60f0a

我想要创建一个带有几个文本框的网页,用户可以在其中键入他们想要绘制的数据,并将在文本框下方绘制图表。用户可以选择他们想要绘制的新数据,并且图表会更新。

我很不擅长用 html 编码,所以我很不擅长创建模板。我该怎么做这样的事情?

感谢@elyase,我创建了自己的示例

https://github.com/bokeh/bokeh/tree/master/examples/embed/simple

这是一个在 html 页面中嵌入散景页面的非常简单的示例。 @elyase 给出的示例很有帮助,但实际上并不能与 python3 一起使用(我无法导入或安装 pyaudio)。对于我要问的问题,这也过于复杂。上面的要点给出了一个非常简单的答案,只有两个文件,都在同一个目录中。非常感谢!

【问题讨论】:

  • 好的,那么除了模板之外,您的 Flask 代码在哪里?
  • 没有!这就是获取散景图所需的全部代码
  • 看看this example
  • @GarrettLinux,嗯,好的。所以你有一个库来绘制图形并想在模板中显示图像?
  • elyase,这正是我想要的!不幸的是它没有用,但我把它作为一个学习例子并写了我自己的。非常感谢!

标签: python html python-3.x flask


【解决方案1】:

基本上,您需要创建一个用作静态图像的视图,然后从该路由中获取图像 url。

我没有你包含的库,所以我将使用matplotlibnumpy 来模拟你试图尝试的内容。这对您来说不是一个完整的解决方案(它以最简单的工作方式使用 2 个视图和 1 个简单模板),但您应该能够理解所有让您完成页面的基本技术。 我有一些 cmets 和指南,我认为代码本身几乎是不言自明的。

好的,这是视图ma​​in.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&amp;height=xxx 一样动态生成 src。

要从视图中的 url 获取 querystring,请使用 request.args.get('KeyName')

一旦你的情节准备好了,用 Python StringIO 模块将它保存在内存中,并使用 Flask 的 send_file 作为静态内容。

您应该阅读并了解更多关于 FlaskHTML 的信息,如果不充分了解这些东西如何协同工作,您就无法构建出真正令人惊叹的东西。

我希望这可以帮助您了解底层技术,祝您好运!

【讨论】:

  • 谢谢,但这并不是我想要的答案。我想使用 Bokeh,因为它提供动态图——而不仅仅是图像!感谢您的回答,我将继续与嵌入图一起学习烧瓶,这应该会有所帮助。我想我也会使用 send_File 向人们发送 csv 数据。
【解决方案2】:

我最终在 elyase 的帮助下创建了自己的答案,并且代码被拉入了散景项目的示例文件夹中。在这里查看:

https://github.com/bokeh/bokeh/tree/master/examples/embed/simple

【讨论】:

  • 找不到页面:(
  • 那是 7 年前的事了。例子来来去去。我将接受的答案更改为上述答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
  • 2013-11-30
  • 2021-09-10
  • 1970-01-01
  • 1970-01-01
  • 2019-04-04
  • 2015-03-24
相关资源
最近更新 更多