• Python Django 之 Views HttpRequest HttpReponse


    一、Python Django 之 Views 数据交互

    http请求中产生两个人核心对象:

    http请求:HttpRequest对象

    http响应:HttpReponse对象

    所在位置django.http

    之前我们用到的参数request就是HttpRequest 检测方法

    二、HttpRequest对象

    1、

    2、

    3、

    三、HttpReponse对象

    1、HttpReponse返回数据

    return HttpResponse("<h1>ok</h1>")

    2、render渲染

    return render(req,"index.html",{"user_list":user_list})

    注意:render渲染比HttpResponse复杂,完成同样的工作render只需要一步,HttpResponse却需要

    Trmplate与Context等步骤。

    3、render_to_response渲染

    1)views

    n="hope"

    return render_to_response("index.html",{"name":n})

    2)templates

    <html>

        <head>

        </head>

        <body>

            <h1>{{ name }}</h1>

        </body>

    </html>

    1)好处

    使用render_to_response比render简便,省去了req参数

    n="hope"

    return render_to_response("index.html",{"name":n})

    2)坏处

    建议使用return,不用render_to_response

    4、redirect重定向

    return redirect(“www.baidu.com”)

    注意:

    --1 url: 原本urlpatterns按照模板使用的{},但是在return redirect("/home/")时,总是报错 'set' object is not reversible,

    后来,将{}的集合写法换成[]列表写法则不再报错,return redirect("/home/")生效。

    1)url   

    urlpatterns = [
    path('admin/', admin.site.urls),
    path('cur_time/', views.cur_time),
    path('hello/',views.hello),
    path('login/', views.login),
    path('home/', views.home)]

    # urlpatterns = {
    # path('admin/', admin.site.urls),
    # path('cur_time/', views.cur_time),
    # # path('userInfo/',views.userInfo),
    # # path('login/', views.login),
    # # path('home/', views.home),
    # path('hello/',views.hello),
    # }

    2)views

    from django.shortcuts import render,HttpResponse,render_to_response,redirect
    import datetime
    from blog import models

    def login(req):
    if req.method == "POST":
    if 1:
    return redirect("/home/")
    return render(req,"login.html")

    def home(req):
    name="xihaohu"
    return render(req,"home.html",{"name":name})

    3)templates

    --1 login

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>登录页面</title>
    </head>
    <body>
    <form action="/login/" method="post">
    <input type="text" name="username">
    <input type="text" name="pwd">
    <input type="submit" name="submit">
    </form>
    </body>
    </html>


    --2 home

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>首页</title>
    </head>
    <body>
    <h1>welcom {{ name }}</h1>
    </body>
    </html>
  • 相关阅读:
    Android内存管理之道
    What a C programmer should know about memory
    Android Bitmap缓存池使用详解
    android 5.0主题风格研究
    最受欢迎的5个Android ORM框架
    目前具体实现 material design 有什么途径?
    计算机的数学要求(?转)
    机器智能公司一览图 | 36氪
    Android中Context
    从源码的角度深入分析Scroller
  • 原文地址:https://www.cnblogs.com/xibuhaohao/p/10192047.html
Copyright © 2020-2023  润新知