我想在一段时间后重定向到url

时间:2019-10-11 05:20:20

标签: python python-3.x flask

我正在使用Flask服务器。我想通过脚本停止服务器。
下面是我的代码,但是要停止服务器,我必须手动停止它。我希望服务器在5秒后自动停止。
我该怎么办?

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)

1 个答案:

答案 0 :(得分:1)

您可以使用

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

完整代码

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)