I'm trying to use this qrcode library to generate a png containing a qrcode. I want to use cherrypy to serve this image dynamically.
qrcode draws on the PIL/Pillow library, so I strongly suspect that the img in the code below works the same way as a pillow image: When I test this by printing it manually I get this.
>>> print(img)
<qrcode.image.pil.PilImage object at 0xcb2c90>
This is the code I have in cherrypy to create a qrcode dynamically. This code does not work.
@cp.expose
def qrcode(self, ticketnumber = 'unknown'):
img = qrcode.make(ticketnumber)
# this works:
# img.save('local.png')
cp.response.headers['Content-Type'] = "image/png"
buffer = StringIO.StringIO()
# this is a guess and not working
img.save(buffer, format='PNG')
buffer.seek(0)
return file_generator(buffer)
Any idea on how to return the PIL/pillow image without saving it as a static file?
After some more googling I got the syntax right. The example below works
@cp.expose
def qrcode(self, ticketnumber = 'unknown'):
img = qrcode.make(ticketnumber)
cp.response.headers['Content-Type'] = "image/png"
buffer = StringIO.StringIO()
img.save(buffer, 'PNG')
return buffer.getvalue()