下面的代码都是我从github上下载的源码中摘取的
django: https://github.com/django/django
下载命令: git clone https://github.com/django/django.git rest_framework: https://github.com/tomchristie/django-rest-framework
下载命令: git clone https://github.com/tomchristie/django-rest-framework.git
============================================================================================== (1)as_view()是什么意思?为什么要加这个。 下面这段话是我从晚上摘录的
==========================================================
因为 URLConf 仍然使用“给一个可调用对象传入 HttpRequest ,并期待其返回一个 HttpResponse”这样的逻辑,所以对于类视图,必须设计一个可调用的接口。这就是类视图的 as_view() 类方法。他接受 request,并实例化类视图,接着调用实例的 dispatch() 方法。这个方法会依据 request 的请求类型再去调用实例的对应同名方法,并把 request 传过去,如果没有对应的方法,就引发一个 HttpResponseNotAllowed 异常。
==========================================================
我的理解:
views.py里面定义的类继承了rest_framework/views.py的class APIView(VIew)类,这个类里面有一个
def as_view(clas, **initkwargs)这个函数。结合上面的叙述就可以知道了。
我在源码里面找了一下,调研了一下。 1 rest_framework/views.py
2
3 @classmethod
4 def as_view(cls, **initkwargs):
5 """
6 Store the original class on the view function.
7
8 This allows us to discover information about the view when we do URL
9 reverse lookups. Used for breadcrumb generation.
10 """
11 view = super(APIView, cls).as_view(**initkwargs)
12 view.cls = cls
13 # Note: session based authentication is explicitly CSRF validated,
14 # all other authentication is CSRF exempt.
15 return csrf_exempt(view)
16
17 =======================================================================
18 django/views/decorators/csrf.py
19
20 def csrf_exempt(view_func):
21 """
22 Marks a view function as being exempt from the CSRF view protection.
23 """
24 # We could just do view_func.csrf_exempt = True, but decorators
25 # are nicer if they don't have side-effects, so we return a new
26 # function.
27 def wrapped_view(*args, **kwargs):
28 return view_func(*args, **kwargs)
29 wrapped_view.csrf_exempt = True
30 return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
31 =======================================================================
32 python27/Lib/functools.py
33
34 def wraps(wrapped,
35 assigned = WRAPPER_ASSIGNMENTS,
36 updated = WRAPPER_UPDATES):
37 """Decorator factory to apply update_wrapper() to a wrapper function
38
39 Returns a decorator that invokes update_wrapper() with the decorated
40 function as the wrapper argument and the arguments to wraps() as the
41 remaining arguments. Default arguments are as for update_wrapper().
42 This is a convenience function to simplify applying partial() to
43 update_wrapper().
44 """
45 return partial(update_wrapper, wrapped=wrapped,
46 assigned=assigned, updated=updated)
47
48
49 =============================================================================
50 需要慢慢去学习
1 django/views/generic/base.py
2
3 class View(object):
4 """
5 Intentionally simple parent class for all views. Only implements
6 dispatch-by-method and simple sanity checking.
7 """
8
9 http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
10
11 def __init__(self, **kwargs):
12 """
13 Constructor. Called in the URLconf; can contain helpful extra
14 keyword arguments, and other things.
15 """
16 # Go through keyword arguments, and either save their values to our
17 # instance, or raise an error.
18 for key, value in six.iteritems(kwargs):
19 setattr(self, key, value)
20
21 @classonlymethod
22 def as_view(cls, **initkwargs):
23 """
24 Main entry point for a request-response process.
25 """
26 for key in initkwargs:
27 if key in cls.http_method_names:
28 raise TypeError("You tried to pass in the %s method name as a "
29 "keyword argument to %s(). Don't do that."
30 % (key, cls.__name__))
31 if not hasattr(cls, key):
32 raise TypeError("%s() received an invalid keyword %r. as_view "
33 "only accepts arguments that are already "
34 "attributes of the class." % (cls.__name__, key))
35
36 def view(request, *args, **kwargs):
37 self = cls(**initkwargs)
38 if hasattr(self, 'get') and not hasattr(self, 'head'):
39 self.head = self.get
40 self.request = request
41 self.args = args
42 self.kwargs = kwargs
43 return self.dispatch(request, *args, **kwargs)
44 view.view_class = cls
45 view.view_initkwargs = initkwargs
46
47 # take name and docstring from class
48 update_wrapper(view, cls, updated=())
49
50 # and possible attributes set by decorators
51 # like csrf_exempt from dispatch
52 update_wrapper(view, cls.dispatch, assigned=())
53 return view
54
55 def dispatch(self, request, *args, **kwargs):
56 # Try to dispatch to the right method; if a method doesn't exist,
57 # defer to the error handler. Also defer to the error handler if the
58 # request method isn't on the approved list.
59 if request.method.lower() in self.http_method_names:
60 handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
61 else:
62 handler = self.http_method_not_allowed
63 return handler(request, *args, **kwargs)
64
65 def http_method_not_allowed(self, request, *args, **kwargs):
66 logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
67 extra={
68 'status_code': 405,
69 'request': request
70 }
71 )
72 return http.HttpResponseNotAllowed(self._allowed_methods())
73
74 def options(self, request, *args, **kwargs):
75 """
76 Handles responding to requests for the OPTIONS HTTP verb.
77 """
78 response = http.HttpResponse()
79 response['Allow'] = ', '.join(self._allowed_methods())
80 response['Content-Length'] = '0'
81 return response
82
83 def _allowed_methods(self):
84 return [m.upper() for m in self.http_method_names if hasattr(self, m)]
85
86
=========================================================================
(2)在urls.py里面出现的pk是怎么回事
我去rest_framework/generics.py里面看了class GenericAPIView(views.APIView)的代码 下面是我截选的代码: 1 class GenericAPIView(views.APIView):
2 queryset = None
3 serializer_class = None
4
5 # If you want to use object lookups other than pk, set 'lookup_field'.
6 # For more complex lookup requirements override `get_object()`.
7 lookup_field = 'pk'
8 lookup_url_kwarg = None
9 def get_object(self):
10 "" "
11 Returns the object the view is displaying.
12
13 You may want to override this if you need to provide non-standard
14 queryset lookups. Eg if objects are referenced using multiple
15 keyword arguments in the url conf.
16 "" "
17 queryset = self.filter_queryset(self.get_queryset())
18
19 # Perform the lookup filtering.
20 lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
21
22 assert lookup_url_kwarg in self.kwargs, (
23 'Expected view %s to be called with a URL keyword argument '
24 'named "%s". Fix your URL conf, or set the `.lookup_field` '
25 'attribute on the view correctly.' %
26 (self.__class__.__name__, lookup_url_kwarg)
27 )
28
29 filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
30 obj = get_object_or_404(queryset, **filter_kwargs)
31
32 # May raise a permission denied
33 self.check_object_permissions(self.request, obj)
34
35 return obj
36
~
pk是框架默认的值,如果不想用"pk"就要修改lookup_field这个变量 (3)RetrieveAPIView 表示什么
202 class RetrieveAPIView (mixins.RetrieveModelMixin,
203 GenericAPIView):
204 """
205 Concrete view for retrieving a model instance.
206 """
207 def get(self, request, *args, **kwargs):
208 return self.retrieve(request, *args, **kwargs)
209