Django:django启动时只调用一次方法 [英] Django : Call a method only once when the django starts up
问题描述
我可以从数据库获取数据,但问题是如何调用initialize方法。这个应该只会被调用一次。
试图查找其他页面,但找不到答案。
代码目前看起来像这样::
def get_latest_dbx(request,....):
#从数据库中获取数据
def get_latest_x请求):
get_latest_dbx(request,x,...)
def startup(request):
get_latest_x(request)
有些人建议( Django仅在ONCE之后执行代码?)调用顶级urls.py中的初始化(这看起来不寻常,因为urls.py应该处理url模式)。编写中间件有另一种解决方法:在哪里放置Django启动代码?
但我相信大多数人都在等待票得到解决。 / p>
更新:
由于OP已经更新了这个问题,似乎中间件的方式可能会更好,因为他实际上在启动时需要一个请求
对象。所有启动代码都可以放在自定义中间件的 process_request
方法中,其中请求
对象在第一个参数中可用。在这些启动代码执行后,可能会设置一些标志,以避免稍后重新运行(提升 MiddlewareNotUsed
异常仅适用于 __ init __
,它没有收到请求
参数)。
BTW,OP的要求看起来有点奇怪。一方面,当Django启动时,他需要初始化一些变量,另一方面,他需要在初始化中使用 request
对象。但是当Django启动时,根本就没有传入的请求。即使有一个,它没有什么意义。我想他实际需要的可能是为每个会话或用户做一些初始化。
I want to initialize some variables (from the database) when Django starts.
I am able to get the data from the database but the problem is how should I call the initialize method . And this should be only called once.
Tried looking in other Pages, but couldn't find an answer to it.
The code currently looks something like this ::
def get_latest_dbx(request, ....):
#get the data from database
def get_latest_x(request):
get_latest_dbx(request,x,...)
def startup(request):
get_latest_x(request)
Some people suggest( Execute code when Django starts ONCE only? ) call that initialization in the top-level urls.py(which looks unusual, for urls.py is supposed to handle url pattern). There is another workaround by writing a middleware: Where to put Django startup code? But I believe most of people are waiting for the ticket to be solved.
UPDATE:
Since the OP has updated the question, it seems the middleware way may be better, for he actually needs a request
object in startup. All startup codes could be put in a custom middleware's process_request
method, where request
object is available in the first argument. After these startup codes execute, some flag may be set to avoid rerunning them later(raising MiddlewareNotUsed
exception only works in __init__
, which doesn't receive a request
argument).
BTW, OP's requirement looks a bit weird. On one hand, he needs to initialize some variables when Django starts, on the other hand, he need request
object in the initialization. But when Django starts, there may be no incoming request at all. Even if there is one, it doesn't make much sense. I guess what he actually needs may be doing some initialization for each session or user.
这篇关于Django:django启动时只调用一次方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!