第九章 Django的视图

  • 9.1. View

  • Django使用请求和响应对象来通过系统传递状态。

  • 当浏览器向服务端请求一个页面时,Django创建一个HttpRequest对象,该对象包含关于请求的元数据。

  • 然后,Django加载相应的视图,将这个HttpRequest对象作为第一个参数传递给视图函数。

  • 每个视图负责返回一个HttpResponse对象。

9.1.1 views.py

  • 一个视图函数(类),简称视图,是一个简单的Python 函数(类),它接受Web请求并且返回Web响应。

  • 响应可以是一张网页的HTML内容,一个重定向,一个404错误,一个XML文档,或者一张图片。

  • 无论视图本身包含什么逻辑,都要返回响应。代码写在哪里也无所谓,只要它在你当前目录下面。除此之外没有更多的要求了——可以说“没有什么神奇的地方”。为了将代码放在某处,大家约定成俗将视图放置在项目(project)或应用程序(app)目录中的名为views.py的文件中。

9.1.2 FBV和CBV

  • FBV:function based view

  • CBV:class based view。api开发

 1. CBV语法

  • 处理请求的逻辑清晰

# cbv示例
from django.views import View
class AddPublisher(View):
  def get(self, request, *args, **kwargs):
    """处理get请求"""
    return response
  def post(self, request, *args, **kwargs):
    """处理post请求"""
    return response 
  def delete(self, request, *args, **kwargs):
    """处理post请求"""
    return response 
  • 使用
# urls.py
url('^add_publisher/', views.AddPublisher.as_view())
  • as_view流程

  1. 项目加载urls.py时,执行类 as_view() —> view函数

  2. 请求到来时,执行view函数

    1. 实例化类—> self

    2. self.request=request

    3. 执行self.dispatch(request, *args, **kwargs)

  3. 执行self.dispatch(request, *args, kwargs)**方法

    1. 判断请求方式是否被允许(不允许: 405)

      • 允许:通过反射获取对应请求方式的方法—> 赋值给handler

        • return handlder(request, *args, **kwargs)

      • 不允许:self.http_method_not_allowed —> handler

        • return handlder(request, *args, **kwargs)

    2. 执行handler(request, *args, **kwargs)

9.2. 视图加装饰器

  • 使用CBV时要注意,请求过来后会先执行dispatch()这个方法,如果需要批量对具体的请求处理方法,如get,post等做一些操作的时候,这里我们可以手动改写dispatch方法,这个dispatch方法就和在FBV上加装饰器的效果一样。

9.2.1 视图函数加装饰器

# FBV加装饰器
# 装饰器函数
from time import time
def timer(func):
      def inner(*args, **kwargs):
        start = time()
        ret = func(*args, **kwargs)
        print(time() - start)
        return ret
    return inner
# 给视图函数加装饰器
@timer
def fun():
  pass

9.2.2 给类方法加装饰器

1. 给某个方法加

  • 导入View类、导入method_decorator

  • 类中定义对应请求的方法

  • 使用带参数的装饰器

# CBV加装饰器
from django.utils.decorators import method_decorator
from django.views import View
class AddPublisher(View):
      def get(self, request):
        # 处理get请求
        return response
      # 给post方法加装饰器
      @method_decorator(timer)
      def post(self, request):
            # 处理post请求
            return response 
      def delete(self, request):
            # 处理post请求
            return response 

2. 给dispatch加

  • 给dispatch加装饰器,所有方法都会生效

from django.views import method_decorator
@method_decorator(timer)
def dispatch(self, request, *args, **kwargs):
      ret = super().dispatch(request, *args, **kwargs)
    return ret

3. 在类上加

  • 加在类上,只对指定的name方法有效

from django.views import method_decorator
@method_decorator(timer, name='get')
@method_decorator(timer, name='post')
class AddPublisher(View):
      def get(self, request):
        # 处理get请求
        return response
      def post(self, request):
            # 处理post请求
            return response 
      def delete(self, request):
            # 处理post请求
            return response 

4. 在类上加

  • 指定name='dispatch',所有方法都生效

from django.views import method_decorator
@method_decorator(timer, name='dispatch')
class AddPublisher(View):
      def get(self, request):
        # 处理get请求
        return response
      def post(self, request):
            # 处理post请求
            return response 
      def delete(self, request):
            # 处理post请求
            return response 

Note(2)

  • 不使用导入method_decorator时

  1. method_decorator

    • 是一个函数,其作用:Converts a function decorator into a method decorator

  2. 传入的参数将会发生变化

 

9.3. reuqest对象

  • django将请求报文中的请求行、头部信息、内容主体封装成 HttpRequest 类中的属性

  • 除了特殊说明的之外,其他均为只读的。

9.3.1 request对象的属性

  • 封装请求中的所有内容

  • 常用的是前5种


属性
含义
1 request.path_info/path 返回用户访问url,不包括域名
2 request.method 请求中使用的HTTP方法的字符串表示,全大写表示。
3 request.GET 包含所有HTTP GET参数的类字典对象,QuerySet
4 request.POST 包含所有HTTP POST参数的类字典对象QuerySet
5 request.body http请求体byte类型 request.POST的数据就是从body里面提取到的
6 request.scheme 请求方案,通常为http 或 https
7 request.encoding 编码方式,为None则则表示使用 DEFAULT_CHARSET 的设置,默认为 'utf-8')。
8 request.FILES 上传的文件
9 request.META 获取请求头,全大写,加HTTP, - 变称_s
10 request.user Django提供的auth模块,获得当前登陆的用户
11 request.session  
12 request.COOKIES  

猜你喜欢

转载自www.cnblogs.com/xu1296634150/p/12922614.html