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. axios文件上传和 Content-Type类型介绍

    Content-Type的作用是什么? Content-Type: 用于在请求头部指定资源的类型和字符编码. 请求头中的content-type,就是 B端发给S端的数据类型描述 . 即告诉服务器端, ...

  2. vue面试题(一)正在重新整理

    1.输入一个 URL到浏览器整个过程发生了什么?ok 1.浏览器查找当前 URL是否存有缓存,并检查这个缓存是否过期 2.DNS 解析 URL 对应的 IP 3.根据 IP 建立 TCP 连接(三次握 ...

  3. 【遇到一个怪异的问题】使用embed来加载模版,只要写在init()函数中就会导致HTTP服务出错

    作者:张富春(ahfuzhang),转载时请注明作者和引用链接,谢谢! cnblogs博客 zhihu Github 公众号:一本正经的瞎扯 经过反复测试,只要换一个写法就能开启/重现这个怪异的问题. ...

  4. net8来了

    11 月 15 日开始的为期三天的 .NET Conf 在线活动的开幕日上,.NET 8作为微软的开源跨平台开发平台正式发布..NET 团队着重强调云.性能.全栈 Blazor.AI 和 .NET M ...

  5. Midjourney|文心一格prompt教程[Text Prompt(下篇)]:游戏、实物、人物、风景、动漫、邮票、海报等生成,终极模板教学

    Midjourney|文心一格prompt教程[Text Prompt(下篇)]:游戏.实物.人物.风景.动漫.邮票.海报等生成,终极模板教学 场景6:游戏 Prompt 真的越长越好吗? 按照 Mi ...

  6. 4.1 Windows驱动开发:内核中进程与句柄互转

    在内核开发中,经常需要进行进程和句柄之间的互相转换.进程通常由一个唯一的进程标识符(PID)来标识,而句柄是指对内核对象的引用.在Windows内核中,EProcess结构表示一个进程,而HANDLE ...

  7. 认识3D模型-GLTF文件

    GLTF文件格式 glTF的全称(Graphics Language Transmission Format)图形语言传输格式.是三维场景和模型的标准文件格式. glTF 核心是 JSON 文件,描述 ...

  8. P7907 [Ynoi2005] rmscne题解

    题目链接:rmscne 神仙经典数据结构难题.看到求区间种类数有关的东西,需要下意识的反应到经典老题 HH的项链,这里可以学习我这篇 题解.具体学习下扫描线怎么做这类东西的. 看看本题,首先处理区间查 ...

  9. ABC 311 A - E

    ABC 311 A - E 不提供代码 A 题意:求一个字符串的第一个 ABC 最早出现的位置,可以打乱顺序,可以间隔 建立三个变量,然后以此判断即可,直到三种字符都出现就可以了 B 题意:给定每个人 ...

  10. Oracle配置DCD避免会话被防火墙强制断开

    今天有客户反馈应用测试连接Oracle数据库的会话半小时左右未做操作就会被中断,报错ORA-3113,询问数据库是否有这样的超时设置,能否取消掉这个限制? 登上环境查看监听日志发现连接的IP和数据库I ...