Six .Django view views (a) the Django view views.py

A. Django view views.py

1 views (views) Introduction

A view function (class), referred to as a view, Python is a simple function (class) that accepts the request and returns Web Web response. 

The response may be a page's HTML content, a redirect, a 404 error, an XML document, or a picture. 

No matter what the view itself contains logic, it must return a response. Write the code where it does not matter, as long as it is in your current directory project. In addition there is no more requirement - and you can say, "There's nothing magical place." 
In order to put the code somewhere, we agreed to a vulgar place the view in the project (project) or application (app) directory named
一个简单的视图

from
django.http import HttpResponse import datetime def current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html)

                                         

 2. The core object request http: HttpRequest objects

All property should be considered read-only, unless otherwise noted. request is actually instantiated objects HttpRequest class at the time of actual use are used request.

Properties:
  Django request packets request line, header information, content body (POST the content body) encapsulated HttpRequest class attributes. In addition to the special instructions of the others are read-only.
0.HttpRequest.scheme string representing the request scheme (typically http or HTTPS) 1.HttpRequest.body   a string representing the request message body. Very useful when dealing with non-HTTP form of messages, such as: binary images, XML, Json and so on.   However, if the time to process the form data, recommend or use HttpRequest.POST.   In addition, we can also file class method of using python to operate it, the details refer HttpRequest.read ().

# 请求request信息
def attr(request):

print(request.path) # 请求的完整的路径(不包括域名和端口) print(request.method) # 表示请求的方式 get post print(request.encoding) # 表示是浏览器提交的数据编码方式 一般是utf-8 print(request.GET) # 类似于字典的对象 它包含了get请求的所有参数 print(request.POST) # 类似于字典的对象 包含了post请求的所有参数 print(request.FILES) # 类似于字典的对象它是包含了所有上传的文件 print(request.COOKIES) # 就是字典包含所有cookies print(request.session) # 类似于字典的对象 表示当前对话session return HttpResponse("打印GET服务器的信息。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。")

服务器打印的顺序

/home/find_show/
GET
None
<QueryDict: {}>
<QueryDict: {}>
<MultiValueDict: {}>
{}

2.HttpRequest.path
  一个字符串,表示请求的路径组件(不含域名)。
  例如:"/music/bands/the_beatles/"

3.HttpRequest.method

  一个字符串,表示请求使用的HTTP 方法。必须使用大写。
  例如:"GET""POST"

4.HttpRequest.encoding

  一个字符串,表示提交的数据的编码方式(如果为 None 则表示使用 DEFAULT_CHARSET 的设置,默认为 'utf-8')。
   这个属性是可写的,你可以修改它来修改访问表单数据使用的编码。
   接下来对属性的任何访问(例如从 GET 或 POST 中读取数据)将使用新的 encoding 值。
   如果你知道表单数据的编码不是 DEFAULT_CHARSET ,则使用它。

5.HttpRequest.GET  

  一个类似于字典的对象,包含 HTTP GET 的所有参数。详情请参考 QueryDict 对象。

6.HttpRequest.POST

  一个类似于字典的对象,如果请求中包含表单数据,则将这些数据封装成 QueryDict 对象。
  POST 请求可以带有空的 POST 字典 —— 如果通过 HTTP POST 方法发送一个表单,但是表单中没有任何的数据,QueryDict 对象依然会被创建。
   因此,不应该使用 if request.POST  来检查使用的是否是POST 方法;应该使用 if request.method == "POST" 
  另外:如果使用 POST 上传文件的话,文件信息将包含在 FILES 属性中。

 7.HttpRequest.COOKIES
  一个标准的Python 字典,包含所有的cookie。键和值都为字符串。


8.HttpRequest.FILES

  一个类似于字典的对象,包含所有的上传文件信息。相见后边
   FILES 中的每个键为<input type="file" name="" /> 中的name,值则为对应的数据。

  注意,FILES 只有在请求的方法为POST 且提交的<form> 带有enctype="multipart/form-data" 的情况下才会
   包含数据。否则,FILES 将为一个空的类似于字典的对象。
 print(request.META) # 一个标准的Python 字典,包含所有的HTTP 首部。具体的头部信息取决于客户端和服务器,下面是一些示例:
    CONTENT_LENGTH —— 请求的正文的长度(是一个字符串)。
    CONTENT_TYPE —— 请求的正文的MIME 类型。
    HTTP_ACCEPT —— 响应可接收的Content-Type。
    HTTP_ACCEPT_ENCODING —— 响应可接收的编码。
    HTTP_ACCEPT_LANGUAGE —— 响应可接收的语言。
    HTTP_HOST —— 客服端发送的HTTP Host 头部。
    HTTP_REFERER —— Referring 页面。
    HTTP_USER_AGENT —— 客户端的user-agent 字符串。
    QUERY_STRING —— 单个字符串形式的查询字符串(未解析过的形式)。
    REMOTE_ADDR —— 客户端的IP 地址。
    REMOTE_HOST —— 客户端的主机名。
    REMOTE_USER —— 服务器认证后的用户。
    REQUEST_METHOD —— 一个字符串,例如"GET" 或"POST"。
    SERVER_NAME —— 服务器的主机名。
    SERVER_PORT —— 服务器的端口(是一个字符串)。
   从上面可以看到,除 CONTENT_LENGTH 和 CONTENT_TYPE 之外,请求中的任何 HTTP 首部转换为 META 的键时,
    都会将所有字母大写并将连接符替换为下划线最后加上 HTTP_  前缀。
    所以,一个叫做 X-Bender 的头部将转换成 META 中的 HTTP_X_BENDER 键

 3. 核心对象 http请求:HttpRequest对象方法

print(request.user)  # AnonymousUser 一个 AUTH_USER_MODEL 类型的对象,表示当前登录的用户。
一个 AUTH_USER_MODEL 类型的对象,表示当前登录的用户。

  如果用户当前没有登录,user 将设置为 django.contrib.auth.models.AnonymousUser 的一个实例。你可以通过 is_authenticated() 区分它们。

    例如:
    if request.user.is_authenticated():
        # Do something for logged-in users.
    else:
        # Do something for anonymous users.

       user 只有当Django 启用 AuthenticationMiddleware 中间件时才可用。

     -------------------------------------------------------------------------------------

    匿名用户
    class models.AnonymousUser
    django.contrib.auth.models.AnonymousUser 类实现了django.contrib.auth.models.User 接口,但具有下面几个不同点:
    id 永远为None。
    username 永远为空字符串。
    get_username() 永远返回空字符串。
    is_staff 和 is_superuser 永远为False。
    is_active 永远为 False。
    groups 和 user_permissions 永远为空。
    is_anonymous() 返回True 而不是False。
    is_authenticated() 返回False 而不是True。
    set_password()、check_password()、save() 和delete() 引发 NotImplementedError。
    New in Django 1.8:
    新增 AnonymousUser.get_username() 以更好地模拟 django.contrib.auth.models.User。
 
 print(request.get_host())   根据从HTTP_X_FORWARDED_HOST(如果打开 USE_X_FORWARDED_HOST,默认为False)和 HTTP_HOST 头部信息返回请求的原始主机。
根据从HTTP_X_FORWARDED_HOST(如果打开 USE_X_FORWARDED_HOST,默认为False)和 HTTP_HOST 头部信息返回请求的原始主机。
   如果这两个头部没有提供相应的值,则使用SERVER_NAME 和SERVER_PORT,在PEP 3333 中有详细描述。

  USE_X_FORWARDED_HOST:一个布尔值,用于指定是否优先使用 X-Forwarded-Host 首部,仅在代理设置了该首部的情况下,才可以被使用。

  例如:"127.0.0.1:8000"   注意:当主机位于多个代理后面时,get_host() 方法将会失败。除非使用中间件重写代理的首部。 要访问的地址是
 http://127.0.0.1:8000/app02/login/?p=11
得到的信息是如下内容

 print(request.get_full_path())  返回 path,如果可以将加上查询字符串。
例如:"/music/bands/the_beatles/?print=true"
/home/find_show/
 print(request.get_signed_cookie())   request.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)
  返回签名过的Cookie 对应的值,如果签名不再合法则返回django.core.signing.BadSignature。

  如果提供 default 参数,将不会引发异常并返回 default 的值。

  可选参数salt 可以用来对安全密钥强力攻击提供额外的保护。max_age 参数用于检查Cookie 对应的时间戳以确保Cookie 的时间不会超过max_age 秒。

        复制代码
        >>> request.get_signed_cookie('name')
        'Tony'
        >>> request.get_signed_cookie('name', salt='name-salt')
        'Tony' # 假设在设置cookie的时候使用的是相同的salt
        >>> request.get_signed_cookie('non-existing-cookie')
        ...
        KeyError: 'non-existing-cookie'    # 没有相应的键时触发异常
        >>> request.get_signed_cookie('non-existing-cookie', False)
        False
        >>> request.get_signed_cookie('cookie-that-was-tampered-with')
        ...
        BadSignature: ...    
        >>> request.get_signed_cookie('name', max_age=60)
        ...
        SignatureExpired: Signature age 1677.3839159 > 60 seconds
        >>> request.get_signed_cookie('name', False, max_age=60)
        False
        复制代码
 print(request.is_secure())   默认为flase
如果请求时是安全的,则返回True;即请求通是过 HTTPS 发起的。
 print(request.is_ajax())  默认为false
    如果请求是通过XMLHttpRequest 发起的,则返回True,方法是检查 HTTP_X_REQUESTED_WITH 相应的首部是否是字符串'XMLHttpRequest'。

  大部分现代的 JavaScript 库都会发送这个头部。如果你编写自己的 XMLHttpRequest 调用(在浏览器端),你必须手工设置这个值来让 is_ajax() 可以工作。
  如果一个响应需要根据请求是否是通过AJAX 发起的,并且你正在使用某种形式的缓存例如Django 的 cache middleware, 
   你应该使用 vary_on_headers('HTTP_X_REQUESTED_WITH') 装饰你的视图以让响应能够正确地缓存。

 4. 核心对象 http请求:HttpRequest对象使用

                                                                                    

GET属性
http:
//127.0.0.1:8000/get1/?a=1&b=2&c=3 def get1(request): a = request.GET.get("a") b = request.GET.get("b") c = request.GET.get("c") return HttpResponse(a+"-"+b+"-"+c) http://127.0.0.1:8000/get2/?a=1&a=2&c=3 def get2(request): alist = request.GET.getlist("a") c = request.GET.get("c") return HttpResponse(alist[0]+"-"+alist[1]+"-"+c)
POST属性
使用表单提交,需要将settings.py文件中的
'django.middleware.csrf.CsrfViewMiddleware',中间件去掉 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>注册</title> </head> <body> <form action="/registe/" method="post"> 用户名: <input type="text" name="username" value=""><hr/> 密码: <input type="password" name="passwd" value=""><hr/> 爱好: <input type="checkbox" name="hobby" value="power">权利 <input type="checkbox" name="hobby" value="money">金钱 <input type="checkbox" name="hobby" value="book">阅读<hr/> <input type="submit" value="注册"> </form> </body> </html> def registe(request): if request.method == "GET": return render(request, "registe.html") else: username = request.POST.get("username") passwd = request.POST.get("passwd") hobbys = request.POST.getlist("hobby") print(username, passwd, hobbys) return HttpResponse("注册成功")
 getlist()属性

       getlist()   将建的值以列表的形式返回           获取多个值                                         
       例如:  www.lover.aa/abc?a=1&b=2&c=3
       注意:键值对的值是多个的时候,比如checkbox类型的input标签,select标签,需要用:

                          request.POST.getlist("hobby")

 

Guess you like

Origin www.cnblogs.com/lovershowtime/p/11349550.html