django视图系统

request对象

  • 常用属性和方法
      print(request) #wsgirequest对象
print(request.path) #请求路径 /index/
print(request.method) #请求方法 POST GET
print(request.POST) #post请求提交的数据<QueryDict:{'username':['root']}>
print(request.GET) #获取url中的查询参数 路径后面?a=1&b=1 返回 <QueryDict:{'a':['1'],'b':['2']}> 不是针对get请求的
print(request.body) #获取http请求消息格式的请求数据部分的内容 bytes类型 b''
print(request.META) #请求头信息
print(request.get_full_path()) #获取完整路径(包含查询参数) /index/?a=1
print(request.FILES) #上传的文件对象数据
print(request.FILES.get('file')) #返回文件对象 获取文件名可以用文件对象.name
#注意,FILES 只有在请求的方法为POST 且提交的<form> 带有enctype="multipart/form-data" 的情况下才会
包含数据。否则,FILES 将为一个空的类似于字典的对象。
print(request.POST.get('username')) #获取键对应的值
print(request.GET.get('sex')) # 获取键对应的值
#多选提交来的数据通过getlist来获取
print(request.POST.getlist('hobby')) #['2','3']

response响应

常用方法

      from django.shortcuts import render,HttpResponse,redirect
return HttpResponse('你好') #回复字符串
return render(request,'home.html') #回复html页面
#重定向方法,参数是个路径
return redirect('/home/') #封装了302状态码,以及浏览器要重定向的路径

添加响应头键值对

      ret = render(request,'home.html')
ret['a'] = 'b' #添加响应头键值对
return ret

添加响应状态码

      ret = render(request,'home.html',status=202)#render修改状态码还可以这样改
ret.status_code = 201 #添加响应状态码
return ret #回复html页面

CBV和FBV

  • 两种视图逻辑的写法方法
      FBV:全称function based view,就是基于函数来写视图逻辑
CBV:全称class based view,就是基于类来写视图
  • 基于函数的写法
      urls.py写法
url(r'^index/(\d+)',views.index) views.py写法
def index(request,xx):
if request.method == 'get':
return render(request,'index.html')
elif rquest.method == 'post':
return HttpResponse('你好')
  • 基于类的视图写法
      urls.py文件写法
#类视图的url
url(r'^login/',views.LoginView.as_view()) views.py文件写法
#需要导入View这个类,然后继承View这个类
from django.views import View
#登录需求
class LoginView(View): #继承这个View父类
#get请求 获取login页面
def get(self,request):
return render(request,'login.html') #post请求,获取post请求提交的数据,并校验等
def post(self,request):
print(request.POST)
#<QueryDict:{'uname',['wei'],'pwd':['123']}>
return render(request,'login.html')

CBV源码重点(反射)

      from django.views import View
View里面的dispatch方法中的反射逻辑,实现了不同的请求方法,找到我们视图类中的对应方法执行
#源码如下:
@classonlymethod
def as_view(cls, **initkwargs):
"""
Main entry point for a request-response process.
"""
for key in initkwargs:
if key in cls.http_method_names:
raise TypeError("You tried to pass in the %s method name as a "
"keyword argument to %s(). Don't do that."
% (key, cls.__name__))
if not hasattr(cls, key):
raise TypeError("%s() received an invalid keyword %r. as_view "
"only accepts arguments that are already "
"attributes of the class." % (cls.__name__, key)) def view(request, *args, **kwargs):
self = cls(**initkwargs)
if hasattr(self, 'get') and not hasattr(self, 'head'):
self.head = self.get
self.request = request
self.args = args
self.kwargs = kwargs
return self.dispatch(request, *args, **kwargs)
view.view_class = cls
view.view_initkwargs = initkwargs # take name and docstring from class
update_wrapper(view, cls, updated=()) # and possible attributes set by decorators
# like csrf_exempt from dispatch
update_wrapper(view, cls.dispatch, assigned=())
return 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:
#http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs) def http_method_not_allowed(self, request, *args, **kwargs):
logger.warning(
'Method Not Allowed (%s): %s', request.method, request.path,
extra={'status_code': 405, 'request': request}
)
return http.HttpResponseNotAllowed(self._allowed_methods())

FBV和CBV加装饰器

  • FBV和普通函数加装饰方式一样
      #装饰器函数
def outer(f):
def inner(request,*args,**kwargs):
print('执行之前做的事')
ret = f(request,*args,**kwargs)
print('执行之后做的事')
return ret
return inner
#使用装饰器
@outer
def books(request):
print('FBV执行了')
return HttpResponse('OK')
  • CBV加装饰器
      from django.utils.decorators import method_decorator #加装饰器需要导入这个类
from django.views import View #类视图需要导入这个View类,并继承这个父类 #装饰器函数
def outer(f):
def inner(request,*args,**kwargs):
print('执行之前')
ret = f(request,*args,**kwargs)
print('执行之后')
return ret
return inner
# 方法一 在每个方法上加装饰器
class LoginView(View):
@method_decorator(outer)
def get(self,request):
print('get方法')
return render(request,'home.html') @method_decorator(outer)
def post(self,request):
print('post方法')
return HttpResponse('ok') 方法二:统一加一个装饰器
class LoginView(View):
# 给类方法统一加装饰器,借助dispatch方法(父类的dispatch方法,
# 就是通过反射来完成不同的请求方法找到并执行我们自己定义的视图类的对应方法)
@method_decorator(outer)
def dispatch(self, request, *args, **kwargs):
print('调用方法之前')
ret = super().dispatch(request,*args,**kwargs) #重写父类的方法 返回的结果就是调用下面的get 或 post方法
print('调用方法之后')
return ret def get(self,request):
print('get方法执行啦')
return render(request,'home.html') def post(self,request):
print('post方法执行啦')
return HttpResponse('ok')
执行顺序:get方法和post方法
执行之前
调用方法之前
get方法执行啦
调用方法之后
执行之后 #方法三 在类上面加装饰器
@method_decorator(outer,name='post')
@method_decorator(outer,name='get')
class LoginView(View):
def get(self,request):
print('get方法来啦')
return render(request,'home.html') def post(self,request):
print('post方法来啦')
return HttpResponse('ok')

django学习第二天---django视图系统,基于类的视图写法,FBV和CBV加装饰器的更多相关文章

  1. Django CBV加装饰器、Django中间件、auth模块

    一. CBV加装饰器 在视图层中,基于函数的视图叫FBV(function base views),基于类的视图叫CBV(class base views).当需要用到装饰器时,例如之前的基于Cook ...

  2. django的FBV和CBV的装饰器例子

    备忘 def auth(func): def inner(request,*args,**kwargs): u = request.COOKIES.get('username111') if not ...

  3. Django---CBV和FBV的使用,CBV的流程,给视图加装饰器,Request对象方法,属性和Response对象,form表单的上传

    Django---CBV和FBV的使用,CBV的流程,给视图加装饰器,Request请求对象方法,属性和Response响应对象,form表单的上传 一丶CBV和FBV       在Django中存 ...

  4. Django-给视图加装饰器

    给FBV加装饰器 FBV:function based view FBV本身就是一个函数,所以跟普通函数加装饰器是一样的 # 装饰函数是要在APP文件中定义,本例是在app01\templatetag ...

  5. Django笔记&教程 7-1 基于类的视图(Class-based views)介绍

    Django 自学笔记兼学习教程第7章第1节--基于类的视图(Class-based views)介绍 点击查看教程总目录 1 介绍 Class-based views (CBVs) are view ...

  6. Django学习笔记之Django视图View

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

  7. Django——基于类的视图(class-based view)

    刚开始的时候,django只有基于函数的视图(Function-based views).为了解决开发视图中繁杂的重复代码,基于函数的通用视图( Funcation-based generic vie ...

  8. Django编写RESTful API(三):基于类的视图

    欢迎访问我的个人网站:www.comingnext.cn 前言 在上一篇文章中,主要讲的是请求和响应,项目里面views.py中的视图函数都是基于函数的,并且我们介绍了@api_view这个很有用的装 ...

  9. Django REST FrameWork中文教程3:基于类的视图

    我们也可以使用基于类的视图编写我们的API视图,而不是基于函数的视图.我们将看到这是一个强大的模式,允许我们重用常用功能,并帮助我们保持代码DRY. 使用基于类的视图重写我们的API 我们将首先将根视 ...

  10. django 中基于类的视图

    django 视图 分为两种: 1.  FBV  基于函数的视图      function   based  view 2.  CBV  基于类的视图         class   based  ...

随机推荐

  1. 【转帖】Linux多链路聚合技术

    https://www.jianshu.com/p/dd8587ecf54f 一般而言,在单体结构的操作系统中,一块物理磁盘会接在总线设备上,并经由总线分配 PCI-Bus 号,这个时候一个 bus  ...

  2. [转帖]Cat导致内存不足原因分析

    背景 线上几亿的数据在回刷的时候容器服务会出现OOM而重启,导致任务中断 内存泄露分析 jmap -histo pid 找出了有几十亿的java.lang.StackTraceElement对象,找不 ...

  3. 神通奥斯卡数据库是否兼容Oracle, 以及参数修改的办法

    1. 最近公司要适配神通数据库, 但是因为一些功能异常.参数可能存在风险. 为了减少问题, 想着简单描述一下这些的处理. 开发和客户给的默认参数建议 1. 不选择 兼容oracle模式 2. 字符集选 ...

  4. 【VictoriaMetrics源码阅读】vm中仿照RoaringBitmap的实现:uint64set

    作者:张富春(ahfuzhang),转载时请注明作者和引用链接,谢谢! cnblogs博客 zhihu 公众号:一本正经的瞎扯 正文 VictoriaMetrics中使用uint64类型来表示一个Me ...

  5. 【JS 逆向百例】37网游登录接口参数逆向

    声明 本文章中所有内容仅供学习交流,严禁用于商业用途和非法用途,否则由此产生的一切后果均与作者无关,若有侵权,请联系我立即删除! 逆向目标 目标:37网游登录 主页:https://www.37.co ...

  6. 缩小ios的包体

    不选全部兼容设备 在xcode中导出ipa时,不勾选导出全部兼容性设备,这样导出的ipa包含两种架构:armv7和64 打包压缩 unity提供三种压缩模式可以选择,默认选择的是:default不压缩 ...

  7. TienChin-课程管理-课程导出

    更改 Course.java: /** * 课程ID */ @TableId(value = "course_id", type = IdType.AUTO) @NotNull(m ...

  8. 8.2 C++ 引用与取别名

    C/C++语言是一种通用的编程语言,具有高效.灵活和可移植等特点.C语言主要用于系统编程,如操作系统.编译器.数据库等:C语言是C语言的扩展,增加了面向对象编程的特性,适用于大型软件系统.图形用户界面 ...

  9. [ Skill ] append1, append, nconc, tconc, lconc, cons 效率对比

    https://www.cnblogs.com/yeungchie/ 先说结论:cons > tconc, lconc >> nconc > append1, append a ...

  10. Kubernetes全栈架构师(Docker基础)--学习笔记

    目录 Docker基础入门 Docker基本命令 Dockerfile用法 制作小镜像上 多阶段制作小镜像下 Scratch空镜像 Docker基础入门 Docker:它是一个开源的软件项目,在Lin ...