zoukankan      html  css  js  c++  java
  • 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 =  "u7528u6237u540du6216u5bc6u7801u4e0du6b63u786e"
    res = msg.encode('utf-8')
    print(res,type(res))
    res = msg.encode('utf-8').decode('utf-8')
    print(res,type(res))
    print(msg)

    结果

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

  • 相关阅读:
    Spring(八)-spring5框架新功能
    Spring(七)-事务操作
    Spring(五)-AOP
    Linux errno错误码
    思考:如何保证服务稳定性?
    CPU性能分析工具原理
    Oracle数据库url格式
    java对象的四种引用:强引用、软引用、弱引用和虚引用
    给老板汇报技术规划的要点
    后端程序员必备:分布式事务基础篇
  • 原文地址:https://www.cnblogs.com/uncleyong/p/11356236.html
Copyright © 2011-2022 走看看