Search code examples
pythonutf-8python-3.7non-ascii-charactersflask-restful

My flask app doesn't return non-ascii character properly


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"
        }]

Solution

  • 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