(1)as_view() (2)在urls.py里面出现的pk是怎么回事 (3)RetrieveAPIView表示什么
下面的代码都是我从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表示什么的更多相关文章
- [django]urls.py 中重定向
Django 1.5 有时候需要对一个链接直接重定向,比如首页啥的重定向到一个内容页等等,在views.py 中可以设定,如果没有参数啥的在urls.py 中设定更加方面 from django.vi ...
- 第三百零四节,Django框架,urls.py模块,views.py模块,路由映射与路由分发以及逻辑处理——url控制器
Django框架,urls.py模块,views.py模块,路由映射与路由分发以及逻辑处理——url控制器 这一节主讲url控制器 一.urls.py模块 这个模块是配置路由映射的模块,当用户访问一个 ...
- 4.对urls.py的解释
解释: 路由配置文件(URL分发器),它的本质是URL模式以及要为该URL模式调用的视图函数之间的映射表.就是以这种方式告诉Django对于每个URL的处理类.Django启动的时候回去加载urls. ...
- 二 Django框架,urls.py模块,views.py模块,路由映射与路由分发以及逻辑处理——url控制器
Django框架,urls.py模块,views.py模块,路由映射与路由分发以及逻辑处理——url控制器 这一节主讲url控制器 一.urls.py模块 这个模块是配置路由映射的模块,当用户访问一个 ...
- django-3-视图(views.py)与网址(urls.py)
视图与网址 操作文件:urls.py.views.py urls.py 作用:用于处理前台的链接(如前台访问:127.0.0.1:8080/index/1212/21212),其实永远访问的是同一个文 ...
- django搭建web (二) urls.py
URL模式: 在app下的urls.py中 urlpatterns=[ url(正则表达式,view函数,参数,别名,前缀)] urlpatterns=[ url(r'^hello/$',hello. ...
- Django入门三之urls.py重构及参数传递
1. 内部重构 2. 外部重构 website/blog/urls.py website/website/urls.py 3. 两种参数处理方式 -1. blog/index/?id=1234& ...
- 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(). ...
- urls.py的配置[路由配置]
urls.py的配置[路由配置] Get请求与Post请求的方式 get请求: (1)地址栏输入url (2)<a href="请求url">点击</a> ...
随机推荐
- iOS学习之NSPredictae及搜索框的实现
NSPredicate Predicate 即谓词逻辑, Cocoa框架中的NSPredicate用于查询,作用是从数据堆中根据条件进行筛选.计算谓词之后返回的结果永远为BOOL类型的值,当程序使用谓 ...
- jQuery里ajax的用法
$.ajax({ type:'post',//这里页面数据发送请求的方式可以为post和get cache:'false ', //这里可以为false或者true 是否要缓存 ,默认为false u ...
- WindowsPhone开发—— 使用手绘图片做景区导览地图
前些日子在做景区App遇到需求,使用手绘图片做一个简易的地图,支持放大缩小平移以及显示景点Mark,安卓上可以使用一个叫做“mAppWidget”的开源库来完成,WP上有人建议用ArcGIS,但是考虑 ...
- js实现时间控件
<html><head> <title>时间控件</title></head><body > <input name=&q ...
- js窗口边缘滑入滑出效果-初级代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- for循环相关
循环语句是指令式编程的常见语句,Scala对其加以改进,成为适应函数式风格的利器. for循环中的变量,没有val或者var,是因为变量的类型,完全是集合中的元素的类型.作用域持续到括号结束. 在sc ...
- Recyclerview使用系列教材
Recylerview越来越多的人使用,本人录制了一套课程,欢迎大家观看,录制的比较仓促,第一课讲解的课程目录有点问题,请大家谅解,目录请看视频外该课程介绍的内容即可. 该课程付费课程包含: 1-Re ...
- |原创|unity 4.3 2D功能SpriteRenderer修改颜色的方法
4.3增加了不少2D功能,然后实在没有找到有人分享,在国外查资料研究一下午然后给个简单的教程 ===================================================== ...
- 《C与指针》第九章练习
本章问题 1.C语言缺少显示的字符串数据类型,这是一个优点还是一个缺点? answer: (这个问题存在争论(尽管我有一个结论))目前这个方法的优点是字符数组的效率和访问的灵活性,它的缺点是有可能引起 ...
- C/C++的四大内存分区 分类: C/C++ 2015-05-09 01:36 163人阅读 评论(0) 收藏
导读 正确的理解C/C++程序的内存分区,是合格程序猿的基本要求. 网络上流形两大版本内存分区,分别为: 1. 五大内存分区:堆.栈.全局/静态存储区.自由存储区和常量存储区. 2. 五大内存分区:堆 ...