只有Django启动ONCE才执行代码? [英] Execute code when Django starts ONCE only?

查看:200
本文介绍了只有Django启动ONCE才执行代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Django Middleware类,我只想在启动时执行一次,以初始化一些其他的编码。我遵循了由sdolan发布的非常好的解决方案这里,但是Hello消息被输出到终端两次。来自django.core.exceptions导入的

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $

class StartupMiddleware(object):
def __init __(self):
printHello world
raise MiddlewareNotUsed('Startup complete')
/ pre>

在我的Django设置文件中,我已经将类包含在 MIDDLEWARE_CLASSES 列表中。 / p>

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

 code> Django版本1.3,使用设置'config.server'
开发服务器运行在http://127.0.0.1:8000/
使用CONTROL-C退出服务器。
Hello world
[22 / Jul / 2011 15:54:36]GET / HTTP / 1.1200 698
Hello world
[22 / Jul / 2011 15:54 :36]GET /static/css/base.css HTTP / 1.1200 0

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

解决方案

不要这样做。



你不想要中间件一次启动的东西。



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



urls.py


$ b $来自django.confs.urls.defaults导入的

$ b从my_app import a_time_startup

urlpatterns = ...

one_time_startup()


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.

解决方案

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

这篇关于只有Django启动ONCE才执行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆