I have written a web application in flask. For one of the endpoints, I am taking som elements from request.form, making it into a formatted line using a template and format() and then writing it to a file. That works fine - as long as the contents are ascii characters. As this web applications is to handle text in Norwegian, it also must handle strings containing the letters æøåÆØÅ. In that case, the application fails out with a "UnicodeEncodeError 'ascii' codec can't encode character '\xe6' in position 78: ordinal not in range(128)" (if it contains an æ) in the line file.write(sentence)
It seems like python is trying to encode my string from ascii to unicode, but it fails as it is already UTF-8.
How can I tell python that the string I have already is UTF-8?
I have
# -*- coding: utf-8 -*-
as the first line of the file.
The relevant code (slightly abbreviated)
comment=request.form['comment']
author=request.form['author']
service=request.form['service']
host=request.form['host']
now=int(time.time())
rawsentence="[{}] ACKNOWLEDGE_SVC_PROBLEM;{};{};2;1;1;{};{}"
sentence=rawsentence.format(now,host,service,author,comment)
filename=<SOME FILE>
with open(filename,'w') as file:
file.write(sentence)