简体   繁体   中英

send python output to flask server

I'm trying to draw something in the python and then display the output in the flask server. simple example:

this is the python code:

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)

this is the html file code:

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

when i run the code, it is not showing the output in the page is there any way to do it?

I do not know well the internal mechanism of generation of images by the PIL library, but I can suggest a simple approach:

Suppose you have this structure:

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

your_script.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)

index.html

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM