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特点
能够直接根据请求方式的不同而匹配对应的方法执行
url(r'^login/',views.My_login.as_view())from django.views import Viewclass My_login(View):def get(self,request):return HttpResponse('GET')def post(self,request):return HttpResponse('POST')
CBV与FBV在路由匹配上本质是一样的
CBV源码解析
def as_view(cls, **initkwargs):"""Main entry point for a request-response process."""for key in initkwargs:if key in cls.http_method_names: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.getself.request = requestself.args = argsself.kwargs = kwargsreturn self.dispatch(request, *args, **kwargs)view.view_class = clsview.view_initkwargs = initkwargs# take name and docstring from classupdate_wrapper(view, cls, updated=())# and possible attributes set by decorators# like csrf_exempt from dispatchupdate_wrapper(view, cls.dispatch, assigned=())return view自定义的类被当做一个参数传入后,调用self.dispatch方法http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']在dispatch中获取请求方法,到http_method_names中匹配是否合规合规则将该方法进行属性查找,找到后执行,找不到则与不合规匹配一样报warning(405)def dispatch(self, request, *args, **kwargs):# Try to dispatch to the right method; if a method doesn't exist,# defer to the error handler. Also defer to the error handler if the# request method isn't on the approved list.if request.method.lower() in self.http_method_names:handler = getattr(self, request.method.lower(), self.http_method_not_allowed)else:handler = self.http_method_not_allowedreturn handler(request, *args, **kwargs)报错部分def http_method_not_allowed(self, request, *args, **kwargs):logger.warning('Method Not Allowed (%s): %s', request.method, request.path,extra={'status_code': 405, 'request': request})return http.HttpResponseNotAllowed(self._allowed_methods())
