-1

I am using a flask server. I want to stop a server by script.
Below is my code, but for stopping a server, I have to manually stop it. I want that after 5 seconds the server is automatically stopped.
How can I do that?

import sys

from flask import Flask, send_file, request, jsonify
import os

upload_directory="/home/einfochips/Desktop/"
file_name = "android.tar.gz"
app = Flask(__name__)

if not os.path.exists(upload_directory):
    sys.exit(0)

@app.route('/')
def list_files():
    files = []
    for filename in  os.listdir(upload_directory):
        path = os.path.join(upload_directory,filename)
        if os.path.isfile(path):
            files.append(filename)
    return jsonify(files)

def shutdown_server():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    func()

@app.route('/shutdown')
def shutdown():
    shutdown_server()
    return 'Server shutting down...'

if __name__ == '__main__':
     app.run(debug = True)
Meraj al Maksud
  • 1,528
  • 2
  • 22
  • 36
hardik gosai
  • 328
  • 3
  • 17

1 Answers1

1

You can use

 from threading import Timer
 Timer(5.0, shutdown_server).start()

Full Code

import sys

from flask import Flask, send_file, request, jsonify
import os
from threading import Timer
import requests

upload_directory="/home/einfochips/Desktop/"
file_name = "android.tar.gz"
app = Flask(__name__)

if not os.path.exists(upload_directory):
    sys.exit(0)


@app.route('/')
def list_files():
    files = []
    for filename in  os.listdir(upload_directory):
        path = os.path.join(upload_directory,filename)
        if os.path.isfile(path):
            files.append(filename)
    return jsonify(files)

def shutdown_server():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    func()

def start_shutdown_server():
    print('starting shutdown server after 5ms with api')
    requests.get('http://localhost:5000/shutdown')

@app.route('/shutdown')
def shutdown():
    print('shutdown Called')
    shutdown_server()
    return 'Server shutting down...'

if __name__ == '__main__':
    Timer(5.0, start_shutdown_server).start()
    app.run(debug = True)
arunp9294
  • 767
  • 5
  • 15