render
返回html页面,并且还可以给html页面传值
redirect
重定向
HttpResponse
返回字符串类型

视图函数必须要返回一个HttpResponse对象

JsonResponse对象

传字典
return JsonResponse(user_dic,json_dumps_params={‘ensure_ascii’:False})
传其他
return JsonResponse(USER_LIST,safe=False)

request对象方法补充

request.method
request.POST
request.GET
request.FILES
request.body #原生的二进制数据
request.path
request.get_full_path #完整的url和后面的参数

FBV与CBV

CBV特点
能够直接根据请求方式的不同而匹配对应的方法执行

  1. url(r'^login/',views.My_login.as_view())
  2. from django.views import View
  3. class My_login(View):
  4. def get(self,request):
  5. return HttpResponse('GET')
  6. def post(self,request):
  7. return HttpResponse('POST')

CBV与FBV在路由匹配上本质是一样的

CBV源码解析

  1. def as_view(cls, **initkwargs):
  2. """
  3. Main entry point for a request-response process.
  4. """
  5. for key in initkwargs:
  6. if key in cls.http_method_names:
  7. raise TypeError("You tried to pass in the %s method name as a "
  8. "keyword argument to %s(). Don't do that."
  9. % (key, cls.__name__))
  10. if not hasattr(cls, key):
  11. raise TypeError("%s() received an invalid keyword %r. as_view "
  12. "only accepts arguments that are already "
  13. "attributes of the class." % (cls.__name__, key))
  14. def view(request, *args, **kwargs):
  15. self = cls(**initkwargs)
  16. if hasattr(self, 'get') and not hasattr(self, 'head'):
  17. self.head = self.get
  18. self.request = request
  19. self.args = args
  20. self.kwargs = kwargs
  21. return self.dispatch(request, *args, **kwargs)
  22. view.view_class = cls
  23. view.view_initkwargs = initkwargs
  24. # take name and docstring from class
  25. update_wrapper(view, cls, updated=())
  26. # and possible attributes set by decorators
  27. # like csrf_exempt from dispatch
  28. update_wrapper(view, cls.dispatch, assigned=())
  29. return view
  30. 自定义的类被当做一个参数传入后,调用self.dispatch方法
  31. http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
  32. dispatch中获取请求方法,到http_method_names中匹配是否合规
  33. 合规则将该方法进行属性查找,找到后执行,找不到则与不合规匹配一样报warning405
  34. def dispatch(self, request, *args, **kwargs):
  35. # Try to dispatch to the right method; if a method doesn't exist,
  36. # defer to the error handler. Also defer to the error handler if the
  37. # request method isn't on the approved list.
  38. if request.method.lower() in self.http_method_names:
  39. handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
  40. else:
  41. handler = self.http_method_not_allowed
  42. return handler(request, *args, **kwargs)
  43. 报错部分
  44. def http_method_not_allowed(self, request, *args, **kwargs):
  45. logger.warning(
  46. 'Method Not Allowed (%s): %s', request.method, request.path,
  47. extra={'status_code': 405, 'request': request}
  48. )
  49. return http.HttpResponseNotAllowed(self._allowed_methods())