How do I properly cache an object (not a model) in Django?
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
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
if _payment_checker is None:
_payment_checker = PaymentChecker(<some constant args>)
or the same through the static class method
__instance = None
if cls.__instance is None:
cls.__instance = cls(<some constant args>)
the second option is preferable - it's easier to develop :)Anonymous
To place the code, please use CodePen or similar tool. Thanks you!