Flask-RESTX - Arabic text in response body

351 Views Asked by At

I'm running a rest api with swagger, flask-restx

However, my problem is that in the swagger UI (http://127.0.0.1:5000/ ?) when testing out the endpoint, arabic text in the response body is returned as excaped characters \\u0645\\u0635\\u0646\\u0648\\u0639 \\u0645\ Same problem when using postman

The problem does not occur when using sublime text request package or when simply entering the URL in the browser (I have a jsonify extension)

Here is a shortened version of my code

@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())

When I call the endpoint products it works fine, but when I call product it does not.

1

There are 1 best solutions below

0
On

Define the following function in 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")

Sample usage:

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') )

Result:

مصنوع م
Citroën
déjà vu
 Printer Icon