python --- jsonify and use the difference in the flask in json.dumps

Original link: https://blog.csdn.net/Duke_Huan_of_Qi/article/details/76064225

 

First, the experiment

the python provides the user frame flask method returns json format data comprising a response, i.e. jsonify, often used in development. Flask as a simple piece of back-end code, an end view of the service function returns json format data according to the client request parameters.

 

 


With chrome browser to access the page to get in the following figure:

 

 

 

Now we use instead python json library json.dumps own direct return value as a function of view, as follows:

 

 

PS: json.dumps direct return result is possible because the use make_response flask and determines the response of automatic construction method, but each response header field is the default. To customize the response field, or may be used make_response Response Response own configuration. With chrome access response page as shown below:

 

 

 


Second, analysis

1.Content-Type differentiated

Jsonify action is actually our incoming json json become serialized form of the data string, the response body, and is provided in response to the Content-Type of application / json, constructed response is returned to the client. jsonify source part as follows:

 

 

可以看出jsonify实际上也是使用了json.dumps来序列化json形式的数据,作为响应正文返回。indent表示json格式化的缩进,若是Ajax请求则不缩进(因为一般Ajax数据没必要直接展示),否则缩进2格。但想必从第一部分的实验结果我们已经看出来了,使用jsonify时响应的Content-Type字段值为application/json,而使用json.dumps时该字段值为text/html。Content-Type决定了接收数据的一方如何看待数据,如何处理数据,如果是application/json,则可以直接当做json对象处理,若是text/html,则还要将文本对象转化为json对象再做处理(个人理解,有误请指正)。


2.接受参数有区别

jsonify可以接受和python中的dict构造器同样的参数,如下图。

 

 

 

而json.dumps比jsonify可以多接受list类型和一些其他类型的参数。但我试了一下,形式为key1=value1,[key2=value2,...]这样的参数是不行的,会报出“TypeError: dumps() takes exactly 1 argument (0 given)”这一错误,而jsonify不会报错并能正常返回数据。

最后,我们可以使用flask中的make_response方法或者直接通过Response类,通过设置mimetype参数来达到和使用jsonify差不多的效果,但少写点代码何乐而不为呢?况且简洁一点更不容易出错,参数越多调试和维护就越麻烦。当然,使用哪个并不是绝对的,必要时要根据前端的数据处理方式来决定。

 

Guess you like

Origin www.cnblogs.com/zhlan/p/12041389.html