赞
踩
什么是序列化?
把我们能识别的对象,转换成别的格式,提供给其他人
什么是反序列化?
将别人提供给我们的编码数据转换为我们需要的数据
以Django框架为例:
def get(self, request):
response = {'code': '200', 'msg': "查询成功", 'results': results}
response = json.dumps(response)
return JsonResponse(response, safe=False)
接收到get请求后将python字典序列化为json格式响应回去
在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数据:
数据:
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)框架
pip install djangorestframework
原代码
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
:表示要对多个对象序列化
查询成功
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时返回报错信息
validate
:serializers
已经写好的钩子函数,attrs是前端传入且经过validate_task_name
校验的参数不符合max_length时会使用
DRF
自带的报错提示
需要在自定义的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
:序列化后需要被响应回去的字段,在创建(create)和更新(update)对象时,会将这个对象序列化为 JSON 数据返回给前端
data
:前端传入的需要被反序列化的数据。这些数据经过反序列化处理后,会被用于创建或更新对象实例。
在进入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_viewsreturn 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)
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)
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方法精准接受?
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)
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
view = super().as_view(**initkwargs)
:调用了父类的as_view(),也就是老的View类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)
总结:
先从结果出发,DRF的Request比Django的request多了个data属性
就是这个data属性帮我们序列化和反序列化,无需额外针对它的编码和请求方式进行修改判断
而这个新的request对象就是
from rest_framework.request import Request
这里的Request对象
老样子直接进他源码
class 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中取属性request.data
直接进入data查看源码@property
def data(self):
if not _hasattr(self, '_full_data'):
self._load_data_and_files()
return self._full_data
总结:
__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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。