Search code examples
pythonasynchronousflask-restful

python flask return prior execution of reboot


for reasons I want to trigger the reboot of an raspberry pi using a REST api.

My REST api is coded in python flask like this:

from flask import Flask
from flask import jsonify
import subprocess

app = Flask(__name__)

@app.route('/api/reboot')
def reboot():
    subprocess.call("/sbin/reboot")
    return jsonify(triggered='reboot')

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

the code is working perfectly fine. But due to its a reboot the return will not be send (because the system is rebooting obviously).

Is there a way to trigger the reboot some kind of async with a delay of a couple milliseconds, that allows to return some value (in my case just an custom 'ack') prior the actual reboot?


Solution

  • Try threading.Timer:

    For example:

    from flask import Flask
    from flask import jsonify
    import subprocess
    import threading
    
    app = Flask(__name__)
    
    def _reboot():
        subprocess.call("/sbin/reboot")
    
    @app.route('/api/reboot')
    def reboot():
        t = threading.Timer(1, _reboot)
        t.start()
        return jsonify(triggered='reboot')
    
    if __name__ == '__main__':
        app.run(debug=True,host="0.0.0.0")