Introduction and use of the view layer of Django

Django's View (View)

View of a function (which may be type), referred to as a view, Python is a simple function (which may be type), which receives the response back to the Web and Web requests.

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 in the name somewhere, we agreed to a vulgar place the view in the project (project) or application (app) directory views.pyfile.

A simple view

Here is a view returns the current date and time in the form of an HTML document:

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)

Code analysis:

  • First of all, from the django.httpimported module HttpResponseclass, as well as the Python datetimelibrary.

  • Then, we define the current_datetimefunction. It is the view function. Each view function using HttpRequestan object as the first parameter, and is commonly known request.

    Note that the name of the view function does not matter; do not need a unified approach to naming names, in order to allow Django to recognize it. Named descriptive sense can be.

  • This view will return an HttpResponseobject that contains the generated response. Each view function is responsible for returning an HttpResponseobject.

Django uses request and response state objects to pass through the system.

When a browser requests a page from the server, Django create an HttpRequest object that contains metadata about the request. Then, Django loads the appropriate view, this view HttpRequest object to function as the first parameter.

Each view is responsible for returning an HttpResponse object.

CBV and FBV

Written before the view functions are based on the view function, called FBV. The view can also be written as class-based. Called the CBV

Take our written before you add the class as an example:

FBV version:

# FBV版添加班级
def add_class(request):
    if request.method == "POST":
        class_name = request.POST.get("class_name")
        models.Classes.objects.create(name=class_name)
        return redirect("/class_list/")
    return render(request, "add_class.html")

CBV version:

# CBV版添加班级
from django.views import View

class AddClass(View):  
    
    def get(self, request):
        return render(request, "add_class.html")
    
    def post(self, request):
        class_name = request.POST.get("class_name")
        models.Classes.objects.create(name=class_name)
        return redirect("/class_list/")

note:

When using CBV, urls.py also make the corresponding changes:

# urls.py中
url(r'^add_class/$', views.AddClass.as_view()),

Add to the view decorator

Decorator decoration FBV

FBV is itself a function, and so add to the normal function decorators no difference:

def wrapper(func):
    def inner(*args, **kwargs):
        start_time = time.time()
        ret = func(*args, **kwargs)
        end_time = time.time()
        print("used:", end_time-start_time)
        return ret
    return inner


# FBV版添加班级
@wrapper
def add_class(request):
    if request.method == "POST":
        class_name = request.POST.get("class_name")
        models.Classes.objects.create(name=class_name)
        return redirect("/class_list/")
    return render(request, "add_class.html")

Decorator decoration CBV

Method class independent functions are not identical, the method can not be directly applied to a function of decorator class, we need to first convert it to a method decorators.

Django provides method_decorator decorative function for converting a method decorator decorators.

# CBV版添加班级
from django.views import View
from django.utils.decorators import method_decorator

class AddClass(View):

    @method_decorator(wrapper)
    def get(self, request):
        return render(request, "add_class.html")

    def post(self, request):
        class_name = request.POST.get("class_name")
        models.Classes.objects.create(name=class_name)
        return redirect("/class_list/")
# 使用CBV时要注意,请求过来后会先执行dispatch()这个方法,如果需要批量对具体的请求处理方法,如get,post等做一些操作的时候,这里我们可以手动改写dispatch方法,这个dispatch方法就和在FBV上加装饰器的效果一样。

class Login(View):
     
    def dispatch(self, request, *args, **kwargs):
        print('before')
        obj = super(Login,self).dispatch(request, *args, **kwargs)
        print('after')
        return obj
 
    def get(self,request):
        return render(request,'login.html')
 
    def post(self,request):
        print(request.POST.get('user'))
        return HttpResponse('Login.post')

Object Request and Response objects

The request object

When a page is requested, Django creates an HttpRequest object of this request contains the original information.
Django This object will be automatically passed to the view response function, general view function using convention receiving the object request parameter.

Official Documents

Common values ​​related requests

  • path_info return the user to access url, not including the domain

  • method string HTTP method used in the request indicates, represents all uppercase.

  • GET contain dictionary-like object all HTTP GET parameters

  • POST dictionary-like object containing all the HTTP POST parameters

  • body request body, byte type request.POST data is extracted from inside the body to

request property

All property should be considered read-only, unless otherwise noted.

属性:
  django将请求报文中的请求行、头部信息、内容主体封装成 HttpRequest 类中的属性。
   除了特殊说明的之外,其他均为只读的。


0.HttpRequest.scheme
   表示请求方案的字符串(通常为http或https)

1.HttpRequest.body
  一个字符串,代表请求报文的主体。在处理非 HTTP 形式的报文时非常有用,例如:二进制图片、XML,Json等。
  但是,如果要处理表单数据的时候,推荐还是使用 HttpRequest.POST 。
  另外,我们还可以用 python 的类文件方法去操作它,详情参考 HttpRequest.read() 。

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 将为一个空的类似于字典的对象。

9.HttpRequest.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 键。

 
10.HttpRequest.user
  一个 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。



11.HttpRequest.session
   一个既可读又可写的类似于字典的对象,表示当前的会话。只有当Django 启用会话的支持时才可用。
    完整的细节参见会话的文档。

request method

1.HttpRequest.get_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() 方法将会失败。除非使用中间件重写代理的首部。

 

2.HttpRequest.get_full_path()
  返回 path,如果可以将加上查询字符串。
  例如:"/music/bands/the_beatles/?print=true"

 

3.HttpRequest.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
        复制代码
         


4.HttpRequest.is_secure()
  如果请求时是安全的,则返回True;即请求通是过 HTTPS 发起的。

 

5.HttpRequest.is_ajax()
  如果请求是通过XMLHttpRequest 发起的,则返回True,方法是检查 HTTP_X_REQUESTED_WITH 相应的首部是否是字符串'XMLHttpRequest'。

  大部分现代的 JavaScript 库都会发送这个头部。如果你编写自己的 XMLHttpRequest 调用(在浏览器端),你必须手工设置这个值来让 is_ajax() 可以工作。

  如果一个响应需要根据请求是否是通过AJAX 发起的,并且你正在使用某种形式的缓存例如Django 的 cache middleware, 
   你应该使用 vary_on_headers('HTTP_X_REQUESTED_WITH') 装饰你的视图以让响应能够正确地缓存。

Note: a plurality of key-value pairs, when the input type such as checkbox, SELECT tag is required to take a plurality of values ​​GetList:

request.POST.getlist("hobby")

Simple file upload example form Forms

def upload(request):
    """
    保存上传文件前,数据需要存放在某个位置。默认当上传文件小于2.5M时,django会将上传文件的全部内容读进内存。从内存读取一次,写磁盘一次。
    但当上传文件很大时,django会把上传文件写到临时文件中,然后存放到系统临时文件夹中。
    :param request: 
    :return: 
    """
    if request.method == "POST":
        # 从请求的FILES中获取上传文件的文件名,file为页面上type=files类型input的name属性值
        filename = request.FILES["file"].name
        # 在项目目录下新建一个文件
        with open(filename, "wb") as f:
            # 从上传的文件对象中一点一点读
            for chunk in request.FILES["file"].chunks():
                # 写入本地文件
                f.write(chunk)
        return HttpResponse("上传完成")

HttpResponse object

Compared with the HttpRequest object is created automatically by Django, HttpResponse objects are our terms of reference of. We write each view will need to be instantiated, fill and return an HttpResponse.

HttpResponse class located django.http module.

use

Passing strings

from django.http import HttpResponse
response = HttpResponse("Here's the text of the Web page.")
response = HttpResponse("Text only, please.", content_type="text/plain")

Set or delete response headers

response = HttpResponse()
response['Content-Type'] = 'text/html; charset=UTF-8'
del response['Content-Type']

Attributes

HttpResponse.content: response content

HttpResponse.charset: response code content

HttpResponse.status_code: status response code

JsonResponse objects

JsonResponse is HttpResponse subclass, designed to generate a response JSON-encoded.

from django.http import JsonResponse

response = JsonResponse({'foo': 'bar'})
print(response.content)

b'{"foo": "bar"}'

The default can only pass a dictionary, a dictionary if you want to pass a non-keyword arguments need to set up safe.

response = JsonResponse([1, 2, 3], safe=False)

JsonResponse can know by looking at the source code, a red box inside these words tell us if you want to pass non dictionaries need to set safe to False

Django shortcut functions (django necessary three-piece suit)

Official Documents

render()

img

Combined with a given template with a given context dictionary and returns an HttpResponse object after rendering.

参数:
     request: 用于生成响应的请求对象。

     template_name:要使用的模板的完整名称,可选的参数

     context:添加到模板上下文的一个字典。默认是一个空字典。如果字典中的某个值是可调用的,视图将在渲染模板之前调用它。

     content_type:生成的文档要使用的MIME类型。默认为 DEFAULT_CONTENT_TYPE 设置的值。默认为'text/html'

     status:响应的状态码。默认为200。   
    
     useing: 用于加载模板的模板引擎的名称。
            
一个简单的例子:
from django.shortcuts import render
def my_view(request):
    # 视图的代码写在这里
    return render(request, 'myapp/index.html', {'foo': 'bar'})

The principle render (actually a HttpResponse object returned):


from django.shortcuts import render,HttpResponse
from django.template import Template,Context

# render 不单可以返回一个html页面,还可以给模板传递
def index(request):

    res = Template('<h1>{{user}}</h1>')
    con = Context({'user':{'usernmae':'cxk','age':38}})
    ret = res.render(con)
    print(ret)
    return HttpResponse(ret)

redirect()

Parameters can be:

  • A model: The model will be called get_absolute_url()function
  • A view, may have parameters: the use urlresolvers.reverseto reverse resolve the name
  • An absolute or relative URL, will remain intact as the redirection location.

Default returns a temporary redirect; deliver permanent=Truereturns a permanent redirect.

Example:

You can use a variety of ways redirect()function.

ORM pass a specific object (to understand)

ORM will call the specific object get_absolute_url()methods to obtain the redirected URL:

from django.shortcuts import redirect
 
def my_view(request):
    ...
    object = MyModel.objects.get(...)
    return redirect(object)

Pass the name of a view

def my_view(request):
    ...
    return redirect('some-view-name', foo='bar')

Transfer to redirect to a specific URL

def my_view(request):
    ...
    return redirect('/some/url/')

Of course, it can be a full URL

def my_view(request):
    ...
    return redirect('http://example.com/')

By default, redirect()it returns a temporary redirect. All of the above forms are receiving a permanentparameter; if set True, returns a permanent redirection:

def my_view(request):
    ...
    object = MyModel.objects.get(...)
    return redirect(object, permanent=True)  

Extended:

Temporary Redirect (response status code: 302) and permanent redirect (response status code: 301) for the average user is no difference, and it is mainly for the search engine robots.

A temporary redirect page to page B, then A is indexed by search engines page.

A permanent redirect page to page B, then B is indexed by search engines page

301 and 302 of the difference between:

  301和302状态码都表示重定向,就是说浏览器在拿到服务器返回的这个状态码后会自动跳转到一个新的URL地址,这个地址可以从响应的Location首部中获取
  (用户看到的效果就是他输入的地址A瞬间变成了另一个地址B)——这是它们的共同点。

  他们的不同在于。301表示旧地址A的资源已经被永久地移除了(这个资源不可访问了),搜索引擎在抓取新内容的同时也将旧的网址交换为重定向之后的网址;

  302表示旧地址A的资源还在(仍然可以访问),这个重定向只是临时地从旧地址A跳转到地址B,搜索引擎会抓取新的内容而保存旧的网址。 SEO302好于301

Guess you like

Origin www.cnblogs.com/guapitomjoy/p/11750528.html