• Django:视图views(二)


    把request对象和response对象原理流程写一下

    request对象

    服务器端接收到http协议的请求,会根据报文信息构建HttpRequest对象

    通过第一个参数,把该对象传递给视图函数

    Request对象包含了如下的属性:

    • path属性:字符串。表示请求的页面的完整路径。
    • method属性:请求的方法。GETPOST

     测试方法:

    添加路由 booktest/urls.py

    urlpatterns = [
        url('^$',views.index), # 路由到views.py中的index()函数
        url('^index', views.index, name="index"),
        url('^(d+)$', views.integer),
        url('^(?P<p2>d+)/(?P<p3>d+)/(?P<p1>d+)$', views.date),
        url('^req$', views.req),
    ]

    添加视图  booktest/views.py

    def req(request):
        print("path:", request.path)
        print("method:", request.method)
        return render(request, 'booktest/req.html')

    添加模板     在templates/booktest/目录下创建req.html       templates/booktest/req.html

    <body>
        <a href="/booktest/req">测试GET</a><br/>
        <form action="/booktest/req" method="POST">
            <input type="submit" value="测试post">
        </form>
    </body>

    settings中把CSRF去掉。 django3/settings.py

    MIDDLEWARE_CLASSES = (
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        #'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
        'django.middleware.security.SecurityMiddleware',
    )

    访问 http://127.0.0.1:8080/booktest/req 点击GET链接则发送GET请求,点击POST按钮则发送POST请求

    GET属性:包含了GET请求的所有参数

    templates/booktest/req.html

    <a href="/booktest/req?a=1&a=2&b=3">测试GET</a><br/>

    booktest/views.py

    def req(request):
        print("path:", request.path)
        print("method:", request.method)
        print("GET:", request.GET)
        return render(request, 'booktest/req.html')

    POST属性:包含post请求方式的所有的参数

    COOKIES属性:描述浏览器的cookies信息

    templates/booktest/req.html

        <form action="/booktest/req" method="POST">
            姓名:<input type="text" name="name"/><br/>
            密码:<input type="password" name="password"/><br/>
            爱好:<input type="checkbox" name="favor" value="eat">吃饭
            <input type="checkbox" name="favor" value="sleep">睡觉
            <input type="checkbox" name="favor" value="play">打豆豆<br/>
            <input type="submit" value="测试post"/>
        </form>

    booktest/views.py

    def req(request):
        print("path:", request.path)
        print("method:", request.method)
        print("GET:", request.GET)
        print("POST:", request.POST)
        return render(request, 'booktest/req.html')

    FILES属性:描述上传文件的信息

    templates/booktest/req.html

    <form action="/booktest/req" method="POST" enctype="multipart/form-data">
            姓名:<input type="text" name="name"/><br/>
            密码:<input type="password" name="password"/><br/>
            爱好:<input type="checkbox" name="favor" value="eat">吃饭
            <input type="checkbox" name="favor" value="sleep">睡觉
            <input type="checkbox" name="favor" value="play">打豆豆<br/>
            上传文件:<input type="file" name="file"/><br/>
            <input type="submit" value="测试post"/>
        </form>

    booktest/view.py

    def req(request):
        print("path:", request.path)
        print("method:", request.method)
        print("GET:", request.GET)
        print("POST:", request.POST)
        print("FILES:", request.FILES)
        print("COOKIES:", request.COOKIES)
        return render(request, 'booktest/req.html')

    is_ajax()方法:判断提交的方式是否用ajax来提交。如果用ajax来提交,则返回True;否则返回False

    templates/booktest/req.html

    <script type="text/javascript">
        window.onload = function(){
            ajax_test = document.getElementById("ajax_test");
            ajax_test.onclick = function(){
                // 1 创建XMLHttpRequest()对象
                var xmlhttp = new XMLHttpRequest();
                // 2 打开服务器
                xmlhttp.open('get', '/booktest/req', true);
                // 注册请求头
                xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                // 4 注册回调函数
                xmlhttp.onreadystatechange = function() {
                    console.log('回调了');
                };
                // 3 发送请求
                xmlhttp.send(null);
            };
        };
        </script>
    <input type="button" id="ajax_test" value="测试ajax提交"/>

    点击该按钮,即可发送ajax请求。

    Response对象

    HttpRequest对象是由Django内部核心自动创建的。

    HttpResponse对象则是由程序员自己创建的

    如果不调用模板,直接返回数据

    def index(request):
        return HttpResponse('hello')

    如果要调用模板,则需要如下步骤:

    1 加载模板。通过loaderget_template方法指定一个模板

    2 渲染模板。

    a 指定一个上下文对象,RequestContext()

    b 用模板的render()方法接收上下文对象。作为HttpResponse()的参数

    booktest/views.py

    from django.http import HttpResponse
    from django.template import loader, RequestContext
    
    def resp(request):
        t1 = loader.get_template('booktest/resp.html')
        context = RequestContext(request, {"text":"helloworld"})
        return HttpResponse(t1.render(context))

    templates/booktest/resp.html

    <body>
    {{text}}
    </body>

    上面的代码通过会被封装到一个函数render()中,所以我们一般简写为

    from django.shortcuts import render
    from django.http import HttpResponse
    
    def resp(request):
        context = {"text":"helloworld"}
        return render(request, "booktest/resp.html", context)

    esponse对象有如下属性:

    content:表示返回的内容。字符串类型。Body显示的部分(用户看到的浏览器显示的内容)

    charsetresponse采用的编码字符集。字符串类型。如果不指定,默认是utf-8

    status_code:状态码。200404500、……

    content-type:输出的MIME类型。(多媒体。包括文本(text/html) 图片(image/jpg image/png) 音频(audio/mp3) 视频(video/mpeg4)

    以上的内容都是通过浏览器输出给客户端的,本身不需要修改。

    可以使用专业的抓包工具,比如Fiddler去查看更详细的请求头、响应头等信息。

    Response对象有如下方法:

    init():实例化HttpResponse对象

    write(content):以文件的方式去写

    flush():清空并输出缓存

    set_cookie(key, value, max_age, expires):设置cookie。其中max_ageexpires二者只需要设置一个值。

  • 相关阅读:
    左值与右值引用 详解
    MFC---导出 Excel 方法
    Linux怎么读? Linux读音考古一日游
    nginx url自动加斜杠问题
    FileBeats配置应用详解
    nginx配置选项try_files详解
    mongodb副本集集群构建
    平凡主丛上的Yang-Mills理论
    Kneser猜想与相关推广
    Lorenzini:Laplacian与图上的黎曼-罗赫定理
  • 原文地址:https://www.cnblogs.com/kumata/p/9674236.html
Copyright © 2020-2023  润新知