Python 如何在不使用 ctrl-c 的情况下停止烧瓶应用程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15562446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:25:09  来源:igfitidea点击:

How to stop flask application without using ctrl-c

pythonflaskflask-extensions

提问by vic

I want to implement a command which can stop flask application by using flask-script. I have searched the solution for a while. Because the framework doesn't provide "app.stop()" API, I am curious about how to code this. I am working on Ubuntu 12.10 and Python 2.7.3.

我想实现一个可以使用flask-script停止flask应用程序的命令。我已经搜索了一段时间的解决方案。因为框架不提供“app.stop()”API,我很好奇如何编码。我正在使用 Ubuntu 12.10 和 Python 2.7.3。

采纳答案by Zorayr

If you are just running the server on your desktop, you can expose an endpoint to kill the server (read more at Shutdown The Simple Server):

如果您只是在桌面上运行服务器,则可以公开一个端点来终止服务器(在Shutdown The Simple Server 中了解更多信息):

from flask import request
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', methods=['POST'])
def shutdown():
    shutdown_server()
    return 'Server shutting down...'

Here is another approach that is more contained:

这是另一种更包含的方法:

from multiprocessing import Process

server = Process(target=app.run)
server.start()
# ...
server.terminate()
server.join()

Let me know if this helps.

如果这有帮助,请告诉我。

回答by danvk

As others have pointed out, you can only use werkzeug.server.shutdownfrom a request handler. The only way I've found to shut down the server at another time is to send a request to yourself. For example, the /killhandler in this snippet will kill the dev server unless another request comes in during the next second:

正如其他人指出的那样,您只能werkzeug.server.shutdown从请求处理程序中使用。我发现在其他时间关闭服务器的唯一方法是向自己发送请求。例如,/kill此代码段中的处理程序将终止开发服务器,除非下一秒有另一个请求进来:

import requests
from threading import Timer
from flask import request
import time

LAST_REQUEST_MS = 0
@app.before_request
def update_last_request_ms():
    global LAST_REQUEST_MS
    LAST_REQUEST_MS = time.time() * 1000


@app.route('/seriouslykill', methods=['POST'])
def seriouslykill():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    func()
    return "Shutting down..."


@app.route('/kill', methods=['POST'])
def kill():
    last_ms = LAST_REQUEST_MS
    def shutdown():
        if LAST_REQUEST_MS <= last_ms:  # subsequent requests abort shutdown
            requests.post('http://localhost:5000/seriouslykill')
        else:
            pass

    Timer(1.0, shutdown).start()  # wait 1 second
    return "Shutting down..."

回答by Nam G VU

My method can be proceeded via bash terminal/console

我的方法可以通过 bash 终端/控制台进行

1) run and get the process number

1)运行并获取进程号

$ ps aux | grep yourAppKeywords

2a) kill the process

2a) 终止进程

$ kill processNum

2b) kill the process if above not working

2b)如果以上不起作用,则终止进程

$ kill -9 processNum

回答by jogco

This is an old question, but googling didn't give me any insight in how to accomplish this.

这是一个老问题,但谷歌搜索并没有让我了解如何实现这一点。

Because I didn't read the code hereproperly! (Doh!) What it does is to raise a RuntimeErrorwhen there is no werkzeug.server.shutdownin the request.environ...

因为我没有正确阅读这里代码!(DOH!)它的作用是提高RuntimeError时,有没有werkzeug.server.shutdownrequest.environ...

So what we can do when there is no requestis to raise a RuntimeError

所以当没有时我们能做的request就是提出一个RuntimeError

def shutdown():
    raise RuntimeError("Server going down")

and catch that when app.run()returns:

并在app.run()返回时捕捉到:

...
try:
    app.run(host="0.0.0.0")
except RuntimeError, msg:
    if str(msg) == "Server going down":
        pass # or whatever you want to do when the server goes down
    else:
        # appropriate handling/logging of other runtime errors
# and so on
...

No need to send yourself a request.

无需向自己发送请求。

回答by Ruben Decrop

I did it slightly different using threads

我使用线程做的略有不同

from werkzeug.serving import make_server

class ServerThread(threading.Thread):

    def __init__(self, app):
        threading.Thread.__init__(self)
        self.srv = make_server('127.0.0.1', 5000, app)
        self.ctx = app.app_context()
        self.ctx.push()

    def run(self):
        log.info('starting server')
        self.srv.serve_forever()

    def shutdown(self):
        self.srv.shutdown()

def start_server():
    global server
    app = flask.Flask('myapp')
    ...
    server = ServerThread(app)
    server.start()
    log.info('server started')

def stop_server():
    global server
    server.shutdown()

I use it to do end to end tests for restful api, where I can send requests using the python requests library.

我用它来对 restful api 进行端到端测试,在那里我可以使用 python requests 库发送请求。

回答by R J

This is a bit old thread, but if someone experimenting, learning, or testing basic flask app, started from a script that runs in the background, the quickest way to stop it is to kill the process running on the port you are running your app on. Note: I am aware the author is looking for a way not to kill or stop the app. But this may help someone who is learning.

这是一个有点旧的线程,但是如果有人从后台运行的脚本开始试验、学习或测试基本的 Flask 应用程序,停止它的最快方法是终止在您运行应用程序的端口上运行的进程在。注意:我知道作者正在寻找一种不杀死或停止应用程序的方法。但这可能对正在学习的人有所帮助。

sudo netstat -tulnp | grep :5001

You'll get something like this.

你会得到这样的东西。

tcp 0 0 0.0.0.0:5001 0.0.0.0:* LISTEN 28834/python

tcp 0 0 0.0.0.0:5001 0.0.0.0:* 听 28834/python

To stop the app, kill the process

要停止应用程序,请终止进程

sudo kill 28834

回答by Sumit Bajaj

For Windows, it is quite easy to stop/kill flask server -

对于 Windows,停止/杀死 Flask 服务器非常容易 -

  1. Goto Task Manager
  2. Find flask.exe
  3. Select and End process
  1. 转到任务管理器
  2. 找到烧瓶.exe
  3. 选择并结束进程

回答by Alex

You can use method bellow

您可以使用下面的方法

app.do_teardown_appcontext()

回答by kip2

If you're working on the CLI and only have one flask app/process running (or rather, you just want want to kill anyflask process running on your system), you can kill it with:

如果您正在使用 CLI 并且只运行一个 Flask 应用程序/进程(或者更确切地说,您只想终止系统上运行的任何Flask 进程),您可以使用以下命令终止它:

kill $(pgrep -f flask)

kill $(pgrep -f flask)

回答by Deg

You don't have to press "CTRL-C", but you can provide an endpoint which does it for you:

您不必按“CTRL-C”,但您可以提供一个为您执行此操作的端点:

from flask import Flask, jsonify, request
import json, os, signal

@app.route('/stopServer', methods=['GET'])
def stopServer():
    os.kill(os.getpid(), signal.SIGINT)
    return jsonify({ "success": True, "message": "Server is shutting down..." })

Now you can just call this endpoint to gracefully shutdown the server:

现在你可以调用这个端点来优雅地关闭服务器:

curl localhost:5000/stopServer