Reputation: 43
>>> def qrcodegenerate(nbr):
... res = requests.get("https://chart.googleapis.com/chart?cht=qr&chs=300x330&choe=UTF-8&chl="+str(nbr))
... print(res.url)
... data =res.text
... with open("C:\wamp\www\Paymentapi\qrcode\qr_"+str(nbr)+'.png','w',encoding="utf-8") as f:
... f.write(data)
...
>>> qrcodegenerate(5697)
Here I am calling API to generate a QR code and I want to save into a PNG file.
The QR code is being generated, but it's not being saved correctly.
Upvotes: 1
Views: 357
Reputation: 17751
PNG files contain binary data, not UTF-8 text.
What you need to do is:
Use res.content
(binary) instead of res.text
(text).
Open the file in binary mode (wb
) instead of text mode (w
), without specifying an encoding.
The resulting code should look like this:
def qrcodegenerate(nbr):
res = requests.get('https://chart.googleapis.com/chart?cht=qr&chs=300x330&choe=UTF-8&chl=' + str(nbr))
print(res.url)
data = res.content
with open('...', 'wb') as f:
f.write(data)
Upvotes: 3