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

  • 0
    Good afternoon!

    There is a PaymentChecker class, its creation takes quite a long 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 actual question is how to cache it correctly 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(...):
                   ....


    Thank you in advance :-)
    Django Anonymous, Dec 27, 2019

  • 1 Answers
  • 0
    If at the compilation stage there is enough data to create, this 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 the 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 :)
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!