首页 > 解决方案 > 将 python 输出发送到烧瓶服务器

问题描述

我正在尝试在 python 中绘制一些东西,然后在烧瓶服务器中显示输出。简单的例子:

这是python代码:

from PIL import Image
from flask import Flask, render_template
import datetime
app = Flask(__name__)
@app.route("/")
def hello():
    img = Image.new('RGB', (60, 30), color = 'red')
    templateData = {
      'title' : 'HELLO!',
      'image': img
      }
    return render_template('index.html', **templateData)
if __name__ == "__main__":
   app.run(host='0.0.0.0', port=80, debug=True)

这是html文件代码:

<!DOCTYPE html>
   <head>
      <title>{{title}}</title>
   </head>
   <body>
      <h1>Hello, World!</h1>
      <img src="{{image}}" alt="not working">
   </body>
</html>

当我运行代码时,它没有在页面中显示输出有什么办法吗?

标签: pythonhtmlflask

解决方案


我不太了解 PIL 库生成图像的内部机制,但我可以建议一个简单的方法:

假设你有这样的结构:

root/
    static/
        img/
    templates/
        index.html
    your_script.py

你的脚本.py

from PIL import Image
from flask import Flask, render_template
import datetime

app = Flask(__name__)
@app.route("/")
def hello():
    img = Image.new('RGB', (60, 30), color = 'red')
    img.save('static/img/red.png')
    templateData = {
        'title' : 'HELLO!',
        'image': 'red'
    }
    return render_template('index.html', **templateData)

if __name__ == "__main__":
   app.run(host='0.0.0.0', port=80, debug=True)

索引.html

<!DOCTYPE html>
    <head>
        <title>{{title}}</title>
    </head>
    <body>
        <h1>Hello, World!</h1>
        <img src="{{url_for('static', filename='img/')}}{{image}}.png">
    </body>
</html>

推荐阅读