Django REST framework 源码剖析-渲染器图解(Renderers)

Django REST framework 源码剖析-渲染器图解(Renderers)

  • 在Django REST framework (DRF) 中,渲染器(Renderers)组件承担着将后端响应数据转换为客户端可解析的格式的职责。它们是数据序列化的关键部分,确保服务器以客户端所能理解的方式返回数据。渲染器会根据客户端请求中的 Accept头来选择适当的格式, 将响应数据转换为JSON、XML、HTML等不同格式, 以适应不同类型的客户端需求。

视图调用源码

  • rest_framework.views
python 复制代码
class APIView(View):

    # The following policies may be set at either globally, or per-view.
    renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES

JSONRenderer源码

  • rest_framework.renderers
python 复制代码
class JSONRenderer(BaseRenderer):
    """
    Renderer which serializes to JSON.
    """
    media_type = 'application/json'
    format = 'json'
    charset = None

TemplateHTMLRenderer源码

  • rest_framework.renderers
python 复制代码
class TemplateHTMLRenderer(BaseRenderer):
    """
    An HTML renderer for use with templates.

    The data supplied to the Response object should be a dictionary that will
    be used as context for the template.

    The template name is determined by (in order of preference):

    1. An explicit `.template_name` attribute set on the response.
    2. An explicit `.template_name` attribute set on this class.
    3. The return result of calling `view.get_template_names()`.

    For example:
        data = {'users': User.objects.all()}
        return Response(data, template_name='users.html')

    For pre-rendered HTML, see StaticHTMLRenderer.
    """
    media_type = 'text/html'
    format = 'html'
    charset = 'utf-8'

StaticHTMLRenderer源码

  • rest_framework.renderers
python 复制代码
class StaticHTMLRenderer(TemplateHTMLRenderer):
    """
    An HTML renderer class that simply returns pre-rendered HTML.

    The data supplied to the Response object should be a string representing
    the pre-rendered HTML content.

    For example:
        data = '<html><body>example</body></html>'
        return Response(data)

    For template rendered HTML, see TemplateHTMLRenderer.
    """
    media_type = 'text/html'
    format = 'html'
    charset = 'utf-8'

HTMLFormRenderer源码

  • rest_framework.renderers
python 复制代码
class HTMLFormRenderer(BaseRenderer):
    """
    Renderers serializer data into an HTML form.

    If the serializer was instantiated without an object then this will
    return an HTML form not bound to any object,
    otherwise it will return an HTML form with the appropriate initial data
    populated from the object.

    Note that rendering of field and form errors is not currently supported.
    """
    media_type = 'text/html'
    format = 'form'
    charset = 'utf-8'

BrowsableAPIRenderer源码

  • rest_framework.renderers
python 复制代码
class BrowsableAPIRenderer(BaseRenderer):
    """
    HTML renderer used to self-document the API.
    """
    media_type = 'text/html'
    format = 'api'
    charset = 'utf-8'

AdminRenderer源码

  • rest_framework.renderers
python 复制代码
class AdminRenderer(BrowsableAPIRenderer):
    template = 'rest_framework/admin.html'
    format = 'admin'

DocumentationRenderer源码

  • rest_framework.renderers
python 复制代码
class DocumentationRenderer(BaseRenderer):
    media_type = 'text/html'
    format = 'html'
    charset = 'utf-8'

SchemaJSRenderer源码

  • rest_framework.renderers
python 复制代码
class SchemaJSRenderer(BaseRenderer):
    media_type = 'application/javascript'
    format = 'javascript'
    charset = 'utf-8'

MultiPartRenderer源码

  • rest_framework.renderers
python 复制代码
class MultiPartRenderer(BaseRenderer):
    media_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'
    format = 'multipart'
    charset = 'utf-8'

CoreJSONRenderer源码

  • rest_framework.renderers
python 复制代码
class CoreJSONRenderer(BaseRenderer):
    media_type = 'application/coreapi+json'
    charset = None
    format = 'corejson'

全局渲染器配置示例

python 复制代码
REST_FRAMEWORK = {
	'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ]
}

局部解析器配置示例

python 复制代码
from django.contrib.auth.models import User
from rest_framework.renderers import JSONRenderer
from rest_framework.response import Response
from rest_framework.views import APIView

class UserCountView(APIView):
    """
    A view that returns the count of active users in JSON.
    """
    renderer_classes = [JSONRenderer]

    def get(self, request, format=None):
        user_count = User.objects.filter(active=True).count()
        content = {'user_count': user_count}
        return Response(content)

基于函数视图的解析器配置示例

python 复制代码
from rest_framework.decorators import api_view, renderer_classes
from rest_framework.response import Response
from myproject.models import User


@api_view(['GET'])
@renderer_classes([JSONRenderer])
def user_count_view(request, format=None):
    """
    A view that returns the count of active users in JSON.
    """
    user_count = User.objects.filter(active=True).count()
    content = {'user_count': user_count}
    return Response(content)

自定义渲染器示例

  • data 请求数据,由 Response() 实例化设置。
  • accepted_media_type 内容协商阶段确定的可接受的媒体类型。
  • renderer_context 视图提供的上下文信息字典。
python 复制代码
from django.utils.encoding import smart_unicode
from rest_framework import renderers


class PlainTextRenderer(renderers.BaseRenderer):
    media_type = 'text/plain'
    format = 'txt'

    def render(self, data, media_type=None, renderer_context=None):
        return data.encode(self.charset)

高级渲染器用法

python 复制代码
from rest_framework.decorators import api_view, renderer_classes
from rest_framework.response import Response
from myproject.models import User
from myproject.serializer import UserSerializer


@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def list_users(request):
    """
    可以返回系统中用户的 JSON 或 HTML 表示的视图。
    """
    queryset = Users.objects.filter(active=True)

    if request.accepted_renderer.format == 'html':
	    # TemplateHTMLRenderer 采用上下文字典,并且还需要 template_name 名称。
	    # 它不需要序列化。
        data = {'users': queryset}
        return Response(data, template_name='list_users.html')

    # JSONRenderer 需要正常的序列化数据。
    serializer = UserSerializer(instance=queryset)
    data = serializer.data
    return Response(data)
相关推荐
IT森林里的程序猿2 小时前
基于机器学习方法的网球比赛胜负趋势预测
python·机器学习·django
kobe_OKOK_3 小时前
Django ORM 字段查询表达式(Field lookup expressions)
后端·python·django
kobe_OKOK_4 小时前
Django ORM 无法通过 `ForeignKey` 自动关联,而是需要 **根据父模型中的某个字段(比如 ID)去查询子模型**。
后端·python·django
濑户川9 小时前
深入理解Django 视图与 URL 路由:从基础到实战
后端·python·django
江上月51314 小时前
django与vue3的对接流程详解(下)
后端·python·django
纸照片1 天前
【邪修玩法】如何在WPF中开放 RESTful API 服务
后端·wpf·restful
万粉变现经纪人1 天前
如何解决 pip install -r requirements.txt 约束文件 constraints.txt 仅允许固定版本(未锁定报错)问题
开发语言·python·r语言·django·beautifulsoup·pandas·pip
蓑笠翁0011 天前
Django REST Framework 全面指南:从模型到完整API接口开发
后端·python·django
鸽鸽程序猿1 天前
【项目】基于Spring全家桶的论坛系统 【下】
后端·spring·restful
B站_计算机毕业设计之家2 天前
python汽车数据分析可视化系统 爬虫 懂车帝 毕业设计 Django框架 vue框架 大数据✅
爬虫·python·数据分析·django·汽车·推荐算法·懂车帝