A Graceful End - Python Flask/Gunicorn后端退出钩子

本文介绍如何使用Gunicorn的钩子机制实现服务的优雅启动与停止,包括信号处理、自定义钩子函数及配置文件的应用。

基本想法

可以把注销监听、注销服务写在flask exit hook里

Flask简单场景

  1. Flask没有app.stop()方法

正常退出

  1. Python有内置的atexit库

“The atexit module defines functions to register and unregister cleanup functions. Functions thus registered are automatically executed upon normal interpreter termination. atexit runs these functions in the reverse order in which they were registered; if you register A, B, and C, at interpreter termination time, they will be run in the order C, B, A.”

指令退出CTRL+C/kill

当使用ctrl+C方式关闭服务器时可以用另一个库叫signal

题外话:可以通过注册signal.signal的形式处理一些事件,但是signal.STOP, signal.SIGKILL是没有办法拦截的(这种杀死是在内核级别实现的)。

# wsgi.py
import signal

def exit_hook(signalNumber, frame):
    print("receiving", signalNumber)
    
if __name__ == "__main__":
    signal.signal(signal.SIGINT, exit_hook)
    app.run()
    
# 可以在结束时输出
# receiving 2

# 但是如果注册signal.SIGKILL/signal.SIGSTOP则代码会报错

回答原文如下:

There is no way to handle SIGKILL

The signals SIGKILL and

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值