问题描述
我正在运行带有flask-restx的rest api
但是,我的问题是,在测试端点时,在大张旗鼓的UI(http://127.0.0.1:5000/?)中,响应正文中的阿拉伯语文本以大写字符\\u0645\\u0635\\u0646\\u0648\\u0639 \\u0645\
的形式返回。
使用邮递员时出现同样的问题
使用高级文本请求包或仅在浏览器中输入URL(我具有jsonify扩展名)时,不会发生此问题
这是我的代码的简化版本
@app.route('/products')
def products():
# logic with database
return JSONEncoder().encode(products)
name_space = api.namespace('product',description='Product API')
@name_space.route("/")
class ProductClass(Resource):
def get(self):
return make_response(products())
当我呼叫端点products
时,它可以正常工作,但是当我呼叫product
时,它却不能。
解决方法
在Python中定义以下功能:
def inverse_repr(a_string):
a_string = repr(a_string)
a_string = a_string.replace('\\\\','\\')
# encode/decode stuff
return a_string.strip("'").encode().decode("unicode-escape")
样品用量:
print( inverse_repr('\\u0645\\u0635\\u0646\\u0648\\u0639 \\u0645') )
print( inverse_repr('\\x43\\x69\\x74\\x72\\x6f\\xeb\\x6e') )
print( inverse_repr('d\\xE9j\\xE0 vu') )
print( inverse_repr('\\U0001F5B6 Printer Icon') )
结果:
مصنوع م
Citroën
déjà vu
? Printer Icon