0

I am making a website, and the user submits some form, where the characters are often not ascii. The code looks something like this:

@app.route('/admin', methods=['POST', 'GET'])

def admin():
    if request.method == 'POST':
        form = request.form
        article = form['article'] + '<HEAD>' + \
            f'<meta name="keywords" content=\'{form["keywords"]}\'>' + \
                f'<meta name="description" content=\'{form["desc"]}\'>'

        open(f'articles_{form["lang"]}/\
            {form["title"]} \
            .html', 'w', encoding='UTF-8').write(article)

(Line breaks are bc it used to be longer and I am yet to clear it up)

On my own computer this ran fine (windows), but on a server running linux I got this error:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 24-27: ordinal not in range(128)

Full error:

[2022-08-29 08:36:09,674] ERROR in app: Exception on /admin [POST]
Traceback (most recent call last):
  File "/home/aggaewea/virtualenv/aggamr_app/aggamxyz_v2/3.9/lib/python3.9/site-packages/flask/app.py", line 2070, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/aggaewea/virtualenv/aggamr_app/aggamxyz_v2/3.9/lib/python3.9/site-packages/flask/app.py", line 1515, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/aggaewea/virtualenv/aggamr_app/aggamxyz_v2/3.9/lib/python3.9/site-packages/flask/app.py", line 1513, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/aggaewea/virtualenv/aggamr_app/aggamxyz_v2/3.9/lib/python3.9/site-packages/flask/app.py", line 1499, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "app.py", line 168, in admin
    open(f'articles_{form["lang"]}/\
UnicodeEncodeError: 'ascii' codec can't encode characters in position 24-27: ordinal not in range(128)
sef sf
  • 117
  • 1
  • 8
  • See if this helps out: https://stackoverflow.com/questions/9942594/unicodeencodeerror-ascii-codec-cant-encode-character-u-xa0-in-position-20 – Mahmud Alptekin Aug 29 '22 at 13:24
  • @MahmudAlptekin it didnt work for me – sef sf Aug 29 '22 at 14:53
  • what did you try when you say it didn't work for you? – topsail Aug 29 '22 at 16:49
  • @topsail the u' '.join solution. the encoding solution is not really good bc I want the name of the file to be in these non-ascii characters and not look like a bunch of numbers and slashes – sef sf Aug 30 '22 at 19:37
  • That's not enough detail. How did you use the u' '.join solution? Post your code! I think I see a possible cause of what is wrong but I'm not going to really bother if you have already tried it - also I need to know if you understand what you are doing when you tried that solution from the provided link. I'd do more myself if I had a reproducible example - but I don't, so I really need to know what you are doing and not just "I tried something but it didn't work". – topsail Aug 30 '22 at 21:39

0 Answers0