I have a pyramid view that needs to generate a qr code and return it as an image to the user. I want to avoid storing the image, I want to just generate it, send it and forget about it.
The first thing I tried was something like this:
oRet = StringIO.StringIO()
oQR = pyqrcode.create('yo mamma')
oQR.svg(oRet, scale=8)
return Response(body = oRet.read(), content_type="image/svg")
But this generates an svg file that can't be opened.
Looking a little closer:
oRet = StringIO.StringIO()
oQR = pyqrcode.create('yo mamma')
oQR.eps(oRet, scale=8)
with open('test.eps','w') as f: # cant display image in file
f.write(oRet.read())
with open('test2.eps','w') as f: # image file works fine
oQR.eps(f, scale=8)
oQR.svg(oRet, scale=8)
with open('test.svg','w') as f: # cant display image in file
f.write(oRet.read())
with open('test2.svg','w') as f: # image file works fine
oQR.svg(f, scale=8)
oQR.png(oRet)
with open('test.png','w') as f: # cant display image
f.write(oRet.read())
with open('test2.png','w') as f: #works
oQR.png(f) # works
with open('test3.png','w') as f:
f.write(oQR.png_as_base64_str()) #doesn't work
So my question is: How do I return a newly generated qr code as a pyramid response without storing it on disk? I don't mind too much what format the image is in
we have a winner:
oRet = StringIO.StringIO()
oQR = pyqrcode.create('yo mamma')
oQR.png(oRet, scale=8)
oResp = Response(body = oRet.getvalue(), content_type="image/png",content_disposition='attachment; filename="yummy.png"')
return oResp
The trick was to use oRet.getvalue()
instead or oRet.read()