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

2022-01-31 00:00:00 python django

问题描述

我正在编写一个 Django 中间件类,我只想在启动时执行一次,以初始化一些其他任意代码.我遵循了 sdolan 这里,但是Hello"消息输出到终端两次.例如

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')

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

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

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

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

任何想法为什么Hello world"被打印两次?谢谢.

Any ideas why "Hello world" is printed twice? Thanks.


解决方案

更新 Pykler 的回答如下:Django 1.7 现在有一个 挂钩

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

不要这样做.

您不希望一次性启动的中间件".

You don't want "middleware" for a one-time startup thing.

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

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()

相关文章