Answer the question
In order to leave comments, you need to log in
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(...):
....
Answer the question
In order to leave comments, you need to log in
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
class PaymentChecker(object):
__instance = None
@classmethod
def get_checker(cls):
if cls.__instance is None:
cls.__instance = cls(<some constant args>)
return cls.__instance
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question