gpt4 book ai didi

django - 有没有办法强制django在退出前运行一些整理代码?

转载 作者:行者123 更新时间:2023-12-04 09:45:41 26 4
gpt4 key购买 nike

我正在用 django 运行一个服务器程序,
我想在服务器运行之前和之后运行一些代码。
我可以把这些代码放在哪里?

<run function a here>
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
^C
<run function b here>

我试过 print('hello')app/__init__.py ,但发现它运行了两次。为什么?

最佳答案

我确实认为用 runserver 运行 Django 应用不是一个好主意或类似。
所以你的问题可以是“如何优雅地退出 Django 应用程序”。

通常我们在生产环境中使用 gunicorn 运行 Django或类似的 WSGI 应用程序。你不会知道它何时以及如何退出。

所以我们可能会捕捉到信号 SIG_INTSIG_TERM优雅地退出。
例如

import signal

def quit_gracefully():
print('quit')

signal.signal(signal.SIGINT, quit_gracefully)
signal.signal(signal.SIGTERM, quit_gracefully)

引用此文档: https://docs.python.org/3/library/signal.html

关于django - 有没有办法强制django在退出前运行一些整理代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62128093/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com