1、传入到视图函数中的是restframework的Request对象,而不是Django的 HttpRequeset对象;Request是HttpRequest继承上做了拓展,兼容了HttpRequest所有功能
2、前端传递的application/json、application/x-www-form-urlencoded、multipart/form-data参数后端根据请求头中的Content——Type。使用统一的request.data属性获取
3、任何 APIException异常都会被捕获到,并且处理成合适格式的响应信息返回给客户端;
4、在DRF中的Response为HTTPResponse的子类
将django中的返回响应数据JsonResponse变为restframework中的Response
Response会自动根据渲染器来将数据转化为请求头中Accept需要的格式进行返回
status指定响应状态码,content_type指定响应头中的Content-Type,一般无需指定,会根据渲染器自动设置
5、重新声明了一个新的as_views方法并在dispatch()进行路由分发前,会对请求的客户端进行身份认证、权限检查、流量控制。
authentication_classes 列表或元组,身份认证类
permissoin_classes 列表或元组,权限检查类
throttle_classes 列表或元祖,流量控制类
在 APIView中仍以常规的类视图定义方法来实现get() 、post() 或者其他请求方式的方法。
View类核心代码在as_view和dispatch方法中,其中as_view是类方法(@classonlymethod),只能通过类调用,不能通过对象调用,它是类视图的入口点。注意这里调用的时候是通过类名.as_view()调用的。
路由匹配成功会调用类视图中的as_view()方法,但是ChannelsAPIView中根本没有as_view()方法
as_view()方法由父类View提供,子类继承父类,具备父类中所有的公用方法
我的路由
urlpatterns=[
re_path('^channels/$',views.ChannelsAPIView.as_view()),
]
我的视图
class ChannelsAPIView(View):
def get(self, request):
'''
GET /channels/
查询所有的频道信息
:param request:
:return:
'''
channel_queryset = NewsChannel.objects.all()
channel_list = []
for channel in channel_queryset:
channel_list.append({
'id': channel.id,
'name': channel.name,
'url': channel.url
})
return JsonResponse(channel_list,safe=False)
def post(self,request):
return JsonResponse({‘message’:‘post方法’})
1、@classonlymethod:表示当前方法为类方法,并且只能类去调用
2、http_method_names = [‘get’, ‘post’, ‘put’, ‘patch’, ‘delete’, ‘head’, ‘options’, ‘trace’]
3、as_view()方法中嵌套了view方法,类似于闭包
def as_view():
pass
def view()
pass
return view
3、代码执行到最后一行代码,开始调用view()方法
4、view()方法最后返回,return self.dispatch(request, *args, **kwargs)
5、进入dispatch(request, *args, **kwargs)方法中
@classonlymethod 表示当前方法为类方法,并且只能类去调用
def as_view(cls, **initkwargs): initkwargs为字典
"""Main entry point for a request-response process."""
for key in initkwargs:
if key in cls.http_method_names: 判断key(请求方法)是否在http_method_names中,如果不在抛出异常
raise TypeError("You tried to pass in the %s method name as a "
"keyword argument to %s(). Don't do that."
% (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) 实例化当前类的对象
if hasattr(self, 'get') and not hasattr(self, 'head'):
self.head = self.get
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
# take name and docstring from class
update_wrapper(view, cls, updated=())
# and possible attributes set by decorators
# like csrf_exempt from dispatch
update_wrapper(view, cls.dispatch, assigned=())
return view
6、request.method.lower():request.method获得前端的请求的方法,为大写,通过lower()转换为小写
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
7、如果前端的请求方法在[‘get’, ‘post’, ‘put’, ‘patch’, ‘delete’, ‘head’, ‘options’, ‘trace’]列表中,request.method.lower()为字符串类型,基于反射机制,根据当前的函数名字得到对应的函数——》这行代码相当于handler=get,这时候还没有调用,
8、执行return handler(request, *args, **kwargs)
:调用get(request,*args, **kwargs)
方法,而get(request,*args, **kwargs)
方法正是类视图中的get方法
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)
总结:1、整个as_view方法是一个装饰器函数,它返回内部函数view,所以as_view()执行其实就是内部函数view执行。内部函数view主要逻辑就是:as_view()=>view()=>dispatch()=>相应的http方法
总结:2、dispatch主要完成http请求方法的派发,调用视图类对应实例方法处理用户请求,所有用户需要定义和http请求方法同名的实例方法完成功能,所以一般CBV的模块写法是:
注意:django的CBV本质上来说就是FBV
from django.views import View
class ChannelsAPIView(View):
def get(self, request):
return JsonResponse({‘message’:‘get方法’})
def post(self,request):
return JsonResponse({‘message’:‘post方法’})
def put(self,request):
return JsonResponse({‘message’:‘put方法’})
def delete(self,request):
return JsonResponse({‘message’:‘delete方法’})
urlpatterns=[
re_path('^channels/$',views.ChannelsAPIView.as_view()),
]
我的视图
from rest_framework.response import Response
from rest_framework.views import APIView
class ChannelsAPIView(APIView):
def get(self, request):
'''
GET /channels/
查询所有的频道信息
:param request:
:return:
'''
channel_queryset = NewsChannel.objects.all()
channel_list = []
for channel in channel_queryset:
channel_list.append({
'id': channel.id,
'name': channel.name,
'url': channel.url
})
return JsonResponse(channel_list,safe=False)
def post(self,request):
return Response({‘message’:‘post方法’})
@classmethod
def as_view(cls, **initkwargs):
"""
Store the original class on the view function.
This allows us to discover information about the view when we do URL
reverse lookups. Used for breadcrumb generation.
"""
if isinstance(getattr(cls, 'queryset', None), models.query.QuerySet): 如果他是QuerySet的一个实例
def force_evaluation():
raise RuntimeError( 翻译:不要直接计算“.queryset”属性,因为结果将被缓存并在请求之间重用请改用“.all()”或调用“.get_queryset()
'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
该走这里了,调用父类的as_view() --- 父类的as_view()核心是dispatch() >> 跳转到dispatch()
view = super().as_view(**initkwargs) 调用父类(View)的as_view()方法;
view.cls = cls
view.initkwargs = initkwargs
# Note: session based authentication is explicitly CSRF validated,
# all other authentication is CSRF exempt.
豁免csrf检测, 返回view
return csrf_exempt(view) 函数里面套函数,这个一个装饰器!!!
1、
view = super().as_view(**initkwargs)
:调用父类(View)的as_view()方法;父类的as_view()核心是dispatch() >> 跳转到dispatch()
ChannelsAPIView类中没有定义dispatch方法,但父类APIView和View都实现了dispatch方法,那么继承那个dispatch方法呐?
根据__mro__先继承APIView中的dispatch方法
1、记录各个参数
2、调用initialize_request()方法
3、initial:加载各种中间件
4、根据得到的请求方法去处理,或处理异常
5、最后统一处理response
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
request = self.initialize_request(request, *args, **kwargs)
self.request = request
self.headers = self.default_response_headers # deprecate?
try:
self.initial(request, *args, **kwargs)
# Get the appropriate handler method
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)
except Exception as exc:
response = self.handle_exception(exc)
self.response = self.finalize_response(request, response, *args, **kwargs)
return self.response
Request:DRF框架提供的Request,并不是传统的request方法
def initialize_request(self, request, *args, **kwargs):
"""
Returns the initial request object.
"""
parser_context = self.get_parser_context(request)
return Request(
request,
parsers=self.get_parsers(),
authenticators=self.get_authenticators(),
negotiator=self.get_content_negotiator(),
parser_context=parser_context
)
class Request:
"""
Wrapper allowing to enhance a standard `HttpRequest` instance.
Kwargs:
- request(HttpRequest). The original request instance.
- parsers(list/tuple). The parsers to use for parsing the
request content.
- authenticators(list/tuple). The authenticators used to try
authenticating the request's user.
"""
def __init__(self, request, parsers=None, authenticators=None,
negotiator=None, parser_context=None):
assert isinstance(request, HttpRequest), (
'The `request` argument must be an instance of '
'`django.http.HttpRequest`, not `{}.{}`.'
.format(request.__class__.__module__, request.__class__.__name__)
)
self._request = request
self.parsers = parsers or ()
self.authenticators = authenticators or ()
self.negotiator = negotiator or self._default_negotiator()
self.parser_context = parser_context
self._data = Empty
self._files = Empty
self._full_data = Empty
self._content_type = Empty
self._stream = Empty
......
......
......
@property
def query_params(self):
"""
More semantically correct name for request.GET.
"""
return self._request.GET
@property
def data(self):
if not _hasattr(self, '_full_data'):
self._load_data_and_files()
return self._full_data
@property
def user(self):
"""
Returns the user associated with the current request, as authenticated
by the authentication classes provided to the request.
"""
if not hasattr(self, '_user'):
with wrap_attributeerrors():
self._authenticate()
return self._user
......
......
......
dispatch()源码中,
request = self.initialize_request(request, *args, **kwargs)
;
initialize_request方法:返回了Request(request,…)
Request类中实现了:query_params、data、user等等方法
request.data:获取前端传递的参数
request.query_params:获取查询字符串参数
request.user:获取用户
获取格式化后缀
设置并执行内容协商
设置并进行 决策版本,确定版本
执行认证(重点)
检查权限
检查限流
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)
最后统一处理response
def finalize_response(self, request, response, *args, **kwargs):
"""
Returns the final response object.
"""
# Make the error obvious if a proper response is not returned
assert isinstance(response, HttpResponseBase), (
'Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` '
'to be returned from the view, but received a `%s`'
% type(response)
)
if isinstance(response, Response):
if not getattr(request, 'accepted_renderer', None):
neg = self.perform_content_negotiation(request, force=True)
request.accepted_renderer, request.accepted_media_type = neg
response.accepted_renderer = request.accepted_renderer
response.accepted_media_type = request.accepted_media_type
response.renderer_context = self.get_renderer_context()
# Add new vary headers to the response instead of overwriting.
vary_headers = self.headers.pop('Vary', None)
if vary_headers is not None:
patch_vary_headers(response, cc_delim_re.split(vary_headers))
for key, value in self.headers.items():
response[key] = value
return response
1、wrapped_view.csrf_exempt = True:实现了将视图功能标记为不受CSRF视图保护;
即当进行post请求时,settings配置文件中间件’django.middleware.csrf.CsrfViewMiddleware’不用注释了
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.
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs)
wrapped_view.csrf_exempt = True
return wraps(view_func)(wrapped_view)