视图层

视图层

一个视图函数,简称视图,是一个简单的Python 函数,它接受Web请求并且返回Web响应。响应可以是一张网页的HTML内容,一个重定向,一个404错误,一个XML文档,或者一张图片. . . 是任何东西都可以。无论视图本身包含什么逻辑,都要返回响应。代码写在哪里也无所谓,只要它在你的Python目录下面。除此之外没有更多的要求了——可以说“没有什么神奇的地方”。为了将代码放在某处,约定是将视图放置在项目或应用程序目录中的名为views.py的文件中。

1.视图层之HttpRequest对象

 前台Post传过来的数据,包装到POST字典中
 request.POST
 
 前台浏览器窗口里携带的数据,包装到GET字典中
 request.GET
 
 前台请求的方式
 request.method
 
 post提交的数据,body体的内容,前台会封装成:name=lqz&age=18&sex=1
 request.body
 
 取出请求的路径,取不到数据部分
 print(request.path)
 
 取出请求的路径,能取到数据部分
 print(request.get_full_path())
 print(request.META)

2.视图层之HttpResponse对象

响应对象主要有三种形式:
HttpResponse()
render()
redirect()
​
render():
        render(request, template_name[, context])
        结合一个给定的模板和一个给定的上下文字典,并返回一个渲染后的 HttpResponse 对象。
    
    
redirect():
     重定向 传递要重定向的一个硬编码的URL
def my_view(request): ... return redirect('/some/url/') 也可以是一个完整的URL: def my_view(request): ... return redirect('http://www.baidu.com/')  ​ ​ HttpResponse(): 返回一个字符串 HttpResponse('hello world')

3.视图层之JsonResponse对象

-导入:from django.http import JsonResponse
-视图函数中:
   def test(request):
      import json
      # dic={'name':'lqz','age':18}
      ll = ['name', 'age']
      
      # 把字典转换成json格式,返回到前台
      return HttpResponse(json.dumps(dic))
      
      # 把列表转换成json格式,返回到前台
      return HttpResponse(json.dumps(ll))
      
      # 把字典转换成json格式,返回到前台
      return JsonResponse(dic)
      
      # 报错,默认不支持列表形式
      return JsonResponse(ll)
      
      # 支持列表形式
      return JsonResponse(ll,safe=False)

4.CBV和FBV

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

-基于类的视图
   -1 路由层:url(r'^test/', views.Test.as_view()),
   -2 视图层
      -导入:from django.views import View
      -写一个类:
         class Test(View):
            def get(self, request):#一定要传request对象
               return HttpResponse('get-test')
​
            def post(self, request):
               return HttpResponse('post-test')
               
-基于函数的视图         

5.简单的文件上传

模板层

 <form action="" method="post" enctype="multipart/form-data">
   {#<form action="" method="post" enctype="application/x-www-form-urlencoded">#}
      <input type="file" name="myfile">
      <input type="text" name="password">
      <input type="submit" value="提交">
   </form>   

视图层

def fileupload(request):
      if request.method=='GET':
         return render(request,'fileupload.html')
      if request.method=='POST':
         print(request.FILES)
         print(type(request.FILES.get('myfile')))
         # 从字典里根据名字,把文件取出来
         myfile=request.FILES.get('myfile')
         from django.core.files.uploadedfile import InMemoryUploadedFile
         # 文件名字
         name=myfile.name
         # 打开文件,把上传过来的文件存到本地
         with open(name,'wb') as f:
            # for line in myfile.chunks():
            for line in myfile:
               f.write(line)
         return HttpResponse('ok')
​
补充:*****编码方式multipart/form-data或者:application/x-www-form-urlencoded传的数据,都可以从POST中取出来

 

原文地址:https://www.cnblogs.com/zhangpang/p/9960203.html