视图层

一、视图函数

一个视图函数,简称视图,是一个简单的Python 函数,它接受Web请求并且返回Web响应。响应可以是一张网页的HTML内容,一个重定向,一个404错误,一个XML文档,或者一张图片. . . 是任何东西都可以。无论视图本身包含什么逻辑,都要返回响应。

from django.shortcuts import render, HttpResponse, HttpResponseRedirect, redirect
import datetime // 视图函数current_datetime使用HttpRequest对象作为第一个参数,并且通常称之为request
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
// 视图会返回一个HttpResponse对象,其中包含生成的响应。每个视图函数都负责返回一个HttpResponse对象
return HttpResponse(html)
b          request         s
r -----------------> e
o <----------------- r
w response ve

二、视图层之HttpRequest对象

django将请求报文中的 请求行、首部信息、内容主体 封装成 HttpRequest 类中的属性。 除了特殊说明的之外,其他均为只读的

# 1.前台Post传过来的数据,包装到POST字典中
request.POST # 2.前台浏览器窗口里携带的数据,包装到GET字典中
request.GET # 3.前台请求的方式
request.method # 4.post提交的数据,body体的内容,前台会封装成:name=lqz&age=18&sex=1
request.body # 5.取出请求的路径,取不到数据部分
request.path # /test/blog/ # 6.取出请求的路径,能取到数据部分
request.get_full_path() # /test/blog?id=1&name=tom # 7.META,一个标准的Python 字典,包含所有的HTTP 首部
request.META # 8.一个类似于字典的对象,包含所有的上传文件信息
request.FILES
#FILES 中的每个键为<input type="file" name="" /> 中的name,值则为对应的数据。
# 注意,FILES 只有在请求的方法为POST 且提交的<form> 带有enctype="multipart/form-data" 的情况下才有
# 包含数据。否则,FILES 将为一个空的类似于字典的对象。

三、视图层之HttpResponse对象

响应对象主要有三种形式:

HttpResponse()
render()
redirect()

1、render()

结合一个给定的模板和一个给定的上下文字典,并返回一个渲染后的 HttpResponse 对象

render(request, 'index.html'[,context])
# 第一个参数是用于生成相应的的请求对象,第二个参数是要使用的模板的名称,第三个参数是添加到模板上下文的字典
# render方法就是将一个模板页面中的模板语法进行渲染,最终渲染成一个html页面作为响应体,render函数相当于
temp=Template('<h1>{{ user }}</h1>')
con=Context({'user':'lqz'})
ret=temp.render(con)
print(ret)
# return render(request,'index.html')
return HttpResponse(ret)

2、redirect()

传递要重定向的一个硬编码的URL

def test(request):
...
#return redirect('/showbooks/')
return redirect('http://127.0.0.1:8888/showbooks')

四、视图层之JsonResponse对象

from django.http import JsonResponse

def test(request):
dic = {'id':1,'name':'tom'}
# JsonResponse默认只支持字典
return JsonResponse(dic) # 等价于
import json
def test(request):
dic = {'id':1,'name':'tom'}
return HttpResonse(json.dumps(dic))
  • JsonResponse默认只支持字典
  • 要用其他类型,可以将JsonResponse参数中的safe设为False,即 return JsonResponse(list, safe=False)

五、CBV和FBV

CBV基于类的视图(Class base view)和FBV基于函数的视图(Function base view)

1、CBV(基于类的视图)

# 路由层
url(r'test/', views.Test.as_view()) # 后面视图必须加括号,源码中是返回一个内存地址 # 视图层
# 1.导入view
from django.views import View
# 2.写类
class Test(view): # 必须继承view
def get(self, request): # 方法名字必须为get、post,参数中必须要有request
return HttpResponse('get_test') def post(self, request):
return HttpResponse('post-test')

2、FBV(基于函数的视图)

# 路由层
url(r'test/', views.show) # 视图层
def show(request):
return HttpResponse('showbooks')

六、文件上传

1、前端

<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="myfile">
<input type="text" name="password">
<input type="submit" value="提交">
</form>
  • 编码enctype用 ‘ multipart/form-data ’

2、后台,文件上传,存到本地

def fileupload(request):
if request.method=='GET':
return render(request,'fileupload.html')
if request.method=='POST':
# 从字典里根据名字,把文件取出来
myfile=request.FILES.get('myfile')
# 文件名字
name=myfile.name
# 打开文件,把上传过来的文件存到本地
with open(name,'wb') as f:
# for line in myfile.chunks():
for line in myfile:
f.write(line)
return HttpResponse('ok')

最新文章

  1. Magento的基本架构解析
  2. $(document).ready、body.Onload()和 $(window).load的区别
  3. 【leetcode】Gray Code (middle)
  4. ASP.NET MVC 微信公共平台开发之 微信接入
  5. Java封装自己的Api
  6. linux 冒号的用途
  7. 08---Net基础加强
  8. Socket的双网卡收发(C#)
  9. python中函数的总结之三
  10. c# 获取指定目录下的所有文件并显示在网页上
  11. rzsz不能大于4G,securefx传5.2G没有问题,
  12. c#代码规范和质量检查工具这点事
  13. Webappbuilder自定义widget模板
  14. 设计模式——命令模式(C++实现)
  15. Linux DNS服务配置
  16. 使用python读取yaml文件
  17. 测试oracle数据库连接
  18. 使用VBA宏批量修改表格
  19. this逃逸
  20. 一步步用svg做一个声波扩散动画

热门文章

  1. 1、jQuery操作Dom
  2. ZJUT11 多校赛补题记录
  3. CPython,PyPy?Python和这两个东西有什么关系
  4. apache2.2.25+tomcat7.0.47集群方案
  5. PAT(A) 1042. Shuffling Machine (20)
  6. pip安装Scrapy因网络问题出错备选方案
  7. 初探Remoting双向通信(二)
  8. 微信小程序の条件渲染
  9. Codeforces 1150D DP
  10. 前端学习(八)sass和bootstrap(笔记)