简体   繁体   English

Django 1.9基于类的视图单例

[英]Django 1.9 class-based view singleton

There is one problem with class-based views in Django that I can't find and easy solution. Django中基于类的视图存在一个我找不到的简单解决方案。

Let's create some class-based view: 让我们创建一些基于类的视图:

class userspaceDispatcher(View):
    def __init__(self,*args, **kwargs):
        super().__init__(*args, **kwargs)
        self.someSharedStuff = MongoConnector() # As example

    def dispatch(self, request, *args, **kwargs):
        # Some code here, it does not matter
        return dispatchResult

Then, when we will make HTTP call, that will pass to my view, every time will be created new instance of userspaceDispatcher. 然后,当我们进行HTTP调用时,它将传递到我的视图,每次都会创建一个新的userspaceDispatcher实例。 As example, to handle requests I need MongoDB connector. 例如,要处理请求,我需要MongoDB连接器。 As I can see on the profiler, initialization of connector takes 5-7ms. 正如我在探查器上看到的那样,连接器的初始化需要5到7毫秒。

So the question is - how to make view class singleton? 所以问题是-如何使视图类单身? Not to be initialized every request? 不是每个请求都初始化?

The solution to this kind of thing is the same with class based view as it is with function based ones. 基于类的视图与基于函数的视图的解决方案相同。 Define the shared value outside the view, at module level, so it will be instantiated only once per process. 在模块级别在视图外部定义共享值,因此每个进程仅实例化一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM