Django—基本视图-View

  • 根视图View类


    @classonlymethod
     def as_view(cls, **initkwargs):
     """Main entry point for a request-response process."""
     # 参数检查
     for key in initkwargs:
     if key in cls.http_method_names: # 参数名不能是指定http的方法名
     raise TypeError("You tried to pass in the %s method name as a "
     "keyword argument to %s(). Don't do that."
     % (key, cls.__name__))
     if not hasattr(cls, key): # 参数名必须是类已有属性
     raise TypeError("%s() received an invalid keyword %r. as_view "
     "only accepts arguments that are already "
     "attributes of the class." % (cls.__name__, key))
     # 视图处理函数
     def view(request, *args, **kwargs):
     self = cls(**initkwargs) # 实例化当前类的对象
     if hasattr(self, 'get') and not hasattr(self, 'head'):
     self.head = self.get
     self.setup(request, *args, **kwargs)
     if not hasattr(self, 'request'):
     raise AttributeError(
     "%s instance has no 'request' attribute. Did you override "
     "setup() and forget to call super()?" % cls.__name__
     )
     # 方法派发
     return self.dispatch(request, *args, **kwargs)
     view.view_class = cls
     view.view_initkwargs = initkwargs
     # take name and docstring from class
     update_wrapper(view, cls, updated=())
     # and possible attributes set by decorators
     # like csrf_exempt from dispatch
     update_wrapper(view, cls.dispatch, assigned=())
     return view # 返回视图函数

    def dispatch(self, request, *args, **kwargs):
     #检查请求方法是不是在http_method_names中包含
     #http_method_names包括八种方法:['get', 'post', 'put', 'patch', 'delete', 'head', 
     #'options', 'trace']
     if request.method.lower() in self.http_method_names:
     handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
     else: #不在调用http_method_not_allowed报错
     handler = self.http_method_not_allowed
     #调用和请求方法同名的实例方法处理用户请求,实例方法需要用户自己定义
     return handler(request, *args, **kwargs)

    from django.views import View
    class IndexView(View):
     def get(self,request):
     return HttpResponse("get")
     def post(self,request):
     return HttpResponse("post")
     def put(self,request):
     return HttpResponse("put")
     def delete(self,request):
     return HttpResponse("delete")
发布了199 篇原创文章 · 获赞 6 · 访问量 2423

猜你喜欢

转载自blog.csdn.net/piduocheng0577/article/details/105036315