下面的代码都是我从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

(1)as_view() (2)在urls.py里面出现的pk是怎么回事 (3)RetrieveAPIView表示什么的更多相关文章

  1. [django]urls.py 中重定向

    Django 1.5 有时候需要对一个链接直接重定向,比如首页啥的重定向到一个内容页等等,在views.py 中可以设定,如果没有参数啥的在urls.py 中设定更加方面 from django.vi ...

  2. 第三百零四节,Django框架,urls.py模块,views.py模块,路由映射与路由分发以及逻辑处理——url控制器

    Django框架,urls.py模块,views.py模块,路由映射与路由分发以及逻辑处理——url控制器 这一节主讲url控制器 一.urls.py模块 这个模块是配置路由映射的模块,当用户访问一个 ...

  3. 4.对urls.py的解释

    解释: 路由配置文件(URL分发器),它的本质是URL模式以及要为该URL模式调用的视图函数之间的映射表.就是以这种方式告诉Django对于每个URL的处理类.Django启动的时候回去加载urls. ...

  4. 二 Django框架,urls.py模块,views.py模块,路由映射与路由分发以及逻辑处理——url控制器

    Django框架,urls.py模块,views.py模块,路由映射与路由分发以及逻辑处理——url控制器 这一节主讲url控制器 一.urls.py模块 这个模块是配置路由映射的模块,当用户访问一个 ...

  5. django-3-视图(views.py)与网址(urls.py)

    视图与网址 操作文件:urls.py.views.py urls.py 作用:用于处理前台的链接(如前台访问:127.0.0.1:8080/index/1212/21212),其实永远访问的是同一个文 ...

  6. django搭建web (二) urls.py

    URL模式: 在app下的urls.py中 urlpatterns=[ url(正则表达式,view函数,参数,别名,前缀)] urlpatterns=[ url(r'^hello/$',hello. ...

  7. Django入门三之urls.py重构及参数传递

    1. 内部重构 2. 外部重构 website/blog/urls.py website/website/urls.py 3. 两种参数处理方式 -1. blog/index/?id=1234& ...

  8. Django的urls.py加载静态资源图片,TypeError: view must be a callable or a list/tuple in the case of include().

    Django的urls.py加载静态资源图片,TypeError: view must be a callable or a list/tuple in the case of include(). ...

  9. urls.py的配置[路由配置]

    urls.py的配置[路由配置] Get请求与Post请求的方式 get请求: (1)地址栏输入url (2)<a href="请求url">点击</a> ...

随机推荐

  1. 【LeetCode OJ】Balanced Binary Tree

    Problem Link: http://oj.leetcode.com/problems/balanced-binary-tree/ We use a recursive auxilar funct ...

  2. Magento文件系统目录结构

    magento │  .htaccess│  cron.php //系统cron程序,修改 linux的cron运行,加入magento的一些定时处理│  cron.sh│  favicon.ico ...

  3. MATLAB与C/C++混合编程的一些总结

    [转载请注明出处]http://www.cnblogs.com/mashiqi 先上总结: 由于C/C++语言的函数输入输出参数的特点,可以将多个参数方便地传入一个函数中,但却不能方便地返回多个参数. ...

  4. Crypto++ 动态链接编译与实例测试

    测试用例的来源<Crypto++入门学习笔记(DES.AES.RSA.SHA-256)> 解决在初始化加密器对象时触发异常的问题: CryptoPP::AESEncryption aesE ...

  5. iTunesConnect进行App转移

    最近有客户提出需求,要把发布的OEM应用转移到自己的账户下,查询未果,在网站上搜索,死活找不到对应的选项,这两天看之前提交的版本已经审核通过了,发现很容易的就找到了转移版本的地方. 仔细思量,应该是之 ...

  6. POJ 1837 DP

    一开始看到这个题 第一反应:暴搜! 看看数据范围 ...放弃了 然后就在各种憋状态转移方程. 各种不会 还是看了Discuss里面说的才有点儿思路 直接放状态转移方程: f[i][ j+ w[i]*c ...

  7. lnmp 在nginx中配置相应的错误页面error_page

    1. 创建自己的404.html页面 2.更改nginx.conf在http定义区域加入: fastcgi_intercept_errors on; 3.更改nginx.conf(或单独网站配置文件, ...

  8. C# 中Join( )的理解

    在MSDN中对Join( )的解释比较模糊:在继续执行标准的 COM 和 SendMessage 消息泵处理期间,阻塞调用线程(线程A),直到某个线程终(线程B)止为止. 首先来看一下有关的概念: 我 ...

  9. boot loader:grub入门[转]

    Boot Loader: Grub 在看完了前面的整个启动流程,以及核心模块的整理之后,你应该会发现到一件事情, 那就是『 boot loader 是加载核心的重要工具』啊!没有 boot loade ...

  10. 认识CPU Cache

    http://geek.csdn.net/news/detail/114619 7个示例科普CPU Cache:http://coolshell.cn/articles/10249.html Linu ...