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 时执行代码?


基础教程推荐
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 包装空间模型 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01