1

trying to make a program in python that request the following api and return with a QRcode. this QRcode i get back is actually formatted text and i need to put that into a PNG file. this is my code

import requests
import os


user = os.getlogin()
print("Hi there, " + user)
text = input("Enter a word: ")
request = requests.get("https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" + text)
response = request.text

file = open("output.txt", "w")
file.write(response)
file.close()
print("\nDone !")

put i get this error when trying to save it as png or text:

'charmap' codec can't encode character '\ufffd' in position 0: character maps to <undefined>

2 Answers 2

2

Not sure what you mean when you say:

this QRcode i get back is actually formatted text and i need to put that into a PNG file

The response you get is not plain-text. You can check the response headers' Content-Type field and confirm that it is an image (image/png). All you have to do is write the response bytes to a file:

def main():

    import requests

    text = "test"
    url = f"https://api.qrserver.com/v1/create-qr-code/?size=150x150&data={text}"

    response = requests.get(url)
    response.raise_for_status()

    with open("output.png", "wb") as file:
        file.write(response.content)

    print("Done.")

    return 0


if __name__ == "__main__":
    import sys
    sys.exit(main())
Sign up to request clarification or add additional context in comments.

3 Comments

oh, never heard of .content ! let me try it out i get back to you...
yup the issue here was that i used .text instead of .content . thanks ! i'll mark it as correct.
Glad it's working! Also be aware of the write-bytes (wb) mode when writing to the file.
1

If you want to save response as png you can do it like this

import requests
import os

user = os.getlogin()
print("Hi there, " + user)
text = input("Enter a word: ")
request = requests.get(
    "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" + text)

open(text+'.png', 'wb').write(request.content)

print("Done !")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.