How do I terminate a flask app that's running as a service?

后端 未结 3 1909
無奈伤痛
無奈伤痛 2020-12-19 16:51

I was able to get my flask app running as a service thanks to Is it possible to run a Python script as a service in Windows? If possible, how?, but when it comes to stopping

相关标签:
3条回答
  • 2020-12-19 17:16

    You can stop the Werkzeug web server gracefully before you stop the Win32 server. Example:

    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...'
    

    If you add this to your Flask server you can then request a graceful server shutdown by sending a POST request to /shutdown. You can use requests or urllib2 to do this. Depending on your situation you may need to protect this route against unauthorized access.

    Once the server has stopped I think you will have to no problem stopping the Win32 service.

    Note that the shutdown code above appears in this Flask snippet.

    0 讨论(0)
  • 2020-12-19 17:17

    You could also trick Flask into believing you pressed Ctrl + C:

    def shutdown_flask(self):
        from win32api import GenerateConsoleCtrlEvent
        CTRL_C_EVENT = 0
        GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0)
    

    Then simply call shutdown_flask() in your SvcStop():

    try:
        # try to exit gracefully
        self.shutdown_flask()
    except Exception as e:
        # force quit
        os._exit(0)
    

    Should shutdown_flask() fail for some reason, os._exit() makes sure your service will end (albeit with a nasty warning), by halting the interpreter.

    0 讨论(0)
  • 2020-12-19 17:29

    I recommend you use http://supervisord.org/. Actually not work in Windows, but with Cygwin you can run supervisor as in Linux, including run as service.

    For install Supervisord: https://stackoverflow.com/a/18032347/3380763

    After install you must configure the app, here an example: http://flaviusim.com/blog/Deploying-Flask-with-nginx-uWSGI-and-Supervisor/ (Is not necessary that you use Nginx with the Supervisor's configuration is enough)

    0 讨论(0)
提交回复
热议问题