简体   繁体   English

json.dumps() 和 JSONRenderer.render() 方法有什么区别?

[英]What is the difference between json.dumps() and JSONRenderer.render() methods?

I am learning Django Rest Framework.我正在学习 Django Rest 框架。 I came up across method JSONRenderer.render() which takes python objects and converts them to JSON string.我遇到了 JSONRenderer.render() 方法,它采用 python 对象并将它们转换为 JSON 字符串。

But why do not we use json.dumps() method for this.但是我们为什么不为此使用 json.dumps() 方法。 Why to create another method which does the same work?为什么要创建另一种具有相同作用的方法?

json.dumps is a standard library function that converts a dictionary into a JSON string. json.dumps是一个标准库 function,它将字典转换为 JSON 字符串。

JSONRenderer is a Django REST Framework renderer . JSONRenderer是一个 Django REST 框架渲染器 Renderer is a class responsible for making sure your clients get a correctly-formatted HTTP response .渲染器是一个 class 负责确保您的客户获得格式正确的HTTP 响应 That is, that the response is a valid HTTP response, with a correct Content-Type header and other things like that.也就是说,响应是有效的 HTTP 响应,具有正确的Content-Type header和其他类似的东西。 DRF allows you to use different renderers, because you might as well have sent an XML response, or a binary. DRF 允许您使用不同的渲染器,因为您可能已经发送了 XML 响应或二进制文件。 All of them need to be formatted into a correct HTTP response.所有这些都需要格式化为正确的 HTTP 响应。

JSONRenderer does need to convert a dictionary to JSON in order to fulfil its purpose, but that's not all it does. JSONRenderer确实需要将字典转换为 JSON 以实现其目的,但这还不是全部。 This class is aware that it's used in an HTTP context, while json.dumps is a generic function fur such classes that purposely lacks this context so you could use it everywhere. This class is aware that it's used in an HTTP context, while json.dumps is a generic function fur such classes that purposely lacks this context so you could use it everywhere.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM