zoukankan      html  css  js  c++  java
  • python_django_views视图模块

    视图(views.py):接收web请求,并响应web请求

    在视图响应web请求的过程中,响应文件可能是网页,也可能是json数据

    若响应的是网页,我们可分为:

    视图函数:在views.py下自定义的各类函数

    视图参数:视图函数的形式参数,一般我们写的是request,这个参数勒一般就存的是我们浏览器发给我们的内容(一串数据流也可以称作是一个HttpRequest实例)

    错误视图:

    404视图:找不到网页(url匹配不成功)时返回

      我们也可以自定义404页面:

        1.在templates下定义404.html(<h2>{{request_path}}</h2>   # 导致错误的网址)

         2.配置setting.py

             a.  DEBUG=True代表永远不会调用404.html页面,所以我们这里要设置为False

           b.  ALLOWED_HOSTS=['*']   # 允许任何人访问

    大概样子长这样↓↓↓:

    500视图:在视图代码中出现错误(服务器代码错误)
    400视图:错误出现在客户端的操作(服务器发现你是爬虫或cookie中带了错误等)

    视图中可操作对象:

    HttpRequest对象浏览器发送给服务器的数据流

    服务器接收http请求后,会根据报文(数据流)创建HttpRequest对象,调用视图时,创建HttpRequest对象就传入views.py中函数的request形参中。

                                  —— HttpRequest对象的属性   

              |                                                     

     HttpRequest对象—   —— HttpRequest对象的方法

              |

                —— QueryDict对象                       

    HttpRequest对象的属性:

    path 请求的完整路径(不包括域名和端口)
    method 表示请求的方式(get/post)

    encoding

    表示浏览器提交数据的编码方式,一般为utf-8
    GET

    类似于字典的对象,包含类get请求的所有参数(获取浏览器地址栏传递过来的数据)

    POST 类似于字典的对象,包含了post请求的所有参数(例:表单提交(获取浏览器提交的数据,并在views函数中作出对应的操作))
    FILES 类似于字典的对象,包含了所有上传的文件(例:word文档上传到服务器)
    COOKIES 字典,包含类所有的cookie对象
    session 类似于字典的对象,表示当前会话

    举个栗子:

              

              结果:

              

    GET属性:

    举个栗子:

      浏览器:

       网址:http://localhost:8000/sunck/get1?a=1&b=2&c=3   # GET获取当数值

               

       结果(浏览器显示):123

       网址:http://127.0.0.1:8000/sunck/get2?a=1&a=2&b=3   # GET获取多个数值a=1&a=2

                

        结果(浏览器显示):123

    POST属性:

    举个栗子:

    浏览器:

             

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>注册</title>
    </head>
    <body>
        <form action="regist/" method="post">
            姓名:<input type="text" name="name" value=""/>
            <hr/>
            性别:<input type="radio" name="gender" value="1"/><input type="radio" name="gender" value="0"/><hr/>
            年龄:<input type="text" name="age" value=""/>
            爱好:
            <input type="checkbox" name="hobby" value="power"/>权利
            <input type="checkbox" name="hobby" value="money"/>金钱
            <hr/>
            <input type="submit" value="注册"/>
        </form>
    </body>
    </html>
    浏览器html代码

    服务器:

             

    from django.shortcuts import render,redirect,HttpResponse
    def showregist(request):
        return render(request,'myapp/regist.html')
    def regist(request):
        name = request.POST.get("name")
        gender = request.POST.get("gender")
        age = request.POST.get("age")
    # 这个网页提交过来得到的值,用模型类创建表单对象,对应的就可以存入数据表中勒
        hobby = request.POST.getlist("hobby")
        print(name)
        print(gender)
        print(age)
        print(hobby)
        return HttpResponse("post")
    Views模块函数

    对应url配置(这里可以直接用地址重定向,就不用写这么复杂勒):

    HttpRequest的方法:

    is_ajax():若通过XMLHttpRequest发起的,返回True(ajax请求,一般返回json数据)

    QueryDict对象:request对象中的GET/POST都属于QueryDict对象

      方法:

        get():根据键获取值(且只能获取一个值)www.sunck.wang/abc?a=1&b=2&c=3
        getlist():将键的值以列表的形式返回(获取多个值)


    HttpRequest对象是由django创建,HttpResponse对象是由程序员创建(因为要合成返回给浏览器的数据)

    HttpRequest对象: 给浏览器返回数据

    返回数据的方法:

    1. 不调用模板,直接返回数据(例:return HttpResponse('dasfds'))

    2.调用模板:使用render(request, templateName[,context])

      作用: 结合数据和模板,返回完整的html页面

      参数:request:请求体对象

            templateName:模板路径

          context:传递给需要渲染在模板上的数据

      举个栗子:

        return render(request,'myapp/main.html',{'username':username})

                                  —— HttpResponse对象的属性   

              |                                                     

     HttpResponse对象—   —— HttpResponse对象的方法

              |    —— 子类HttpResponseRedict

              |  ——

                   —— 子类JsonResponse

    HttpResponse对象的属性:

    HttpResponse().content

    返回给浏览器内容的类型

    HttpResponse().charset

    编码方式

    HttpResponse().status_code  

    响应状态码 (200/304/404)

    HttpResponse().content-type

    指定输出的MIME类型(例:若我是html文件,则按网页渲染,若我是json文件,则为json文件接收)

    HttpResponse对象的方法:

    init

    使用页面内容实例化HttpResponse对象

    write(content)

    以文件的形式写入

    flush()

    以文件的形式输出缓冲区(刷新缓冲区)

    set_cookie(key,value='', max_age=None,exprise=None) 

     在浏览器存入cookie

    delete_cookie(key)

    删除cookie(若删除不存在的key,不会报错)

    set_cookie方法:

    # cookie
    def cookietest(request):
        res = HttpResponse()
        # cookie1 = request.COOKIES    # 存入后,取出cookie值
        # res.write('<h1>' + cookie['sunck'] + '</h1>')   # 在浏览器上显示取出的cookie值
        cookie = res.set_cookie('sunck','good')   # 存入cookie值,这里面俺们就可以存一个token
        return res
        # 在浏览器》检查》Network》刷新页面》选中name》Cookie》查看写的cookie值

    子类HttpResponseRedirect:继承类HttpResponse类

    作用:地址重定向(服务器端的跳转)

      (例:我们输入网址1,但显示的页面是网址2滴页面)

    简写方法:redirect()

    举个栗子:

    from django.http import HttpResponseRedirect
    from django.shortcuts import redirect
    
    # 重定向
    def redirect1(request):
        # return HttpResponseRedirect('/sunck/redirect2')
        return redirect('/sunck/redirect2')     # 简写方法(推荐使用)
    
    def redirect2(request):
        return HttpResponse('我是重定向页面')

    对应的url:

     过程:

      当我们在浏览器输入:http://localhost:8000/sunck/redirect1时,浏览器显示的网址:http://localhost:8000/sunck/redirect2/,这就是重定向,虽然在浏览器没有操作,但是它是在服务器中完成了自我跳转。

    子类JsonResponse:返回json数据,一般用于异步请求(ajax)

    (例:若HttpRequest().is_ajax() 为true,则我们一般返回的就是json数据)

    大概过程:

    from django.http import JsonResponse
    def js(request):
        if request.is_ajax():
            return JsonResponse({})    # 返回json数据,{}代表json数据

    注:JsonResponse中属性Content-type的类型为application/json(默认返回为json类型)

  • 相关阅读:
    第一章 数据集散地:数据库
    第六章 使用ADO.NET查询和操作数据
    第五章 使用ADO.NET访问数据库
    第四章 深入C#的String类
    IOS框架和服务
    一步步调试解决iOS内存泄漏
    app跳转
    iOS 视频直播
    学习心得
    iOS中FMDB的使用
  • 原文地址:https://www.cnblogs.com/Vera-y/p/11925851.html
Copyright © 2011-2022 走看看