0

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?

576i
  • 7,579
  • 12
  • 55
  • 92

2 Answers2

1

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()
576i
  • 7,579
  • 12
  • 55
  • 92
0

For python3: note that there is no more StringIO, refer this post

Replacing above buffer = StringIO.StringIO() with buffer = io.BytesIO() works for me.

Blindfreddy
  • 622
  • 6
  • 12