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字符串。

转载于:https://www.cnblogs.com/uncleyong/p/11356236.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值