CBV和FBV

  1. FBV(function based view )

  2. CBV(class based view)

1. CBV的定义

# 增加出版社 CBV
from django.views import View class AddPublisher(View):
def get(self, request):
pass def post(self, request):
pass

2. CBV使用

url(r'^add_publisher/', views.AddPublisher.as_view()),

3. CBV的流程

views.AddPublisher.as_view() 程序加载的时候执行  ——》 view函数

当请求到来的时候执行view函数:

  1. self = AddPublisher()

  2. self.request = request

  3. 执行self.dispatch方法

    1. 判断请求方式是否被允许

      1. 允许时,通过反射获取到AddPublisher中定义的get或者post方法 ——》handler

      2. 不允许时,self.http_method_not_allowed ——》handler

    2. 执行handler 拿到返回结果 Httpresponse对象

CBV的匹配原理:

通过查看View的源码,可以看到里面有很多提交方法

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

使用ajax的时候这些方法都可以使用

这种根据url 来匹配的方法都是通过反射(getattr)获得的. 请求发过来之后,会先走一个dispatch的方法,这个方法在View类中

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)
  request.method.lower()

将请求方式变成小写.  通过反射找到类中的对应方法

所有的框架,本质都是通过请求方式, 反射不同的函数

所以CBV的本质,其实还是用的FBV, 只不过用类封装了而已

4. 给CBV加装饰器 method_decorator

from django.utils.decorators import method_decorator

       加载到某个get 或者 post的方法上:

@method_decorator(timer)
def get(self, request):

    加在self.dispatch方法上:

@method_decorator(timer)
def dispatch(self, request, *args, **kwargs):

    加在类上:

@method_decorator(timer, name='post')
@method_decorator(timer, name='get')
class AddPublisher(View):

5. 区别

  1. 不使用method_decorator

func: <function AddPublisher.dispatch at 0x00000163735176A8>args :<app01.views.AddPublisher object at 0x00000163735F7EF0> <WSGIRequest: GET '/add_publisher/'>

  1. 使用method_decorator

func:<function method_decorator.<locals>.dec.<locals>.wrapper.<locals>.bound_func at 0x0000019664B4A378>arsgs: <WSGIRequest: GET '/add_publisher/'>

简而言之:

不使用method_decorator的时候, 第二个参数是request

使用method_decorator的时候, 第一个参数是request

request对象(常用的) **

需要记几个常用的request的属性和方法

print(request.method)   # 请求方式   GET 、POST
print(request.GET) # get的请求数据 QueryDict{} url携带参数
print(request.POST) # post的请求数据 QueryDict{} form表单提交的post数据
print(request.path_info) # 路径信息 不包含IP和端口、参数
print(request.path) #获取请求路径信息
print(request.body) #获取的是请求体里的数据

 print(request.FILES) #上传的文件
  上传文件注意事项:
  form表单的enctype:multipart/form-data;
  method="post";
  name="作为键";
  {%csrf_token%};
  取文件对象的方法: chunks();
  request.FILES中获取文件对象

print(request.is_ajax())       #是否是ajax请求
print(request.get_host())
print(request.get_full_path()) # 路径信息 + 参数

response对象

1. HttpResponse("字符串") --->字符串
2. render(request,"模板文件名",{k:v}) ----->完整的页面
3. redirect("要跳转的地址")---> 本质是响应头:Location:url
1. ret=HttpResponse() ret["Location"]=url(设置响应头) 4. JsonResponse({字典}) ContentType:application/json
1.传非字典类型的时候设置: safe=False

文件上传 

view.py

# 上传文件
def upload(request):
if request.method == 'POST':
# print(request.body)
file = request.FILES.get('f1')
with open(file.name, 'wb') as f:
for chunk in file.chunks():
f.write(chunk)
return HttpResponse('上传成功') return render(request, 'upload.html') import json
from django.http import JsonResponse def json_test(request):
data = {'name': 'alex', 'pwd': 'alexdsb'} ret = HttpResponse(json.dumps(data))
ret['Content-Type'] = 'application/json'
ret['xxx'] = 'axxx'
return ret
# return HttpResponse(json.dumps(data), content_type='application/json') # Content-Type: text/html; charset=utf-8
# return JsonResponse(data) # Content-Type: application/json

template

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
文件:<input type="file" name="f1">
<button>上传</button>
</form>
</body>
</html>

上传文件注意事项:

  1. form表单的enctype = 'multipart/form-data'

  2. request.FILES中获取文件对象

  3. 使用文件对象的chunks()

JsonResponse 作用是做序列化的

服务器--->浏览器

Contenttype:json

from django.http import JsonResponse

def json_test(request):
data = {'name': 'alex', 'pwd': 'alexdsb'} return JsonResponse(data) # Content-Type: application/json
# return HttpResponse(json.dumps(data), content_type='application/json') # Content-Type: text/html; charset=utf-8

视图系统CBV 和 response的更多相关文章

  1. Django 视图系统

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

  2. Django框架详细介绍---视图系统

    Django视图系统 1.什么是视图 在Django中,一个视图函数/类,称为视图.实质就是一个用户自定义的简单函数,用来接收WEB请求并xing响应请求,响应的内容可以是一个HTML文件.重定向.一 ...

  3. Django框架简介-视图系统

    2.3 视图系统 一个视图函数(类),简称视图,是一个简单的Python 函数(类),它接受Web请求并且返回Web响应. 响应可以是一张网页的HTML内容,一个重定向,一个404错误,一个XML文档 ...

  4. django框架--视图系统

    目录 一.视图函数的理解 二.视图函数的定位 三.请求对象HttpRequest 四.响应对象HttpResponse 一.视图函数的理解 视图函数的作用是,对指定的url执行业务逻辑,视图函数将会作 ...

  5. 运维开发笔记整理-基于类的视图(CBV)

    运维开发笔记整理-基于类的视图(CBV) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.FBV与CBV 1>.什么是FBV FBC(function base views ...

  6. django之视图系统 views.py-->主要内容(FBV和CBV、dispath、request对象和request.FILES、JsonResponse)

    一个视图函数(类),简称视图,是一个简单的Python 函数(类),它接受Web请求并且返回Web响应. 一 视图的实现可以基于两种方法: 1 基于函数的形式 FBV 使用装饰器装饰FBV  直接在上 ...

  7. Python学习(三十二)—— Django之视图系统

    转载自:http://www.cnblogs.com/liwenzhou/articles/8305104.html Django的View(视图) 一个视图函数(类),简称视图,是一个简单的Pyth ...

  8. Django之视图系统

    Django的View(视图) 一个视图函数(类),简称视图,是一个简单的python函数(类),它接受web请求并返回web响应. 响应可以是一张网页的HTML内容,一个重定向,一个404错误,或者 ...

  9. python 终极篇 --- django 视图系统

    Django的View(视图) 一个视图函数(类),简称视图,是一个简单的Python 函数(类),它接受Web请求并且返回Web响应. 响应可以是一张网页的HTML内容,一个重定向,一个404错误, ...

随机推荐

  1. sql分组统计多列值

    select BQDM,sum(case when HFBZ='0' then 1 ELSE 0 end) bxschf,sum(case when HFBZ='1' then 1 ELSE 0 en ...

  2. 如何获取app配置文件内容

    App.config: <appSettings> <add key="FCPConnection" value="Data Source=192.16 ...

  3. 【转】Powerdesigner逆向工程从sql server数据库生成pdm

    第一步:打开"控制面板"中的"管理工具" 第二步:点击"管理工具"然后双击"数据源(odbc)" 第三步:打开之后,点击 ...

  4. linux虚拟机上svn客户端连接问题

    在虚拟机上搭建好的svn,本地连接居然不行,原来是防火墙端口没开造成的. 修改配置文件:vi /etc/sysconfig/iptables # Generated by iptables-save ...

  5. 查看window端口占用并结束相关进程

    启动cmd命令行 运行netstat –ano,可列出所有端口情况 根据被占用的端口号,比如8081,运行netstat -aon|findstr "8081",找到它对应的PID ...

  6. Win8 Metro(C#)数字图像处理--2.71Sigma平滑滤波器

    原文:Win8 Metro(C#)数字图像处理--2.71Sigma平滑滤波器  [算法说明]   Sigma平滑滤波器是构造一个模板,比如3*3大小的模板,计算这个模板对应的像素的标准差d,然后 ...

  7. Android零基础入门第13节:Android Studio配置优化,打造开发利器

    原文:Android零基础入门第13节:Android Studio配置优化,打造开发利器 是不是很多同学已经有烦恼出现了?电脑配置已经很高了,但是每次运行Android程序的时候就很卡,而且每次安装 ...

  8. asp.net处理请求

    当用户通过客户端浏览器向Web服务器发出请求时,Web服务器检查所请求页的扩展名, 如果是aspx,就会启动ASP.NET引擎处理该请求.ASP.NET引擎首先会检查输出缓冲中, 是否有此页面或此页面 ...

  9. Delphi For Linux Compiler

    Embarcadero is about to release a new Delphi compiler for the Linux platform. Here are some of the k ...

  10. Globalize 1.0 发布,jQuery 的国际化插件

    分享 <关于我> 分享  [中文纪录片]互联网时代                 http://pan.baidu.com/s/1qWkJfcS 分享 <HTML开发MacOSAp ...