无法从 Python-Flask 上的输入接收 Unicode 值



我的示例 Python 脚本是这样的:

# -*- coding: utf-8 -*-
from flask import *
app = Flask(__name__)

@app.route('/', methods=['GET','POST'])
def checkName():
if request.method=='POST':
namekh = request.form['KhmerName']
print "Khmer name is ",namekh
if isinstance(namekh.encode('utf8'), unicode):
return render_template('hello.html', Name=namekh)
else:
namekh = 'Please enter khmer character only'
return render_template('hello.html', Name=namekh)

return render_template('hello.html')
if __name__ == '__main__':
app.run(debug=True)

从上面的脚本中,我尝试在提交时从表单元素名称KhmerName接收输入值,并检查它是否是 Unicode 字符。然后我将其发送到我的 html 标记hello.html显示。

html 看起来像这样:

{% if Name %}
<p>Hello, {{Name}} wellcome to mysite</p>
{% endif %}
<form class="form-horizontal" action='' method='POST'>
<div class="form-group">
<label for="KhmerName" class="col-sm-2 control-label">Khmer Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="KhmerName" name="KhmerName" placeholder="KhmerName">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>

但是,我的问题是,如果KhmerName是一种无字符,它是否工作正常,但它是 Unicode 字符,它会返回错误消息

UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-4: character maps to <undefined>
Traceback (most recent call last)
File "C:Python27libsite-packagesflaskapp.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "C:Python27libsite-packagesflaskapp.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "C:Python27libsite-packagesflaskapp.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:Python27libsite-packagesflaskapp.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "C:Python27libsite-packagesflaskapp.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:Python27libsite-packagesflaskapp.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:Python27libsite-packagesflaskapp.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "C:Python27libsite-packagesflaskapp.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "F:pythoncheck Unicodehello.py", line 12, in hello_world
print "Khmer name is ",namekh
File "C:Python27libencodingscp437.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-4: character maps to <undefined>

我在这里检查 Unicode 所做的是使用isinstance(namekh.encode('utf8'), unicode),所以它应该工作(返回 true(,因为如果输入值是 unicode 字符,namekh的类型已经是unicode类型。然而,我不知道为什么它会返回像上面这样的错误。

我有一个演示项目的测试。request.form["key"]的变量返回类型是unicode。因此,您无需将其转换为unicodestr使用decode。我还在演示项目上测试សួរស្តីរ,它可以打印。从您提供的代码。您可能只想允许使用高棉字符。我认为您使用正则表达式来测试输入。

REGEX_KHMER = u"[u1780-u17ddu17e0-u17e9u17f0-u17f9]+"
if re.match(REGEX_KHMER, namekh):
return correctly
else:
return enter khmer character only

编辑- 我之前的回答很糟糕。我正在改进它

សួរស្តីរ中的字符不能用单个字节表示,并且在python2字符串中是一个字节序列,您将遇到问题。

事实是,你可以解码成 unicode(在 python-2.x 中str是一个字节序列,你必须将其解码为 unicode,你在 python-3.x 中不需要它,因为字符串已经在 unicode 中,它们是str对象 - 字符序列,或者如果我能说字符抽象(,你只能编码成字节而不解码它

实际上,正如@stamaimer所建议的那样,从烧瓶中的request.form["key"]返回的数据是unicode所以你不需要编码它,事实上你不能,这就是你得到错误的原因。

你可以这样做:

isinstance(namekh,unicode)

无需编码。但这也没有意义,因为你已经有了 unicode。

我希望这能帮助你。

@app.route('/', methods=['GET','POST'])
def checkName():
if request.method=='POST':
namekh = request.form['KhmerName']
print "Khmer name is ",namekh
# The default namekh is unicode
if isinstance(namekh, unicode):
return render_template('hello.html', Name=namekh)
else:
namekh = 'Please enter khmer character only'
return render_template('hello.html', Name=namekh)

return render_template('hello.html')

如下

最新更新