Why is Flask not printing german umlauts?

0

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

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More