zoukankan      html  css  js  c++  java
  • Django 视图层

    1.1 request请求对象 属性/方法

    • django将请求报文中的请求行、首部信息、内容主体封装成 HttpRequest 类中的属性
    (1)request.GET 类似于字典对象,包含HTTP GET所有参数
    (2)request.POST 类似于字典对象,请求中包含表单数据,将这些数据封装成 QueryDict 对象。
    (3)request.body 一个字符串,代表请求报文的主体
    (4)request.path 一个字符串,请求路径的组件
    (5)request.method 一个字符串,表示请求使用的HTTP 方法。必须使用大写。
    (6)request.get_full_path() 返回请求路径组件(包含数据部分)
    (7)request.files 一个类似于字典的对象,包含所有的上传文件的信息
    注:FILES 中的每个键为<input type="file" name="" /> 中的name,值则为对应的数据。
    ,FILES 只有在请求的方法为POST 且提交的<form>带有enctype="multipart/form-data" 的情况下才会包含数据。否则,FILES 将为一个空的类似于字典的对象。
    --------------------------------------------
    注:
    form表单,不写method ,默认是get请求
    #get与post应用场景
    1 get:请求数据,请求页面,
    2 post请求:向服务器提交数据
    
    • 代码:
    模板:
    <body>
        {#不写method ,默认是get请求#}
    <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>
    </body>
    

      

     urls: re_path('^index1/',views.index1) views: def index1(request): print(type(request )) #<class 'django.core.handlers.wsgi.WSGIRequest'> print(request) #<WSGIRequest: GET '/index1/'> print(request.POST ) #<QueryDict: {}> #< QueryDict: {'name': ['hh'], 'password': ['77'], 'myfile': ['']} > print(request .GET) #<QueryDict: {}> print(request.path) # 请求路径的组件/index1/ print(request.get_full_path()) #请求组件,包含数据部分 print(HttpResponse) #<class 'django.http.response.HttpResponse'> print(request.body) # b'' get 请求没有内容,post请求内容为b'name=rr&password=tt' return render(request ,'index.html') 

    1.2 HttpResponse响应对象

    1.2.1 形式一 HttpResponse():

    • HttpResponse()括号内直接跟一个具体的字符串作为响应体

    1.2.2 形式二 render():

    • 作用:结合一个给定的模板和一个给定的上下文字典,并返回一个渲染后的 HttpResponse 对象
    • 格式:
    render(request, template_name[, context])
    参数:
    (1)request用于生成响应的请求对象。
    (2)template_name:要使用的模板的完整名称,可选的参数
    (3)context:添加到模板上下文的一个字典。默认是一个空字典。如果字典中的某个值是可调用的,视图将在渲染模板之前调用它。
    例:
    book_list=Book.objects.all()
        return render(request,'book_list.html',{'book_list':book_list})
    

    1.2.3 形式三 redirect()

    • 重定向url
    def my_view(request):
        return redirect('/some/url/')
        
    或者是完整的url:
    def my_view(request):
        return redirect('http://www.baidu.com/') 
    

      

    • 代码:
     obj=render(request,'index.html')
        print(obj) #<HttpResponse status_code=200, "text/html; charset=utf-8">
        print(type(obj)) #<class 'django.http.response.HttpResponse'>
        return obj
        
        obj = redirect('/index2/')
        print(obj) #<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/index2/">
        return obj
    

      

    1.3 JsonResponse

    • 向前端返回一个json格式字符串的两种方式
    方式一:
    import json
        dic={'name':'lqz',"age":33}
        return HttpResponse(json.dumps(dic))
    方式二:
    from django.http import JsonResponse
        dic = {'name': 'lqz', "age": 33}
        return JsonResponse (dic)
    

      

    --------------------------------------- 注:在返回列表的时候要设置safe=False from django.http import JsonResponse li = [1, 2, 3, 4] return JsonResponse(li,safe=False) 

    1.4 CBV和FBV

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

    1.4.1 CBV

    views:
    from django.views import View
    # 先导入View,并继承
    class Test(View):
         #对请求进行判断,分发
         def dispatch(self, request, *args,**kwargs ):
            #加逻辑
            print('eeeee')  #先打印eeeee,然后执行get/post请求函数,再打印fffff
            obj=super().dispatch(request, *args,**kwargs) #继承父类属性
            #加逻辑
            print('fffff')
            return obj
            
        def get(self,request):
            obj=render(request,'index.html')
            print(type(obj)) #<class 'django.http.response.HttpResponse'>
            return obj
        def post(self,request):
            print(request.POST) #<QueryDict: {'name': ['hh'], 'password': ['ff']}>
            return HttpResponse ('ok')
    
    urls:
     path('test/',views.Test.as_view()) #.as_view()固定写法
    

      

    1.5 文件上传

    模板:
    <body>
        {#不写method ,默认是get请求;在请求的方法为POST 且提交的<form>带有enctype="multipart/form-data" 的情况下才会包含数据#}
    <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>
    </body>
    
    视图函数:
    from django.views import View
    class Test(View):
         def get(self,request):
            obj=render(request,'index.html')
            print(type(obj)) #<class 'django.http.response.HttpResponse'>
            return obj
        def post(self,request):
            print(request.POST) #<QueryDict: {'name': ['hh'], 'password': ['ff']}>
            # ff是文件对象,可以取出内容保存到本地 <MultiValueDict: {'myfile': [<InMemoryUploadedFile: 响应状态码.PNG (text/plain)>]}>
            ff=request .FILES.get('myfile')
            # print(ff.name) # 调get方法取出文件 响应状态码.PNG
            file_name=ff.name
            print(type(ff))  #<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
            with open(file_name ,'wb') as f:
                for line in ff.chunks():
                    f.write(line)
            return HttpResponse ('ok')
    
    urls:
    path('test/',views.Test.as_view()) #.as_view()固定写法
    

      

  • 相关阅读:
    物理机安装Centos7
    rust网站
    windows10安装ubuntu双系统教程
    在win10+Ubuntu双系统下,完美卸载Ubuntu
    C# Lambda 学习笔记
    git unable to resolve reference 'refs/remotes/gitee/20210825-add-Projet-coreScene': reference broken
    git如何获取远端仓库新分支
    编码规范
    新萝卜家园GHOST WIN7系统32,64位官方版下载
    Semaphore实战
  • 原文地址:https://www.cnblogs.com/quqinchao/p/9898606.html
Copyright © 2011-2022 走看看