lincolnloop / python-qrcode

Python QR Code image generator
https://pypi.python.org/pypi/qrcode
Other
4.34k stars 664 forks source link

Getting "object has no attribute 'read' error." when saving PNG file FileSystemStorage #219

Open wecoon opened 3 years ago

wecoon commented 3 years ago

I am using PNG type QR code generator and it actually works fine when out of context. However, when the user sends POST request, I want to generate and save QR code to the model, but I cannot make save with FileSystemStorage. I have tried many different ways to make it work, but here is my final outcome.

In this case I get PymagingImage object and convert to PngImageFile object which I then try to save with FileSystemStorage. However, both PymagingImage object and PngImageFile object are failing in the same way: object has no attribute 'read' error.

qr = qrcode.make("123456", image_factory=PymagingImage)  # PymagingImage object
buffer = BytesIO()
qr.save(buffer, "PNG")  
qr_from_buffer = Image.open(buffer)  # PngImageFile object
fs = FileSystemStorage()
qr_img = fs.save("qrcode.png", qr_from_buffer)

I know this may not be connected to python-qrcode library, but more documentation would be beneficial. Thanks all!

heuer commented 3 years ago

Untested but try the following:

qr = qrcode.make("123456", image_factory=PymagingImage)  # PymagingImage object
buffer = BytesIO()
buffer.seek(0)
fs = FileSystemStorage()
qr_img = fs.save("qrcode.png", qr_from_buffer)

IMO the code is still wrong (i.e FileSystemStroage.save() method may not return anything but None) but it may point into the right direction.

BTW: If you've Pillow / PIL available there seems to be no reason to use the PymagingImage factory and just stay with the default factory?

Here an example which should work (uses another QR Code generator but should be easy to adapt):

https://github.com/heuer/segno/blob/master/examples/django_qrcode/

Specifically:

https://github.com/heuer/segno/blob/master/examples/django_qrcode/qrcode/models.py https://github.com/heuer/segno/blob/master/examples/django_qrcode/qrcode/views.py