Execute code when Django starts ONCE only?(仅在 Django 启动 ONCE 时执行代码?)
问题描述
我正在编写一个 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()
这篇关于仅在 Django 启动 ONCE 时执行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:仅在 Django 启动 ONCE 时执行代码?
基础教程推荐
- 合并具有多索引的两个数据帧 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01