Writing view view request and response correlation function

Django view function view

  A view function (class), referred to as a view, Python is a simple function (class) that accepts the request and returns Web Web response.

  The response may be a page's HTML content, a redirect, a 404 error, an XML document, or a picture.

  No matter what the view itself contains logic, it must return a response. Write the code where it does not matter, as long as it is in your current directory project. In addition there is no more requirement - and you can say, "There's nothing magical place." In order to put the code in the name somewhere, we agreed to a vulgar place the view in the project (project) or application (app) directory views.pyfile.

A simple view

  Here is a view returns the current date and time in the form of an HTML document:

from django.http import HttpResponse
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)

  Let's explain the above code line by line:

  • First of all, from the django.httpimported module HttpResponseclass, as well as the Python datetimelibrary.

  • Then, we define the current_datetimefunction. It is the view function. Each view function using HttpRequestan object as the first parameter, and is commonly known request.

    Note that the name of the view function does not matter; do not need a unified approach to naming names, in order to allow Django to recognize it. We will name it current_datetime, because this name can more accurately reflect the function it implements.

  • This view will return an HttpResponseobject that contains the generated response. Each view function is responsible for returning an HttpResponseobject.

  Django uses request and response state objects to pass through the system.

  When a browser requests a page from the server, Django create an HttpRequest object that contains metadata about the request. Then, Django loads the appropriate view, this view HttpRequest object to function as the first parameter.

  Each view is responsible for returning an HttpResponse object.

    img

  视图层,熟练掌握两个对象即可:请求对象(request)和响应对象(HttpResponse)

CBV和FBV

  FBV(function base views) 就是在视图里使用函数处理请求。

    之前都是FBV模式写的代码,所以就不写例子了。

  CBV(class base views) 就是在视图里使用类处理请求。

  Python是一个面向对象的编程语言,如果只用函数来开发,有很多面向对象的优点就错失了(继承、封装、多态)。所以Django在后来加入了Class-Based-View。可以让我们用类写View。这样做的优点主要下面两种:

  1. 提高了代码的复用性,可以使用面向对象的技术,比如Mixin(多继承)
  2. 可以用不同的函数针对不同的HTTP方法处理,而不是通过很多if判断,提高代码可读性

书写一个FBV(函数类)

FBV(function base views) 就是在视图里使用函数处理请求。

from django.shortcuts import render,HttpResponse,redirect
def cs(request):
    return redirect('/cs1/')  #重定向  redirect(路径)

书写一个CBV(对象)

CBV(class base views) 就是在视图里使用类处理请求。

最后一步源码

 http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

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_allowed
    return handler(request, *args, **kwargs)

通过剖析源码 我们可以在分发前执行我们的逻辑

from django.views import View
class LoginView(View):
    # def dispatch(self, request, *args, **kwargs):
    #     print('xx请求来啦!!!!')请求来之前  但不知道是什么方法前执行
    #     ret = super().dispatch(request, *args, **kwargs)
    #     print('请求处理的逻辑已经结束啦!!!')
    #     return ret
    def get(self,request):  #处理get请求直接定义get方法,不需要自己判断请求方法了,源码中用dispatch方法中使用了反射来处理的
        print('小小小小')
        return render(request,'login.html')

    def post(self,request):
        print(request.POST)
        return HttpResponse('登录成功')

注意类请求 urls.py路由写法

url(r'^路径/', views.类名.as_view()),
url(r'^login/', views.LoginView.as_view()),

FBV(函数类) CBV(对象)加装饰器?

FBV本身就是一个函数,所以和给普通的函数加装饰器无差别

CBV(对象)加装饰器需要先将其转换为方法装饰器。Django中提供了method_decorator装饰器用于将函数装饰器转换为方法装饰器。

代码如下

装饰器装饰FBV

FBV本身就是一个函数,所以和给普通的函数加装饰器无差

def wrapper(func):
    def inner(*args, **kwargs):
        start_time = time.time()
        ret = func(*args, **kwargs)
        end_time = time.time()
        print("used:", end_time-start_time)
        return ret
    return inner


# FBV版添加班级
@wrapper
def add_class(request):
    if request.method == "POST":
        class_name = request.POST.get("class_name")
        models.Classes.objects.create(name=class_name)
        return redirect("/class_list/")
    return render(request, "add_class.html")

装饰器装饰CBV

类中的方法与独立函数不完全相同,因此不能直接将函数装饰器应用于类中的方法 ,我们需要先将其转换为方法装饰器。Django中提供了method_decorator装饰器用于将函数装饰器转换为方法装饰器。

第一步先引入模块from django.utils.decorators import method_decorator`
第2步 加语法糖@method_decorator(wrapper)`


from django.shortcuts import render,HttpResponse
from django.views import View
from django.utils.decorators import method_decorator
def wrapper(func):
    def inner(*args, **kwargs):
        print(11111)
        ret = func(*args, **kwargs)
        print(22222)
        return ret
    return inner

# @method_decorator(wrapper,name='get')  # 方式3给get加 用的不多
class LoginView(View):

    @method_decorator(wrapper)  #方式1
    def get(self,request):
        print('小小小小')
        return HttpResponse('登录成功')

    def post(self,request):
        print(request.POST)
        return HttpResponse('登录成功')

请求相关:request 对象 属性

当一个页面被请求时,Django就会创建一个包含本次请求原信息(请求报文中的请求行、首部信息、内容主体等)的HttpRequest对象。
  Django会将这个对象自动传递给响应的视图函数,一般视图函数约定俗成地使用 request 参数承接这个对象。

  When a page is requested, Django creates an HttpRequest object of this request contains the original information.
  Django This object will be automatically passed to the view response function, general view function using convention receiving the object request parameter.

  Official Documents

path_info 返回用户访问url,不包括域名
method 请求中使用的HTTP方法的字符串表示,全大写表示。
GET 包含所有HTTP GET参数的类字典对象
POST 包含所有HTTP POST参数的类字典对象
body 请求体,byte类型 request.POST的数据就是从body里面提取到的

request.method    ——》 请求的方式 8种  GET POST PUT DELETE OPTIONS
        request.GET       ——》 字典  url上携带的参数
        request.POST      ——》 字典  form表单通过POST请求提交的数据
        request.path_info ——》 URL路径 不带参数 
        request.body      ——》 请求体
        request.FILES       上传的文件  {}
        request.COOKIES     cookie
        request.session     session
        request.META            请求头

Response correlation: HTTPResponse objects

from django.shortcuts import render,HttpResponse,redirect
HTTPResponse('字符串') #返回字符串
render(request,'xx.html')#返回html页面

redirect 重定向
def cs(request):
    return redirect('/cs1/')  #重定向到url为cs1的地址

def cs1(request):
    return HttpResponse('666') #返回字符串666
    
def cs1(request):
    render(request,'xx.html')#返回html页面

Guess you like

Origin www.cnblogs.com/saoqiang/p/12381793.html