flask json 中文乱码问题

1、使用 jsonify 返回 ASCII 码
使用 jsonify 返回中文时,出现如下乱码(其实是 ASCII 码)
解决:
为 flask 添加如下代码
flask_app.config['JSON_AS_ASCII'] = False
完整代码如下:
# -*- coding:utf-8 -*-
from flask import Flask
from flask_cors import CORS
from api.MovieAPI import movies
# initiate a flask object
flask_app = Flask(__name__, template_folder="templates", static_folder="static")
# support cross domain access
CORS(flask_app, supports_credentials=True)
# register blueprint
flask_app.register_blueprint(movies, url_prefix="/movies")
# don't use json as ascii
flask_app.config['JSON_AS_ASCII'] = False
# set json sort key to false
flask_app.config['JSON_SORT_KEYS'] = False
if __name__ == '__main__':
    flask_app.run(host='0.0.0.0', port=8082)
2、返回 json 中文乱码
如果发现加上 1 中的代码后,仍然出现乱码,如下:
也是由于直接使用 jsonify 返回时,没有 Content-Type 的 Headers
解决:
使用 flask response 方式返回,并且设置 Content-Type 的值
response = make_response(jsonify(json_string))
response.headers['Content-Type'] = 'application/json;charset=UTF-8'
修改前:
# -*- coding:utf-8 -*-
from flask import jsonify
from flask import make_response
def result_success(data):
    json_result = {
        "status": "200",
        "msg": "request success",
        "data": data,
    }
    return jsonify(json_result)
def result_failed(msg, code='400'):
    json_result = {
        "status": code,
        "msg": msg,
    }
    return jsonify(json_result)
修改后:
# -*- coding:utf-8 -*-
from flask import jsonify
from flask import make_response
JSON_RESPONSE_CONTENT_TYPE = 'application/json;charset=UTF-8'
def _custom_response(json_string):
    response = make_response(jsonify(json_string))
    response.headers['Content-Type'] = JSON_RESPONSE_CONTENT_TYPE
    return response
def result_success(data):
    success_dict = {
        "status": "200",
        "msg": "request success",
        "data": data
    }
    return _custom_response(success_dict)
def result_failed(msg, code='400'):
    fail_dict = {
        "status": code,
        "msg": msg,
    }
    return _custom_response(fail_dict)

You may also like...

发表评论

电子邮件地址不会被公开。 必填项已用*标注