A
A
Alexander Savchuk2015-05-25 18:40:36
Django
Alexander Savchuk, 2015-05-25 18:40:36

How to properly cache an object (not a model) in Django?

Good afternoon!
There is a PaymentChecker class, its creation takes quite a lot of time, and it is not profitable to create it in each request, since it does not change from request to request, that is, you need something like a singleton. Therefore, the question is how to properly cache it or organize it as a singleton.
It would be correct to put it in a separate file, for example, utils.py of the following form:

# utils.py

class PaymentChecker(object):
    ....

payment_checker = PaymentChecker(<some constant args>)

# views.py
import utils

class CheckPayment(View):
    def get(...):
           if utils.payment_checker.check(...):
               ....

Thanks in advance :-)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vadim Shandrinov, 2015-05-25
@MrLinch

If there is enough data to create at the compilation stage, then it is possible.
Another option is to make a lazy getter, something like

_payment_checker = None
def get_payment_checker():
     global _payment_checker
     if _payment_checker is None:
          _payment_checker =  PaymentChecker(<some constant args>)
     return _payment_checker

or the same through a static class method
class PaymentChecker(object):
    __instance = None
    @classmethod
    def get_checker(cls):
         if cls.__instance is None:
               cls.__instance =  cls(<some constant args>)
         return cls.__instance

The second option is preferable - it's easier to develop :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question