gpt4 book ai didi

python - 仅在 Django 启动 ONCE 时执行代码?

转载 作者:IT老高 更新时间:2023-10-28 12:25:23 25 4
gpt4 key购买 nike

我正在编写一个 Django 中间件类,我只想在启动时执行一次,以初始化一些其他任意代码。我遵循了 sdolan here 发布的非常好的解决方案,但“Hello”消息输出到终端两次。例如

from django.core.exceptions import MiddlewareNotUsed
from django.conf import settings

class StartupMiddleware(object):
def __init__(self):
print "Hello world"
raise MiddlewareNotUsed('Startup complete')

在我的 Django 设置文件中,我将类包含在 MIDDLEWARE_CLASSES 列表中。

但是当我使用 runserver 运行 Django 并请求页面时,我进入了终端

Django version 1.3, using settings 'config.server'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Hello world
[22/Jul/2011 15:54:36] "GET / HTTP/1.1" 200 698
Hello world
[22/Jul/2011 15:54:36] "GET /static/css/base.css HTTP/1.1" 200 0

任何想法为什么“Hello world”被打印两次?谢谢。

最佳答案

更新:Django 1.7 现在有一个 hook for this

文件:myapp/apps.py

from django.apps import AppConfig
class MyAppConfig(AppConfig):
name = 'myapp'
verbose_name = "My Application"
def ready(self):
pass # startup code here

文件:myapp/__init__.py

default_app_config = 'myapp.apps.MyAppConfig'

对于 Django < 1.7

第一个答案似乎不再起作用,urls.py 在第一次请求时加载。

最近的工作是将启动代码放在您的任何一个 INSTALLED_APPS init.py 中,例如myapp/__init__.py

def startup():
pass # load a big thing

startup()

当使用 ./manage.py runserver ...这会执行两次,但那是因为 runserver 有一些技巧可以首先验证模型等 ...正常部署甚至当 runserver auto重新加载,这只会执行一次。

关于python - 仅在 Django 启动 ONCE 时执行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6791911/

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