简体   繁体   中英

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.

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. As example, to handle requests I need MongoDB connector. As I can see on the profiler, initialization of connector takes 5-7ms.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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