Search code examples
python-2.7flasktextareaarabic

How to solve UnicodeEncode proplem


I use python2.7 with flask framework , i try to get the text from textarea in Html page and store it at a text file , it works successfully if the text written in English , but i need to make it work for Arabic text . i try many solution without result !!

what can i do !! this is the code .

       # -*- coding: cp1256-*-
       from flask import Flask, render_template, request
       import jinja2
       import os
       import codecs 
       os.chdir("C:\Python27")
       app = Flask(__name__)
       @app.route("/")
       def hello():
           return render_template("razan.html")
       @app.route('/submit', methods=['POST'])
       def submit_textarea():
           text = request.form.get("text")
           with open('aaa.txt','w') as outfile:
                outfile.write(text)
           return  render_template("razan.html")

       if __name__ == "__main__":
              app.run(host="0.0.0.0", port=int("3000"), debug=True)

and this is the HTML Code :

  <!DOCTYPE html>
  <html>
  <head>
  <meta charset="cp1256">
  </head>
  <body>

  <h1>Enter some text</h1>
  <form action="submit" id="textform" method="post" >
     <textarea name="text" type="text"> مرحبا </textarea>
     <button type="submit" value="submit_textarea()" > submt</button> 
  </form>
  </body>
  </html>

and it give me this error :

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


Solution

  • Read the file in unicode

    import codecs
    outfile = codecs.open('aaa.txt', 'w', 'utf-8')
    outfile.write(text)