Sunday, November 14, 2021

[SOLVED] Why is Flask not printing german umlauts?

Issue

I have a problem regarding the german umlauts when trying to print a shopping list from alexa with flask. The code I use is:

#!flask/bin/python
#IMPORT THE FLASK AND PRINTER LIBRARIES
from flask import Flask, request
from escpos.printer import Usb
#ASSIGN VARIABLES FOR THE PRINTER AND FLASK
p = Usb(0x0416, 0x5011)
app = Flask(__name__)
#CREATE 'INDEX' PAGE
@app.route('/')
def index():
    return 'Your Flask server is working!'
#CREATE "PAGE" CALLED "LIST" FOR PRINTING ALEXA SHOPPING LIST
@app.route('/list')
def list():
    #CAPTURE "GET" DATA FROM IFTTT WEBOOKS
    content = request.get_data()
    #CONVERT RAW DATA TO STRING
    str_content = str(content)
    #DIVIDE DATA INTO SEPERATE LINES
    str_split = str_content.splitlines()
    #SEPERATE WORDS BY COMMA AND ADD TO A NEW LIST
    newlist = []
    for word in str_split:
        word = word.split(',')
        newlist.extend(word)
    #REMOVE FORMATTING MARKS
    rmv_marks = [s.strip("b'") for s in newlist]
    #PRINT HEADER
    #print("Shopping List\n")
    p.text("Shopping List:\n")
    #ENUMERATE AND PRINT EACH ITEM IN LIST
    r = 1
    for x in rmv_marks:
        #print(str(r) + ". " + x + "\n")
        p.text(str(r) + ". " + x + "\n")
        r += 1
    #RETURN RESULTS
    return 'x'
#RUN THE PROGRAM
if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')`

It works but when the item on the list has an umlaut in it (e.g. SpĆ¼lmittel), it always prints it like "4. Sp\xc3\xbclmittel"

I am completely new to this so i hope someone can help me. Thank you very much!


Solution

Your content is bytes, not a string, and calling str() on it will convert it into a string, but stupidly based on the __repr__. Instead, call get_data differently:

content = request.get_data(as_text=True)

Now this will be a correctly decoded string already, you can then also get rid of your b'-stripping.



Answered By - L3viathan