zoukankan      html  css  js  c++  java
  • drf serializer获取viewset 中的上下文context,自定义上下文

    1. 在视图继承ViewAPI时,在初始化序列化类时可以传递context参数

    2. 在视图继承viewset后,我们只能对序列化类做一个声明,但是在实际创建序列化实例时,会帮我们将rquest参数传递到实列中,可以使用self.context来获取.

    源码分析:

    BaseSerializer中:

    class BaseSerializer(Field):
        """
        The BaseSerializer class provides a minimal class which may be used
        for writing custom serializer implementations.
    
        Note that we strongly restrict the ordering of operations/properties
        that may be used on the serializer in order to enforce correct usage.
    
        In particular, if a `data=` argument is passed then:
    
        .is_valid() - Available.
        .initial_data - Available.
        .validated_data - Only available after calling `is_valid()`
        .errors - Only available after calling `is_valid()`
        .data - Only available after calling `is_valid()`
    
        If a `data=` argument is not passed then:
    
        .is_valid() - Not available.
        .initial_data - Not available.
        .validated_data - Not available.
        .errors - Not available.
        .data - Available.
        """
    
        def __init__(self, instance=None, data=empty, **kwargs):
            self.instance = instance
            if data is not empty:
                self.initial_data = data
            self.partial = kwargs.pop('partial', False)
            self._context = kwargs.pop('context', {}) # 传递上下文参数
            kwargs.pop('many', None)
            super(BaseSerializer, self).__init__(**kwargs)
    

    在viewset中是怎样自动传递上下文的的:

    class GenericAPIView(views.APIView):
        def get_serializer(self, *args, **kwargs):
            """
            Return the serializer instance that should be used for validating and
            deserializing input, and for serializing output.
            """
            serializer_class = self.get_serializer_class()
            kwargs['context'] = self.get_serializer_context()
            return serializer_class(*args, **kwargs)
    
        def get_serializer_class(self):
            """
            Return the class to use for the serializer.
            Defaults to using `self.serializer_class`.
    
            You may want to override this if you need to provide different
            serializations depending on the incoming request.
    
            (Eg. admins get full serialization, others get basic serialization)
            """
            assert self.serializer_class is not None, (
                "'%s' should either include a `serializer_class` attribute, "
                "or override the `get_serializer_class()` method."
                % self.__class__.__name__
            )
    
            return self.serializer_class
          #这里设置了上下文
        def get_serializer_context(self):
            """
            Extra context provided to the serializer class.
            """
            return {
                'request': self.request,
                'format': self.format_kwarg,
                'view': self
            }
    

    所以如果要自定以上下文的的值,可以重写get_serializer_context方法.

  • 相关阅读:
    Nmap绕过防火墙&脚本的使用
    Nmap在实战中的高级用法
    kali&BT安装好之后无法上网或者无法获得内网IP
    [转]谈渗透测试方法和流程
    xssless
    国内外有名的安全扫描工具,你知道几个?
    Linux下如果忘记了Mysql的root密码该怎么办?
    JSP手动注入 全
    sqlmap用户手册 [详细]
    Windows系统如何使用sqlmap
  • 原文地址:https://www.cnblogs.com/qianxunman/p/13798614.html
Copyright © 2011-2022 走看看