(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> ...
随机推荐
- OpenCV是什么?
OpenCV其实就是一对C和C++语言的源代码文件,这些源代码文件中实现了许多常用的计算机视觉算法.例如C借口函数cvCanny()实现了Canny边缘提取算法.可以直接将这些源代码添加到我们自己的项 ...
- 三部曲一(数据结构)-1022-Gold Balanced Lineup
Gold Balanced Lineup Time Limit : 4000/2000ms (Java/Other) Memory Limit : 131072/65536K (Java/Othe ...
- NSFetchedResultsControllerDelegate不执行
熬了2 ,3个小时 才解决这个问题 在进行IM 设置时候 NSFetchRequest *request=[NSFetchRequest fetchRequestWithEntityName:@&q ...
- 如何垂直居中一个<img>?
<!doctype html><html> <head> <meta charset="UTF-8"> <meta name= ...
- angularjs 迭代器
angularjs 迭代器可以使用管道字符(|)添加到表达式和指令中. 有以下五种转换数据的迭代器: (1)currency-格式化数字为货币格式. (2)filter-从数组中选择一个一个子集. ( ...
- 引用计数gc机制使用不当导致内存泄漏
上一篇文章找同事review了一下,收到的反馈是铺垫太长了,我尽量直入正题,哈哈 最近dbd压测时发现内存泄漏,其实这个问题去年已经暴露了,参见这篇博客[压测周].当时排查不够仔细,在此检讨下.关于d ...
- java.lang.Enum<E extends Enum<E>>
public enum Direction { L, LU, U, RU, R, RD, D, LD, STOP, JUMP;} for(Direction d: Direction.values() ...
- Python 爬虫学习 urllib2
用urllib2抓取被限制的网站页面 # coding:utf-8 import urllib2 url = "http://blog.csdn.net/troubleshooter&quo ...
- 字符串匹配--manacher算法模板
manacher算法主要是处理字符串中关于回文串的问题的,它可以在 O(n) 的时间处理出以字符串中每一个字符为中心的回文串半径,由于将原字符串处理成两倍长度的新串,在每两个字符之间加入一个特定的特殊 ...
- Windows 10的TPM模块到底是不是美国全球监控体系的奠基石?
http://bbs.pediy.com/showthread.php?t=202638 http://www.zhihu.com/topic/19671262/newest 2015年3月18日,微 ...