概念

  • 一个视图函数,简称视图,是一个简单的Python函数,用于接受Web请求并返回Web响应。
  • 通常将视图函数写在project或app目录中的名为views.py文件中

简单的实例

 

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)

 

 

 

定义方式

CBV

  可读性更加强,将post 和 get请求分开用两个方法定义

  记得更改urls中的调用方式

实例

# CBV版添加班级
from django.views import View
class AddClass(View):
  
  def get(self, request):
  return render(request, "add_class.html")
  
  def post(self, request):
    class_name = request.POST.get("class_name")
    models.Classes.objects.create(name=class_name)
  return redirect("/class_list/")

# urls.py中
url(r'^add_class/$', views.AddClass.as_view()),

FBV

  代码更加简洁,但是可读性差,urls 中的调用方式简单

实例

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 源码剖析 以及 重写方法

CBV 源码顺序

  通过调用 View 中的 as_view() 调用  view 再调用 dispatch 

  本质上执行的则是 dispatch 

Django 视图系统

重写 dispatch()   

利用 super 执行父类中的 dispatch 方法后再执行自己的

重写dispatch函数可以实现

  所有类型的函数执行的时候都做一个固定操作的插入

from django.shortcuts import render,HttpResponse
from django.views import View

class LoginView(View):
  defdispatch(self, request, *args, **kwargs): ... ret = super().dispatch(self, request, *args, **kwargs) return ret def get(self): ... return HttpResponse("ok")

给视图加装饰器 

使用装饰器装饰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

类需要特殊的装饰器进行一次封装才行

from django.utils.decorators import method_decorator

@method_decorator(wrapper)

 

给CBV加装饰器可以有多种方式

  给 类 加装饰器

from django.utils.decorators import method_decorator

@method_decorator(check_login, name="get")
@method_decorator(check_login, name="post")
class HomeView(View):

  def dispatch(self, request, *args, **kwargs):
    return super(HomeView, self).dispatch(request, *args, **kwargs)
    
  def get(self, request):
    return render(request, "home.html")
    
  def post(self, request):
    print("Home View POST method...")
    return redirect("/index/")

 

  给 post 或者 get 加装饰器

from django.utils.decorators import method_decorator


class HomeView(View):
    
  def dispatch(self, request, *args, **kwargs)    
    return super(HomeView, self).dispatch(request, *args, **kwargs)

  def get(self, request):
    return render(request, "home.html")

  @method_decorator(check_login)
  def post(self, request):
    print("Home View POST method...")
    return redirect("/index/")

 

  给 dispatch 加装饰器

  CBV中首先执行的就是dispatch,这样相当于给get和post方法都加上了装饰器

from django.utils.decorators import method_decorator


class HomeView(View):    
    
  @method_decorator(check_login)
  def dispatch(self, request, *args, **kwargs):
    return super(HomeView, self).dispatch(request, *args, **kwargs)

  def get(self, request):
    return render(request, "home.html")

  def post(self, request):
    print("Home View POST method...")
    return redirect("/index/")

常用对象

request对象

  常用的

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

  不常用的特么好多

 1 1.HttpRequest.get_host()
 2 
 3   根据从HTTP_X_FORWARDED_HOST(如果打开 USE_X_FORWARDED_HOST,默认为False)和 HTTP_HOST 头部信息返回请求的原始主机。
 4    如果这两个头部没有提供相应的值,则使用SERVER_NAME 和SERVER_PORT,在PEP 3333 中有详细描述。
 5 
 6   USE_X_FORWARDED_HOST:一个布尔值,用于指定是否优先使用 X-Forwarded-Host 首部,仅在代理设置了该首部的情况下,才可以被使用。
 7 
 8   例如:"127.0.0.1:8000"
 9 
10   注意:当主机位于多个代理后面时,get_host() 方法将会失败。除非使用中间件重写代理的首部。
11 
12  
13 
14 2.HttpRequest.get_full_path()
15 
16   返回 path,如果可以将加上查询字符串。
17 
18   例如:"/music/bands/the_beatles/?print=true"
19 
20  
21 
22 3.HttpRequest.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)
23 
24   返回签名过的Cookie 对应的值,如果签名不再合法则返回django.core.signing.BadSignature。
25 
26   如果提供 default 参数,将不会引发异常并返回 default 的值。
27 
28   可选参数salt 可以用来对安全密钥强力攻击提供额外的保护。max_age 参数用于检查Cookie 对应的时间戳以确保Cookie 的时间不会超过max_age 秒。
29 
30         复制代码
31         >>> request.get_signed_cookie('name')
32         'Tony'
33         >>> request.get_signed_cookie('name', salt='name-salt')
34         'Tony' # 假设在设置cookie的时候使用的是相同的salt
35         >>> request.get_signed_cookie('non-existing-cookie')
36         ...
37         KeyError: 'non-existing-cookie'    # 没有相应的键时触发异常
38         >>> request.get_signed_cookie('non-existing-cookie', False)
39         False
40         >>> request.get_signed_cookie('cookie-that-was-tampered-with')
41         ...
42         BadSignature: ...    
43         >>> request.get_signed_cookie('name', max_age=60)
44         ...
45         SignatureExpired: Signature age 1677.3839159 > 60 seconds
46         >>> request.get_signed_cookie('name', False, max_age=60)
47         False
48         复制代码
49          
50 
51 
52 4.HttpRequest.is_secure()
53 
54   如果请求时是安全的,则返回True;即请求通是过 HTTPS 发起的。
55 
56  
57 
58 5.HttpRequest.is_ajax()
59 
60   如果请求是通过XMLHttpRequest 发起的,则返回True,方法是检查 HTTP_X_REQUESTED_WITH 相应的首部是否是字符串'XMLHttpRequest'61 
62   大部分现代的 JavaScript 库都会发送这个头部。如果你编写自己的 XMLHttpRequest 调用(在浏览器端),你必须手工设置这个值来让 is_ajax() 可以工作。
63 
64   如果一个响应需要根据请求是否是通过AJAX 发起的,并且你正在使用某种形式的缓存例如Django 的 cache middleware, 
65    你应该使用 vary_on_headers('HTTP_X_REQUESTED_WITH') 装饰你的视图以让响应能够正确地缓存。
66 
67 请求相关方法
View Code

相关文章: