Django的视图系统
12.7.1 CBV和FBV
-
class based view
-
function based view 函数视图
-
基本写法和定义
from django.views import View class AddPublisher(View): def get(self,request): return response def post(self,request): return redircet('/publisher_list/') -
urls文件中的使用urlpatterns = url(r'^add_pub/', views.AddPublsher.as_view())
12.7.2 as_view的流程
- 项目启动 加载
url.py时,执行类.as_view()从而得到一个view函数(as_view()函数里封装着一个view函数,并且还会返回一个view) - 请求到来的时候会执行view函数
- 通过self实例化类
self.request = request
- 通过self实例化类
- 执行
self.dispatch(request,*args,**kwargs)http_method_names可以执行的请求方式- 如果允许,会通过反射获取到对应请求方式的方法并赋值给 handle
- 如果不被允许, 则执行
self.http_method_not_allowed,并赋值给 handle - handle执行结果就是执行自定义的类的每个函数
12.7.3 视图加装饰器
-
FBV 直接加装饰器
-
CBV
from django.utils.decorators import method_decorator-
加载方法上
@method_decorator(timer) def get(self,request,*args,**kwargs): #处理get请求 -
加载dispatch方法上
- dispatch是父类中的一个方法,其内部决定 request的调用与否
@method_decorator(timer) def dispatch(self,request,*args,**Kwargs): ret = super().dispatch(request,*args,**kwargs) return ret -
加在类上
@method_decorator(timer,name='post') @method_decorator(timer,name='get') @method_decorator(timer,name='dispatch')(推荐) class AddPublisher(View): -
使用和不使用
method_decorator的区别- 如果不加
method_decorator闭包里需要传递self参数,第二个参数才是request参数
def timer(func): def inner(request, *args, **kwargs): start = time.time() ret = func(request, *args, **kwargs) print("函数执行的时间是{}".format(time.time() - start)) return ret return inner- 加上之后,被修饰函数是绑定方法,传递过程中不需要再传递self参数
- 如果不加
-
12.7.4 request对象
- 属性
-
request.scheme表示请求方案的字符串 https或http -
request.COOKIES字典格式 包含所有的cookie -
request.session一个类似于字典的对象 -
request.method- 请求中使用的HTTP方法的字符串表示,全大写表示。
GET POST DELETE OPTIONS PUT TRACE HEAD PATCH
-
request.GET- 包含所有HTTP POST参数的类字典对象
-
request.POST- 包含所有HTTP POST参数的类字典对象
- 属性
enctype是applicaion/x-www-form-urlencoded表单提交 这是默认的
-
request.path_infoURL的路径 不包括ip和端口 也不包含参数 -
request.body- byte类型 request
-
request.FILES- 需要提交的表单,属性
enctype必须是multpart/form-data,才可以提交文件
<form action="" method="post" enctype="multpart/form-data"> <input type="file" name='f1'> <button> 上传 </button> </form>- 之后在视图函数中可以正常接收文件,
f1.name可以获取文件名称
def recv(request): if request.method == 'POST': f1 = request.FILES.get('f1') with open(f1.name,'wb'): for i in f1.chunks(): #相当于按块下载,也可以自己设置KB来下载 f.write(i) - 需要提交的表单,属性
-
request.META- 一个标准的python字典,里面包含了http的所有头部信息
- 头部信息都有变化,将所有字符转换为大写,用下划线替换任何连字符并
HTTP_在名称中添加前缀,例如,调用的标头X-Bender将映射到META密钥HTTP_X_BENDER。
- 方法
request.get_full_path()完整URL的路径, 不包含ip和端口但是包含参数request.is_ajax()判断是否是ajax请求request.get_host()获取主机的IP和端口
12.7.5 response对象
-
基本分类
Httpresponse('字符串') --->'字符串' render(request,'模板的文件名',{k1:v1}) ----> 范围一个完整的HTML页面 redirect('重定向的地址') ---->重定向 location:地址 -
JsonResonse- 作用:将信息序列化输入到网页端
from django.http.resonse import JsonResponse JsonResponse({'name':'alex','age':12}) #如果要序列化列表,则需要设置 safe参数为False JsonResponse([1,2,3,4],safe=False)- 直接使用日常用的json也是可以的,区别是使用json序列化后的
Content-Type:text/html; charset=utf-8这个属性意味着不支持反序列化,对后续操作造成不方便 - 即使使用了json我们可以通过设置
Content-Type的值来让json的结果同样支持序列化
ret = HttpResponse(json.dump(data)) ret['Content-Type'] = 'application/json' -
TemplateResponse- 返回的是一个对象 可以在中间件后续再进行一些操作。

浙公网安备 33010602011771号