I have an non ASCII character on HTML form data and when Flask processes the character, it gives me an error like this:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 2: ordinal not in range(128) I believe that I have to decode the request form, but I can't find a way to do that.
Here's what I have:
HTML
<body> <div id="avisos"> <form action="/opcion/avisos_cadastrar/resultado" method="post"> <br> <fieldset> <legend> Aviso </legend> <center> <h3> Cadastrar </h3> </center> <br> Titulo: <input type="text" name="titulo" maxlength="32" autocomplete='off'> </input> <textarea name="aviso" id="text-area" rows="10" cols="50" maxlength="512" autocomplete='off'> </textarea> <br> <input type=submit value="enviar"> <script> var area = document.getElementById("text-area"); var message = document.getElementById("message"); var maxLength = 512; var checkLength = function() { if(area.value.length <= maxLength) { message.innerHTML = (maxLength - area.value.length) + " caracteres restantes."; } } setInterval(checkLength, 150); </script> </fieldset> </form> </div> </body> FlaskApp
@app.route("/opcion/avisos_cadastrar/resultado", methods = ['POST']) def avisos_cadastrar_resultado(): __titulo = request.form['titulo'] __aviso = request.form['aviso'] query_insert_aviso = " INSERT INTO tjs_stage.avisos (Titulo, Aviso) VALUES ('{} ', '{} ')" .format(__titulo,__aviso) cur.execute(query_insert_aviso) con.commit() return render_template('resultado.html') I tried to use something like..
__titulo = request.form['titulo'].decode("utf-8") __aviso = request.form['aviso'].decode("utf-8") ...and also...
__titulo = request.form['titulo'].decode("raw_unicode_escape") __aviso = request.form['aviso'].decode("raw_unicode_escape") ...but it didn't worked.
Maybe something is missing at my HTML or maybe at the FlaskApp, but I'm little bit lost.
Any ideas?
__tituloand__aviso? Seems more likely that its coming fromcur.execute(). Also you need to be careful when executing SQL queries with data from forms. You should escape that data to prevent any potential SQL injection attacks from malicious users.import systhenreload(sys)and finallysys.setdefaultencoding('utf-8')per this post. If it doesn't work I have another theory...sys.setdefaultencoding()work? If so, I'm sure we can find a more permanent solution.