视图层

MVC和MTV        
    M          T                 V

    models       template         views

    M          V                 C(路由+views)
    models    模板              控制器
今天重点
视图层:request对象: 
    # form表单,不写method ,默认是get请求
    #     1 什么情况下用get:请求数据,请求页面,
    #     2 用post请求:向服务器提交数据

    # request.GET  字典  可以用get取值
    # request.POST  字典

    # request.method 请求的类型 (get,post)

    # request.body  post提交的数据都会放到body里

    # http://127.0.0.1:8000/index/ppp/dddd/?name=lqz
    # 协议:ip地址和端口/路径?参数(数据)  
    # print(request.path)               路径不包括参数部分
    # print(request.get_full_path()) 包括参数部分
jsonresponse

原生的可以返回任意数据格式
    # dic={'name':'lqz','age':18}
    # li=[1,2,3,4]
    # # return HttpResponse(json.dumps(li))
JsonResponse(向前端页面发json格式字符串)
    # from django.http import JsonResponse
    # return JsonResponse(li,safe=False)  默认可以传字典,如果要传非字典形式的数据要设置safe=False
CBV(class base view)和FBV(function base view) 
视图里可以用函数也可以用类,处理匹配url的逻辑,返回值
    cbv: 视图和路由的写法模板
        1 from django.views import View   #views导入类
        2 class Test(View):
            def dispatch(self, request, *args, **kwargs):   #可以理解为装饰器,派生
                # 加点东西
                print('111')

                #原来的东西不动,加新功能
                obj=super().dispatch(request, *args, **kwargs) #调用方法,接收返回值
                # 加点东西
                print('2222')
                return obj #方法的返回值返回到页面
            def get(self,request):
                obj= render(request,'index.html')
                print(type(obj))
                return obj
            def post(self,request):
                return HttpResponse('ok')
        3 re_path(r'index/', views.Test.as_view()),   #返回的是一个函数,get请求就是get函数,否则就是post函数
简单文件上传
    1 <form action="" method="post" enctype="multipart/form-data">
        用户名:<input type="text" name="name">
        密码:<input type="text" name="password">
        文件:<input type="file" name="myfile">
        <input type="submit">
    
        </form>


        #enctype="multipart/form-data"******************* 必须加这个 不然文件提交不上去
        #<input type="file" name="myfile">
        
    2   # ff是一个文件对象,django封装的
    def post(self,request):
        #print(request.POST)
        # ff是一个文件对象,django封装的  取文件对象的方法
        ff=request.FILES.get('myfile')
        # 文件对象的名字
        file_name=ff.name
        #from django.core.files.uploadedfile import InMemoryUploadedFile
        #print(type(ff))  #重写了InMemoryUploadedFile类的str方法
        with open(file_name,'wb') as f:
            for line in ff.chunks(): #chunks() 是一个生成器
                f.write(line)
        return HttpResponse('ok')
原文地址:https://www.cnblogs.com/xujinjin18/p/9594468.html