3

I am trying to use flask-restful api, and as a returning value the code should returning a list of json datas. However, when contents in json is non-ascii character like (èòsèèò) the returning value

This is the a sample code:

#! /usr/bin/env python
# coding: utf-8

from flask import Flask, Response
from flask_restful import Resource, Api
import json

app = Flask(__name__)
# Create the API
API = Api(app)



@app.route('/')
def hello_world():
    return Response('Here, with Response it works well: höne')

class APICLASS(Resource):
    """

    """
    def get(self, id):
        return [
        {
        "hey": 11,
        "test": "höne"
        }], 200


API.add_resource(APICLASS, '/<string:id>')

if __name__ == '__main__':
    app.run(debug=True)

But when I check the result on localhost, I see the following output:

[
        {
        "hey": 11,
        "test": "h\u00f6ne"
        }]
ElisaFo
  • 130
  • 13
  • To be honest I didn't understand your question! I am retrieving all the data as a list of _Json_ from the database. However right before passing to _flask restful Api_ it is ok. Even, if I pass a single string like `"höne"` instead of list of _json_, I still would see the problem – ElisaFo Apr 29 '19 at 14:36
  • I don't know how it doesn't transfer it properly. When I try to return a non-ascii character directly without any list by using the above code, I get the same error! – ElisaFo Apr 29 '19 at 15:25

1 Answers1

8

Apparently, it is related to this bug. I'm not sure if there are any side effects but this might help:

# ...
app = Flask(__name__)
# Create the API
API = Api(app)

API.app.config['RESTFUL_JSON'] = {
    'ensure_ascii': False
}

@app.route('/')
# Rest of your code
spadarian
  • 1,604
  • 10
  • 14
  • 1
    Thanks it works. It works with just adding the last part of your code: `api.app.config['RESTFUL_JSON'] = { 'ensure_ascii': False` } – ElisaFo Apr 29 '19 at 13:20
  • Could you also tell me how can I add your code as a class, and call it in other classes? As presented in your provided link – ElisaFo Apr 29 '19 at 15:23