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 时执行代码?
基础教程推荐
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
