flask如何返回真正意義上的json字符串?以及中文如何正常顯示?


flask中,不能直接return字典,需要把字典轉換為json字符串
方式有三種:
1. return str(字典)
2.return json.dumps(字典)
3.return jsonify(字典)
其中,dumps是json模塊的方法,jsonify是flask封裝的方法

雖然他們返回的都是json字符串,但是是不一樣的

0.代碼及腳本准備

服務端部分代碼

@server.route('/login',methods=['get','post'])
def login():
    username = request.values.get('username','').strip()
    password = request.values.get('password','').strip()
    if username and password:
        password = md5_s(password)
        sql = 'select id,username from users where username="%s" and password="%s"'%(username,password)
        res = op_mysql(sql)
        if res:
            token = username+str(int(time.time()))
            token = md5_s(token)
            op_redis(username,token)
            response = make_response('{"code":9420, "msg":"恭喜%s,登錄成功","token":"%s"}'%(username,token))
            response.set_cookie(username,token)
            return response
            # return '{"code":9420, "msg":"恭喜%s,登錄成功","token":"%s"}'%(username,token)
        else:
            return '{"code":9410,"msg":"用戶名或密碼不正確"}'
            # return json.dumps({"code":9410,"msg":"用戶名或密碼不正確"},ensure_ascii=False)
            # return jsonify({"code":9410,"msg":"用戶名或密碼不正確"})  # jmeter請求,中文響應亂碼;postman請求,中文正常顯示
    else:
        return '{"code":9400,"msg":"用戶名和密碼不能為空"}'

jmeter腳本

這里用錯誤的賬號和密碼來演示

 

1.返回str(字典)

return '{"code":9410,"msg":"用戶名或密碼不正確"}'  

jmeter響應結果:中文正常顯示

瀏覽器響應

響應頭

2.返回json.dumps(字典)

return json.dumps({"code":9410,"msg":"用戶名或密碼不正確"}) 

jmeter響應結果:中文未正常顯示

msg =  "\u7528\u6237\u540d\u6216\u5bc6\u7801\u4e0d\u6b63\u786e"
res = msg.encode('utf-8')
print(res,type(res))
res = msg.encode('utf-8').decode('utf-8')
print(res,type(res))
print(msg)

結果

b'\xe7\x94\xa8\xe6\x88\xb7\xe5\x90\x8d\xe6\x88\x96\xe5\xaf\x86\xe7\xa0\x81\xe4\xb8\x8d\xe6\xad\xa3\xe7\xa1\xae' <class 'bytes'>
用戶名或密碼不正確 <class 'str'>
用戶名或密碼不正確

要想中文正常顯示,需要加上:ensure_ascii=False

return json.dumps({"code":9410,"msg":"用戶名或密碼不正確"},ensure_ascii=False) 

jmeter響應結果:中文正常顯示

 

瀏覽器響應

響應頭

3.返回jsonify(字典)

return jsonify({"code":9410,"msg":"用戶名或密碼不正確"}) 

jmeter響應結果:中文未正常顯示 

要想中文正常顯示,需要加上:server.config['JSON_AS_ASCII'] = False

jmeter響應結果:中文正常顯示

 

瀏覽器響應

響應頭

4.總結

方式一:返回的是: Content-Type:text/html 

方式二:返回的是: Content-Type:text/html 

方式三:返回的是: Content-Type:application/json

所以,方式三才是真正意義上的json字符串。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM