gevent(py)wsgi正常关闭 [英] gevent (py)wsgi graceful shutdown

查看:284
本文介绍了gevent(py)wsgi正常关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道(通过搜索和检查gevent的源代码)正常关闭基于WSGI的gevent服务器的唯一方法是:

The only way I know (from searching and inspecting the gevent's source) to gracefully shutdown a gevent WSGI based server is:

server = gevent.wsgi.WSGIServer(('', 80), someWSGIApp)
def shutdown():
  print('Shutting down ...')
  server.stop(timeout=60)
  exit(signal.SIGTERM)
gevent.signal(signal.SIGTERM, shutdown)
server.serve_forever()

现在,优美的意思是等待所有greenlet自行终止.因此,例如,如果他们仍在处理请求,则可以正确完成它们.

Now, what I mean by graceful is to wait for all the greenlets to terminate by themselves. So for instance if they're still serving requests, they can finish them up properly.

问题是,使用上面的貌似正确的代码,服务器确实确实在等待max. 60秒,但所有TCP连接在收到SIGTERM后立即终止.但是,Greenlets会继续做自己的工作(例如睡觉),直到它们完成或超时为止.

Problem is, with the above seemingly correct code, the server does indeed wait for max. of 60 seconds, but all the TCP connections are terminated immediately upon receiving SIGTERM. Greenlets however continue doing what they were (e.g. sleeping) until either they finish or the timeout occurs.

有什么想法吗?

推荐答案

您可以通过在一个线程中运行服务器,然后在另一个线程中关闭服务器来解决该问题.下面的代码在Python 3.7中运行.

You can solve the problem by running the server in one thread and shut it down in another. The code below is running in Python 3.7.

from gevent.pywsgi import WSGIServer
import signal
import threading

# define your app here
app = ...

server_address = ("localhost", 4000)


class WebServer(threading.Thread):
    def __init__(self):
        super().__init__()

    def run(self):
        global server
        server = WSGIServer(server_address, app)
        server.serve_forever()


def shutdown(num, info):
    print(f'Shutting down website server...\n'
          f'{num} {info}')
    server.stop()
    server.close()


if __name__ == "__main__":
    server = None
    WebServer().start()

    signal.signal(signal.SIGINT, shutdown)

这篇关于gevent(py)wsgi正常关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆