python - Ascii 编解码器无法编码字符

标签 python unicode flask ascii

我正在运行一个带有文本输入的 Flask Web 服务,但现在我遇到一个问题,文本输入有时包含不包含在 ASCII 字符集中的字符(错误示例:“(错误:未提供文本)'ascii'编解码器无法对位置 20 中的字符 u'\u2019' 进行编码)")

我的 Flask Web 服务代码看起来(有点)像这样:

class Classname(Resource):
    def __init__(self):
       self.reqparse = reqparse.RequestParser()
       self.reqparse.add_argument('text', type=str, required=True, help='Error: no text provided')
       super(Classname,self).__init__()

    def post(self):
       args = self.reqparse.parse_args()
       text = args['text']
       return resultOfSomeFunction(text)

我已经尝试将 ascii 字符串转换为 unicode,但这不起作用(错误:“unicode”对象不可调用)。我还尝试添加:

text = re.sub(r'[^\x00-\x7f]',r' ',text)

规则之后

text = args['text']

但这也给了我同样的错误(“ascii”编解码器无法编码字符)。

我该如何解决这个问题?

最佳答案

您是否尝试过从 self.reqparse.add_argument('text', type=str, required=True, help='Error: no textprovided') 中删除 type=str

Note:

The default argument type is a unicode string. This will be str in python3 and unicode in python2

来源:http://flask-restful-cn.readthedocs.org/en/0.3.4/reqparse.html

关于python - Ascii 编解码器无法编码字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33653559/

相关文章:

upload - ImportError : No module named flask. ext.uploads.UploadSet

python - 在 Docker 镜像中克隆 git 存储库失败

python - 需要一个 python 脚本来搜索 sql 文件集合中的特定关键字,返回找到每个关键字的索引

python - 获取所有希腊语 unicode 字符的列表

windows - 如何在 Linux 中使用 POSIX 方法从文件中读取 Unicode-16 字符串?

在 Systemd 中使用 Gunicorn 套接字的 Centos 7 上的 Nginx 权限问题

javascript - 使用 Flask 在 iOS 上进行 JSON POST

python - 使用 Google App Engine 和 Jinja2 的 TemplateNotFound : index. html

python - NumPy odeint 输出额外变量

mysql 字符集,我可以在 python 中执行转换吗?