I have one url, lets say /users/comments/. This page can be accessed with HTML or with JSON via ajax.
I want to cache both version of the page. How can I achieve this?
I didn't find an easy way to do it. But this is the code to manually cache and return the JSON copy of the site if the GET params ?type=json otherwise will return the html.
Top of view:
if request.GET.get('type', None) == 'json' and not request.user.is_authenticated():
#check cache
cached_page = cache.get(request.get_full_path())
if cached_page:
return HttpResponse(json.dumps(cached_page), content_type="application/json")
At the bottom of view:
if request.is_ajax():
rendered = render_to_string('lootr/deal-item.html', params, context)
if not request.user.is_authenticated():
cache.set(request.get_full_path(), rendered, 60 * 30)
return HttpResponse(json.dumps(rendered), content_type="application/json")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.