Reputation: 76
How can I solve this?
How add cache header in HttpResponse? Now the file is not cached.This module is needed to search and return photos or gifs.
Just need to cache the file on the client in the browser.
my views:
def q(request, slug, name):
arr = {
'png': 'image/png',
'jpg': 'image/jpeg',
'gif': 'image/gif',
}
current_time = datetime.datetime.utcnow()
image_data = open(path, 'rb').read()
response = HttpResponse(image_data, content_type = arr[extension])
last_modified = current_time - datetime.timedelta(days=1)
response['Last-Modified'] = last_modified.strftime('%a, %d %b %Y %H:%M:%S GMT')
response['Expires'] = current_time + datetime.timedelta(days=30)
response['Cache-Control'] = 'public, max-age=315360000'
response['Date'] = current_time
response['Cache-Control'] = 'no-cache'
return response
Response headers:
Cache-Control: no-cache, max-age=900
Content-Length: 767365
Content-Type: image/gif
Date: 2019-05-06 20:21:25.134589
Expires: 2019-06-05 20:21:25.134589
Last-Modified: Sun, 05 May 2019 20:21:25 GMT
Server: WSGIServer/0.2 CPython/3.7.3
X-Frame-Options: SAMEORIGIN
Request headers:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
Cache-Control: max-age=0
Connection: keep-alive
Host: localhost:8088
If-Modified-Since: Sun, 05 May 2019 20:21:14 GMT
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36
Upvotes: 1
Views: 1641
Reputation: 1
Put the following in your code to get Cache_Control
added to your settings
from django.views.decorators.cache import cache_control
@cache_control(private=True, max_age=3153600)
def q(request, slug, name):
....
Upvotes: 0
Reputation: 76
After I set MIDDLEWARE, it all worked.
MIDDLEWARE = [
'django.middleware.http.ConditionalGetMiddleware',
]
Upvotes: 1
Reputation: 20692
Django uses middleware to set the cache headers of your responses. In order to override what the middleware is settings, you should use the @cache_control
view decorator or the patch_cache_control
function, as described here so that the middleware knows this takes precedence and doesn't override the headers:
from django.views.decorators.cache import cache_control
@cache_control(public=True, max_age=315360000)
def q(request, slug, name):
...
Upvotes: 1