Ctrl-c를 사용하지 않고 플라스크 응용 프로그램을 중지하는 방법
플라스크 스크립트를 사용하여 플라스크 응용 프로그램을 중지 할 수있는 명령을 구현하고 싶습니다. 나는 잠시 동안 해결책을 찾았습니다. 프레임 워크는 "app.stop ()"API를 제공하지 않기 때문에 코드 작성 방법이 궁금합니다. Ubuntu 12.10 및 Python 2.7.3에서 작업 중입니다.
데스크톱에서 서버를 실행하는 경우 엔드 포인트를 노출하여 서버를 종료 할 수 있습니다 (자세한 내용은 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...'
다음은 더 포함 된 또 다른 접근 방식입니다.
from multiprocessing import Process
server = Process(target=app.run)
server.start()
# ...
server.terminate()
server.join()
이것이 도움이되는지 알려주세요.
실을 사용하여 약간 다르게했습니다
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()
파이썬 요청 라이브러리를 사용하여 요청을 보낼 수있는 안정적인 API에 대한 종단 간 테스트를 수행하는 데 사용합니다.
내 방법은 bash 터미널 / 콘솔을 통해 진행할 수 있습니다.
1) 실행하고 프로세스 번호 얻기
$ ps aux | grep yourAppKeywords
2a) 프로세스 종료
$ kill processNum
2b) kill the process if above not working
$ kill -9 processNum
As others have pointed out, you can only use werkzeug.server.shutdown
from 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 /kill
handler in this snippet will kill the dev server unless another request comes in during the next second:
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..."
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 here properly! (Doh!) What it does is to raise a RuntimeError
when there is no werkzeug.server.shutdown
in the request.environ
...
So what we can do when there is no request
is to raise a RuntimeError
def shutdown():
raise RuntimeError("Server going down")
and catch that when app.run()
returns:
...
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.
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.
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
To stop the app, kill the process
sudo kill 28834
You can use method bellow
app.do_teardown_appcontext()
For Windows, it is quite easy to stop/kill flask server -
- Goto Task Manager
- Find flask.exe
- Select and End process
참고URL : https://stackoverflow.com/questions/15562446/how-to-stop-flask-application-without-using-ctrl-c
'programing' 카테고리의 다른 글
HTTParty로 오류를 어떻게 처리 할 수 있습니까? (0) | 2020.11.01 |
---|---|
select2에서 AJAX로 태그 지정 (0) | 2020.11.01 |
Entity Framework 6 GUID를 기본 키로 : 'Id'열, 'FileStore'테이블에 NULL 값을 삽입 할 수 없습니다. (0) | 2020.11.01 |
명령 줄에 액세스하지 않고 실행중인 Apache 버전을 어떻게 찾습니까? (0) | 2020.10.31 |
스택 또는 힙에서 C ++의 글로벌 메모리 관리? (0) | 2020.10.31 |