Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Flask的application/json返回类型中文编码非UTF-8的问题详解 #225

Open
soapgu opened this issue Sep 19, 2023 · 0 comments
Open
Labels
problem problem or trouble

Comments

@soapgu
Copy link
Owner

soapgu commented Sep 19, 2023

主要问题

我们直接进入主题,使用下面代码,返回一个json对象

@app.route("/")
def hello_world():
    data = {'message': 'test utf-8,中文!'}
    return data

用postman看返回
图片
粗粗一看好像没啥问题

图片 仔细一看发现问题了!response就不是用的UTF-8编码!
  • 疑问

所有中文被写成/u开头的二次编码,虽然现在的json库都很强大,应该可以处理非UTF-8编码的内容。
但是这样总显得膈应。一定要打破砂锅问到底

  1. 先从搜索引擎/ChatGPT找答案

普遍给我答案只要config里面配一下JSON_AS_ASCII=False就行。
看上去很容易解决!
但是实验下来就是没用!还是要找官档

  1. 找官档的配置项
图片 这个配置项已经“过期”了,难怪不行!

The default app.json provider has equivalent attributes instead.

这句啥意思?可以通过app.json配置文件配置?

实验下来好像还是不行!

  1. 病急乱投医

Flask的json编码不行,我自己编行不行?

@app.route("/")
def hello_world():
    data = {'message': 'test utf-8,中文!'}
    return json.dumps(data,ensure_ascii=False);

答案是不行!response被解析成了html/text。
硬来是不行的,还是要靠巧劲

  1. 最终解法

最后有点陷入僵持了,报着试试的原则在Flask的网站里搜“ASCII”看看

找到相关项了

图片
app = Flask(__name__)
#app.config['JSON_AS_ASCII'] = False;

#set = app.config.from_pyfile("config.py");
#print("load config" + str(set));
print(app.config);
app.json.ensure_ascii=False;

@app.route("/")
def hello_world():
    data = {'message': 'test utf-8,中文!'}
    #return json.dumps(data,ensure_ascii=False);
    #response = jsonify(data)
    return data
   #return "<p>中文你好!</p>"

最终解决方案!注释留着代表走过的弯路!
原来答案就在那句话里面

The default app.json provider has equivalent attributes instead.
只不过app.json不是配置文件,而是Flask的json属性!

图片

原来我就是那只乌鸦!
图片

@soapgu soapgu changed the title Flask的application/json返回类型中文编码问题 Flask的application/json返回类型中文编码非UTF-8的问题详解 Sep 19, 2023
@soapgu soapgu added the problem problem or trouble label Sep 26, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
problem problem or trouble
Projects
None yet
Development

No branches or pull requests

1 participant