我正在运行一个带有文本输入的 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/