问题:仅在Django启动一次时执行代码?

我正在编写一个Django中间件类,该类只想在启动时执行一次,以初始化一些其他人工代码。我遵循了sdolan 在此处发布的非常好的解决方案,但是“ 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”?谢谢。

I’m writing a Django Middleware class that I want to execute only once at startup, to initialise some other arbritary code. I’ve followed the very nice solution posted by sdolan here, but the “Hello” message is output to the terminal twice. E.g.

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

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

and in my Django settings file, I’ve got the class included in the MIDDLEWARE_CLASSES list.

But when I run Django using runserver and request a page, I get in the terminal

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

Any ideas why “Hello world” is printed twice? Thanks.


回答 0

从以下Pykler的答案进行更新:Django 1.7现在对此具有钩子


不要这样

您不希望一次性使用“中间件”。

您想在顶层执行代码urls.py。该模块将被导入并执行一次。

urls.py

from django.confs.urls.defaults import *
from my_app import one_time_startup

urlpatterns = ...

one_time_startup()

Update from Pykler’s answer below: Django 1.7 now has a hook for this


Don’t do it this way.

You don’t want “middleware” for a one-time startup thing.

You want to execute code in the top-level urls.py. That module is imported and executed once.

urls.py

from django.confs.urls.defaults import *
from my_app import one_time_startup

urlpatterns = ...

one_time_startup()

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。