简体   繁体   中英

How to return more than just one value in Flask?

I have a flask application. For this question I use the given hello world example to make it easier. As seen below after the execution of a task it shows "Hello World!" on 0.0.0.0:5000 .

Actually my application does quite a big task and I would like to print a short message after every step of the task like a log. For example after doing step 1 I want it to print step 1 done then it goes on to step 2. Is that somehow possible?

I am well aware of the fact that I can not refresh the page because that would restart my task. When something goes wrong I have to go to the logs of my server to find out what happend but I would like to kind of expose those information.

from flask import Flask

app = Flask(__name__)

port = int(os.getenv("PORT"))

@app.route('/')
def hello_world():
    do some tasks
    return 'Hello, World!'

if __name__ == '__main__':
   app.run(host='0.0.0.0', port=port)

Using a separate socket connection updating the progress is the most practical way using for example: https://flask-socketio.readthedocs.io/en/latest/ If you are hosting a lot of these request I would recommend setting up a MQTT broker and use https://github.com/MrLeeh/Flask-MQTT

The other option is to create a separate listener path with a work ID parameter of the work being done and keep polling that for updates with a Ajax call from the page

@app.route('/status/<int:jobid>')
def check_status(jobid):
    return StatusOfTheWorkBeingCarriedOut(jobid)

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