下面的代码都是我从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. Mac上常用的一些命令

    FTP:先cd到要传的文件的文件夹>ftp 10.214.111.1cd到上传的ftp文件put 文件名 虚拟环境cd myproject. venv/bin/activate 激活sudo p ...

  2. C++ Daily 《4》----一个简单的 int to string 的方法

    经常会在项目中用到 int to string, 之前一般用C语言的 sprintf, 发现C++ 中的 ostringstream 可以轻松完成这个任务. #include <iostream ...

  3. lua class(table)

    自己看吧: Base = {x = 0,y = 0} ---原型表 Base.name = "luohai"Base.age = 22Base.sex = "man&qu ...

  4. 利用pip8.1.2 安装django1.9.7

    把python2升级到python3之后,利用pip安装django1.9.7时报错: DistributionNotFound: The 'pip==7.1.0' distribution was ...

  5. position置顶或某固定位置 兼容ie6ie7

    用absolute来模拟fixed效果: /*相当于正常的position:fixed;top:0 */.sl_fixed_top{bottom:auto;top:0;_bottom:auto;_to ...

  6. linux C之access函数(转-追梦的小鸟)

    access():判断是否具有存取文件的权限 相关函数    stat,open,chmod,chown,setuid,setgid表头文件    #include<unistd.h>定义 ...

  7. POJ 2893 M × N Puzzle(树状数组求逆序对)

                                                               M × N Puzzle Time Limit: 4000MS   Memory ...

  8. MongoDB学习笔记二:创建、更新及删除文档

    插入并保存文档 对目标集使用insert方法插入一个文档: > db.foo.insert({"bar" : "baz"}) 这个操作会给文档增加一个&q ...

  9. Python学习笔记——Day5(转载)

    python 编码转换 主要介绍了python的编码机制,unicode, utf-8, utf-16, GBK, GB2312,ISO-8859-1 等编码之间的转换. 常见的编码转换分为以下几种情 ...

  10. 微信自定义菜单view类型获取openid访问网页

    用户点击view类型按钮后,微信客户端将会打开开发者在按钮中填写的url值 (即网页链接),达到打开网页的目的,但是view不能获取用户的openid,需与网页授权获取用户基本信息接口结合使用,获得用 ...