0

I have converted image to base64 string using following code. Based on this string want to create Image object and want to add some headers to it like ,

Expires: Mon, 29 Apr 2013 21:44:55 GMT Cache-Control: max-age=0, no-cache, no-store ,

and print that object as a image to the django template.

Is it possible in django ?

Here is the code to convert img from url to base64.

import mimetypes
import urllib2
def stringifyImage(url):
    tmpdir = 'tmp'
    mmtp = mimetypes.guess_type(url, strict=True)
    if not mmtp[0]:
        return False

    ext = mimetypes.guess_extension(mmtp[0])
    f = open(tmpdir+'tmp'+ext,'wb')
    f.write(urllib2.urlopen(url).read())
    f.close()
    img = open(tmpdir+'tmp'+ext, "rb").read().encode("base64").replace("\n","")
    return img
Nishant Nawarkhede
  • 6,960
  • 9
  • 49
  • 67

1 Answers1

0

Seeing your question I see:

  1. You have the image which you want to pass it to Django template
  2. Set the expires, no-cache related headers

I feel you can achieve it by sending the image object as a HttpResponse and then add decorators for the headers you are looking for.

You can look into the following links:

  1. A decorator that adds additional headers to disable caching
  2. A decorator that helps for adding expiry date
  3. Then once you have the required headers set, you can send the HttpResponse for the image which is requested by the tempate:

Inside the views.py

from PIL import Image
from django.views.decorators.cache import cache_page

@cache_page(60 * 15)    #cached for 15 minutes
def getImg(request):
    #Getting the image url

    #image is the Image object of PIL

    # serialize to HTTP response http://effbot.org/zone/django-pil.htm
    response = HttpResponse(mimetype="image/png")
    image.save(response, "PNG")
    return response
  1. Then in your img tag, use the template for src (considering the url.py has the view identifier):

    <img src='{% url getImg %}' >

Further read: Django's Cache Framework

Community
  • 1
  • 1
Nagaraj Tantri
  • 4,572
  • 10
  • 47
  • 72