How to Serve QR Images from Memory with Django


TL; DR: I used SpooledTemporaryFile with FileResponse to server generated QR images directly from memory, no disk IO involved.

Please see my code sample with notes:

# this is views.py in a typical Django project

# dependencies
from django.http import HttpResponse, FileResponse
import qrcode
from qrcode.image.pure import PyPNGImage
from tempfile import SpooledTemporaryFile

def qr(request, keyword):
  domain_name = request.META['HTTP_HOST']
  
  # to generate a QR code in PNG format
  img = qrcode.make(f'https://{domain_name}/{keyword}', image_factory=PyPNGImage)
  
  # a virtual file in memory
  in_memory_file = SpooledTemporaryFile()
  
  # save the image into the virtual file
  img.save(in_memory_file)
  
  # this step is important
  # seek(0) rewinds the pointer of this IO stream to its beginning which was set to its end from previous step
  in_memory_file.seek(0)
  
  # return the image as qr.png in an HTTP response
  return FileResponse(in_memory_file, filename='qr.png')

🙂