DRF的序列化和反序列化

DRF的序列化和反序列化

什么是序列化?

把我们能识别的对象,转换成别的格式,提供给其他人

  • 从数据库取出来—》序列化–》 给前端

什么是反序列化?

将别人提供给我们的编码数据转换为我们需要的数据

  • 前端数据发送给接口—》反序列化—》转存数据库

Django传统序列化

以Django框架为例:

def get(self, request):
    response = {'code': '200', 'msg': "查询成功", 'results': results}
	response = json.dumps(response)
	return JsonResponse(response, safe=False)

接收到get请求后将python字典序列化为json格式响应回去

Django传统反序列化

在Django中反序列化需要根据参数的编码类型使用不同方法

json.loads(request.POST)在Django中并不能转换url编码类型,因此当参数为url编码时这种写法是错误的

反序列化json数据

# json数据:b'{"abc":"def"}'

data = json.loads(request.body)
# 结果:{'abc': 'def'}

data = json.loads(request.POST)
# 报错

data = request.POST
# 为空 <QueryDict: {}>

encoded数据:

数据:

image-20240411155853328

def put(self, request, u_id):
	print(request.body)
    # b'abc=def&qqq=www'
    
	print(f'POST:{request.POST}')
    # POST:<QueryDict: {}>
    
	print(f'body:{request.body}')
    # body:b'abc=def&qqq=www'

可以看出在没有第三方模块的情况下无法将request中的参数转化为有效数组,因此接下来我们需要借助Django的DRF(Django Rest Framework)框架

安装DRF

pip install djangorestframework

序列化器serializers

序列化

原代码

class task(View):
    # 获取所有内容
    def get(self, request):
        results = []
        task_list = (models.task.objects.all())
        [results.append({'task_id': i.task_id, 'task_name': i.task_name, 'task_time': str(i.task_time),
                         'task_desc': i.task_desc}) for i in task_list]
        response = {'code': '200', 'msg': "查询成功", 'results': results}
        response = json.dumps(response)
        return JsonResponse(response, safe=False)

添加serializers.py(自行在app中创建)

# taskserializer.py
from rest_framework import serializers

class TaskSerailizer(serializers.Serializer):
    # 过滤条件 下面是会被带入参数的字段
    task_id = serializers.CharField()
    task_name = serializers.CharField()
    task_time = serializers.CharField()
    task_desc = serializers.CharField()

视图

from rest_framework.views import APIView
from rest_framework.response import Response

class task(APIView):
    # 获取所有
    def get(self, request):
        # 获取表中所有对象
        task_obj = models.task.objects.all()
        # 将task_obj丢进序列化器序列化
        serializer = TaskSerailizer(instance=task_obj, many=True)
        return Response({'code': '200', 'msg': '查询成功', 'result': serializer.data})

serializer = TaskSerailizer(instance=task_obj, many=True)

instance:指定要被序列化的对象

many:表示要对多个对象序列化

查询成功

image-20240411191719930

反序列化

from rest_framework import serializers
from rest_framework.exceptions import ValidationError


class TaskSerailizer(serializers.Serializer):
    task_id = serializers.CharField()
    task_name = serializers.CharField(max_length=10)
    task_time = serializers.CharField()
    task_desc = serializers.CharField(min_length=10)

    def validate_task_name(self, task_name):
        if 'qqq' in task_name:
            raise ValidationError('task_name中不能包含qqq')
        else:
            return task_name

    def validate(self, attrs):
        # attrs是前端传入且经过validate_name校验的参数
        if attrs.get('task_name') == attrs.get('task_desc'):
            raise ValidationError('task名和task描述不能相同')
        else:
            return attrs

validate_task_name:自定义的钩子函数,当task_name出现qqq时返回报错信息

validateserializers已经写好的钩子函数,attrs是前端传入且经过validate_task_name校验的参数

不符合max_length时会使用DRF自带的报错提示

image-20240411194809610

反序列化保存

需要在自定义的serializers.py文件中重写create和update方法

from rest_framework import serializers
from app import models


class TaskSerailizer(serializers.Serializer):
    task_id = serializers.CharField()
    task_name = serializers.CharField(max_length=10)
    task_time = serializers.CharField()
    task_desc = serializers.CharField(min_length=10)

    def create(self, validated_data):
        # validated_data:前端传入且已通过校验的数据
        models.task.objects.create(**validated_data)

    def update(self, instance, validated_data):
        # instance:要更新的已存在对象
        # validated_data:前端传入且已通过校验的数据
        instance.task_id = validated_data.get('task_id')
        instance.task_name = validated_data.get('task_name')
        instance.task_time = validated_data.get('task_time')
        instance.task_desc = validated_data.get('task_desc')
        instance.save()
        return instance

views.py

instance:要更新的已存在对象
validated_data:前端传入且已通过校验的数据

def put(self, request, u_id):
    task_obj = models.task.objects.filter(pk=u_id).first()
    # 改对象必须传data和instance
    serializer = TaskSerailizer(instance=task_obj, data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response({'code': '200', 'msg': "修改成功", 'result': serializer.data})
    else:
        return Response({'code': '201', 'msg': serializer.errors})

instance和data

instance:序列化后需要被响应回去的字段,在创建(create)和更新(update)对象时,会将这个对象序列化为 JSON 数据返回给前端

data:前端传入的需要被反序列化的数据。这些数据经过反序列化处理后,会被用于创建或更新对象实例。

CBV和APIView执行流程源码解析

CBV源码分析

在进入APIView之前首先需要了解传统CBV的原理

例:

# urls.py
from django.contrib import admin
from django.urls import path
import app.views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('app/', app.views.task.as_view()),
]

# views.py
class task(View):
    # 根据id获取
    def get(self, request, u_id):
        response = {'code': '200', 'msg': "查询成功"}
        return JsonResponse(json.dumps(response), safe=False)

首先引入问题:为什么浏览器向后端发送get请求时会被该get方法精准接受?

其实是因为在注册url时app.views调用的as_view()方法帮我们做好了大部分规划

Ctrl+左键进入as_view()源码

class View:
    http_method_names = [
        "get",
        "post",
        "put",
        "patch",
        "delete",
        "head",
        "options",
        "trace",
    ]

    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)


    @classonlymethod
    def as_view(cls, **initkwargs):
        """Main entry point for a request-response process."""
        for key in initkwargs:
            if key in cls.http_method_names:
                raise TypeError(
                    "The method name %s is not accepted as a keyword argument "
                    "to %s()." % (key, cls.__name__)
                )
            if not hasattr(cls, key):
                raise TypeError(
                    "%s() received an invalid keyword %r. as_view "
                    "only accepts arguments that are already "
                    "attributes of the class." % (cls.__name__, key)
                )

        def view(request, *args, **kwargs):
            self = cls(**initkwargs)
            self.setup(request, *args, **kwargs)
            if not hasattr(self, "request"):
                raise AttributeError(
                    "%s instance has no 'request' attribute. Did you override "
                    "setup() and forget to call super()?" % cls.__name__
                )
            return self.dispatch(request, *args, **kwargs)

        view.view_class = cls
        view.view_initkwargs = initkwargs

        # __name__ and __qualname__ are intentionally left unchanged as
        # view_class should be used to robustly determine the name of the view
        # instead.
        view.__doc__ = cls.__doc__
        view.__module__ = cls.__module__
        view.__annotations__ = cls.dispatch.__annotations__
        # Copy possible attributes set by decorators, e.g. @csrf_exempt, from
        # the dispatch method.
        view.__dict__.update(cls.dispatch.__dict__)

        # Mark the callback if the view class is async.
        if cls.view_is_async:
            markcoroutinefunction(view)

        return view


    def dispatch(self, request, *args, **kwargs):
        # Try to dispatch to the right method; if a method doesn't exist,
        # defer to the error handler. Also defer to the error handler if the
        # request method isn't on the approved list.
        if request.method.lower() in self.http_method_names:
            handler = getattr(
                self, request.method.lower(), self.http_method_not_allowed
            )
        else:
            handler = self.http_method_not_allowed
        return handler(request, *args, **kwargs)

    def http_method_not_allowed(self, request, *args, **kwargs):
        logger.warning(
            "Method Not Allowed (%s): %s",
            request.method,
            request.path,
            extra={"status_code": 405, "request": request},
        )
        response = HttpResponseNotAllowed(self._allowed_methods())

        if self.view_is_async:

            async def func():
                return response

            return func()
        else:
            return response

  • @classonlymethod表示只能用类调用此方法,这也是为什么我们只能用as_views()而不是as_views
  • 这个时候我们来到了task(View)继承的View类下的as_view()方法
  • 中间的步骤先不管 直接看return view
def view(request, *args, **kwargs):
    self = cls(**initkwargs)
    self.setup(request, *args, **kwargs)
    if not hasattr(self, "request"):
        raise AttributeError(
            "%s instance has no 'request' attribute. Did you override "
            "setup() and forget to call super()?" % cls.__name__
        )
    return self.dispatch(request, *args, **kwargs)
  • 这个时候可以看出其实我们就是在调用父类的view方法
  • 这里的request参数就是我们的浏览器接受的request请求,如果没填request则会弹出一个error
  • 重点是最后调用了实例中的dispatch方法
  • 既然我们的task类调用了dispatch方法那么就应该在task类下搜寻这个方法,但是很明显我们没有写过这方法,因此又回到父类View中的dispatch方法(这俩方法挨得很近,往下翻翻就找到了)
def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(
            self, request.method.lower(), self.http_method_not_allowed
        )
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)
  • if request.method.lower() in self.http_method_names:当我们的request请求类型存在于http_method_names
  • 那么先看看这个http_method_names是什么东西
http_method_names = [
    "get",
    "post",
    "put",
    "patch",
    "delete",
    "head",
    "options",
    "trace",
]
  • 其实就是个定义好的字符串列表
  • 再接着看dispatch
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
  • 其实就是从我们task实例中获取相应的HTTP请求方法,如果不存在就用它默认的
  • 最后返回handler,再解释一下gatter的用法
class Test(object):
    x = 1


a = Test()
print(getattr(a, 'x'))  # 获取属性 x 值
# 结果:1
print(getattr(a, 'y', 'None'))  # 获取属性 y 值不存在,但设置了默认值
# 结果:None
print(a.x)  # 效果等同于上面
# 结果:1
  • 回到我们最初的问题为什么浏览器向后端发送get请求时会被该get方法精准接受?
  • 走到这里基本可以得出结论了,说白了就是如果我有get就走我类下的get方法,没有就走它默认的

APIView源码分析

  • class task(APIView):直接Ctrl+左键进入APIView
  • 直接看里面的as_view()方法
class APIView(View):	
    @classmethod
    def as_view(cls, **initkwargs):
        if isinstance(getattr(cls, 'queryset', None), models.query.QuerySet):
            def force_evaluation():
                raise RuntimeError(
                    'Do not evaluate the `.queryset` attribute directly, '
                    'as the result will be cached and reused between requests. '
                    'Use `.all()` or call `.get_queryset()` instead.'
                )
            cls.queryset._fetch_all = force_evaluation

        view = super().as_view(**initkwargs)
        view.cls = cls
        view.initkwargs = initkwargs

        # Note: session based authentication is explicitly CSRF validated,
        # all other authentication is CSRF exempt.
        return csrf_exempt(view)
  • 当请求发送过来时先进入csrf_exempt(view)
def csrf_exempt(view_func):
    """Mark a view function as being exempt from the CSRF view protection."""

    # view_func.csrf_exempt = True would also work, but decorators are nicer
    # if they don't have side effects, so return a new function.
    @wraps(view_func)
    def wrapper_view(*args, **kwargs):
        return view_func(*args, **kwargs)

    wrapper_view.csrf_exempt = True
    return wrapper_view
  • 里面其实就是第一个CSRF装饰器,它帮你免除了CSRF保护,并返回了一个带有相同功能的函数
  • view = super().as_view(**initkwargs):调用了父类的as_view(),也就是老的View类
  • 那么既然它既然调用了父类的方法,肯定也会有些地方进行了重新
  • 老View中最重要的方法是什么?是dispatch
  • 直接在APIView类中找它重写的dispatch
def dispatch(self, request, *args, **kwargs):
    """
    `.dispatch()` is pretty much the same as Django's regular dispatch,
    but with extra hooks for startup, finalize, and exception handling.
    """
    self.args = args
    self.kwargs = kwargs
    # 1.这里包装了新的request对象,此时的request在原Django的request对象的基础上升级了
    request = self.initialize_request(request, *args, **kwargs)
    self.request = request
    self.headers = self.default_response_headers  # deprecate?

    try:
        # 2.initial里做了三件事:三大认证:认证,频率,权限
        self.initial(request, *args, **kwargs)

        # Get the appropriate handler method
        # 3.这里看注释也能猜到就是执行了跟请求方式同名的方法,也就是我们用的get post...
        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower(),
                              self.http_method_not_allowed)
        else:
            handler = self.http_method_not_allowed
		
        response = handler(request, *args, **kwargs)
	
    # 4.如果三大认证或者视图函数出现异常会在这里统一处理
    except Exception as exc:
        response = self.handle_exception(exc)

    self.response = self.finalize_response(request, response, *args, **kwargs)
    return self.response
  • 先来看一下三大认证
def initial(self, request, *args, **kwargs):
    """
    Runs anything that needs to occur prior to calling the method handler.
    """
    self.format_kwarg = self.get_format_suffix(**kwargs)

    # Perform content negotiation and store the accepted info on the request
    neg = self.perform_content_negotiation(request)
    request.accepted_renderer, request.accepted_media_type = neg

    # Determine the API version, if versioning is in use.
    version, scheme = self.determine_version(request, *args, **kwargs)
    request.version, request.versioning_scheme = version, scheme

    # Ensure that the incoming request is permitted
    self.perform_authentication(request)
    self.check_permissions(request)
    self.check_throttles(request)
  • self.perform_authentication(request) 验证请求合法性
  • self.check_permissions(request) 检查请求权限
  • self.check_throttles(request) 验证请求频率

总结:

  • 只要执行了DRF的APIView,就不会再有CSRF限制了
  • request也会被替换为它新建的request
  • 在执行请求方法之前(与方法重名的request请求)进行了三大验证
    • 验证合法性
    • 验证请求权限
    • 验证请求频率
  • 三大认证和视图函数中任意位置出现异常统统报错

DRF的Request解析

先从结果出发,DRF的Request比Django的request多了个data属性

就是这个data属性帮我们序列化和反序列化,无需额外针对它的编码和请求方式进行修改判断

而这个新的request对象就是

from rest_framework.request import Request

这里的Request对象

老样子直接进他源码

class Request:
  • 此时抛出第一个疑问:既然新Request没有继承老的request那他是怎么实现方法重构的呢?难不成一个一个写吗
  • 其实它在下面用到了魔法方法__getattr__
def __getattr__(self, attr):
    """
    If an attribute does not exist on this instance, then we also attempt
    to proxy it to the underlying HttpRequest object.
    """
    try:
        _request = self.__getattribute__("_request")
        return getattr(_request, attr)
    except AttributeError:
        return self.__getattribute__(attr)
  • __getattr__是一个拦截方法,当调用了类中不存在的属性时就会触发__getattr__
  • _request = self.__getattribute__("_request")的意思就是通过调用对象的__getattribute__方法来获取对象中名为_request的属性值,说白了就是去老request中取属性
  • 那么接下来在找找data属性在哪
  • request.data直接进入data查看源码

image-20240411230702887

  • 注意是rest_framework.request的data
@property
def data(self):
    if not _hasattr(self, '_full_data'):
        self._load_data_and_files()
    return self._full_data
  • 当前实例中没有_full_data属性时自动调用_load_data_and_files()方法,而这个方法就是他帮我们封装各种请求和编码方式的地方(内容过多有兴趣自己去了解)

总结:

  • 之前如何用request,在DRF中还是如何用
  • request.data将请求体的数据,将原先的各个方法包装成了数据属性
  • request.query_params就是原先的request.GET,这么写是为了符合restful规范
  • __getattr__中的request._request 就是老的Django中的request

魔法方法__getattr__

以__开头的都叫魔法方法,魔法方法不是我们主动调用的,而是在某种情况下自动触发的

__getattr__用于拦截对象.属性,如果属性不存在则会触发

class Person:
    def __getattr__(self, item):
        print('根据:', item, '取值')
        return '123'


p = Person()
print(p.name)  # 属性不存在,就会打印__getattr__中的内容
# 根据: name 取值
# 123
  • 28
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值