Want to speed up your API responses? Might as well look into caching. Provided the response wont change every time with a new page refresh, we can just save the response and return it to the user instead of having to put soo much load on the database itself. The code here is:
from django.views.decorators.cache import cache_page
from django.utils.functional import wraps
def cache_per_user(timeout):
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(request, *args, **kwargs):
user_id = ‘not_auth’
if request.user.is_authenticated:
user_id = request.user.id
return cache_page(timeout, key_prefix="_user_{}_".format(user_id))(view_func)(request, *args, **kwargs)
return _wrapped_view
return decorator
Now that you have written your own custom cache, import it into your views and use it as a simple decorator like:
@cache_per_user(3600)
where ‘3600’ is the timeout in seconds