Django - How do I access request object outside views?

时间:2017-04-06 17:13:18

标签: django request views

I have a file named utilities.py in the app directory, which contains small utility functions specific to my app. I will be calling these function from views.py. The problem is some utility function requires access to request object.

Is there any way to use request object outside the view without passing it as argument to the utility function ?

1 个答案:

答案 0 :(得分:0)

我制作了自定义/lib/foo/boar.js类,该类在Django中间件中初始化,并将链接放置到Context对象上。

关于以下两个重要事项:

  1. request类必须继承Context,以防止在多个线程中运行应用程序时请求泄漏。
  2. threading.local设为单例。我为此使用了Singleton元类。

因此,您只需在代码的任何部分进行此调用就可以获取Django请求对象:

Context