Python2.7+Flask框架下阿拉伯文本UnicodeEncode问题求助
Hey Razan, I’ve run into this exact encoding headache with Python 2.7 and non-Latin scripts before—let’s break down what’s going wrong and how to fix it. The core issue is Python 2’s split between bytes and Unicode strings, plus mismatched encodings across your stack (HTML → Flask → file storage). Here’s a step-by-step solution:
1. Update Your Script File Encoding
Your current code uses cp1256 for the script file, but UTF-8 is the universal standard that supports Arabic (and every other language) without compatibility gaps. Update the top of your .py file to:
# -*- coding: utf-8 -*-
2. Ensure HTML Sends UTF-8 Data
First, make sure your HTML template tells browsers to encode form data in UTF-8. Add this meta tag inside the <head> section of your template:
<meta charset="UTF-8">
This guarantees the Arabic text from your <textarea> is sent to Flask in UTF-8 format, which avoids garbled byte conversion early on.
3. Properly Decode & Store Request Data in Flask
In Python 2, request.form returns byte strings (not Unicode), so you need to decode the submitted text to Unicode before working with it. Here’s the adjusted route code:
from flask import Flask, render_template, request import codecs import os os.chdir("C:\\Python27") # Use double backslashes for Windows file paths app = Flask(__name__) @app.route("/", methods=["GET", "POST"]) # Add POST to handle form submissions def hello(): if request.method == "POST": # Get text from textarea and decode UTF-8 bytes to Unicode arabic_text = request.form.get("your_textarea_name").decode("utf-8") # Write Unicode text to file with proper encoding with codecs.open("arabic_output.txt", "w", encoding="utf-8") as f: f.write(arabic_text) return "Arabic text saved successfully!" return render_template("your_template.html") # Replace with your actual template name
Key checks here:
- Replace
"your_textarea_name"with thenameattribute of your<textarea>in the HTML. - Using
codecs.openwithencoding="utf-8"ensures Unicode text is converted to valid UTF-8 bytes when saved to the file. - The
methods=["GET", "POST"]flag lets the route accept form submissions.
4. Validate Your HTML Form Setup
Double-check your form doesn’t override the encoding. It should look something like this:
<form method="POST" action="/"> <textarea name="your_textarea_name" rows="5" cols="50"></textarea> <br> <button type="submit">Save Text</button> </form>
No need for accept-charset if you already have the UTF-8 meta tag—modern browsers default to UTF-8 for form data.
Quick Debug Tip
If you still see issues, print type(arabic_text) after decoding. It should show <type 'unicode'>, not <type 'str'> (which is a byte string in Python 2). This confirms you’re working with actual text characters, not raw bytes.
内容的提问来源于stack exchange,提问作者Razan Balatiah

