Home > Backend Development > Python Tutorial > Detailed explanation of Django views in python (with examples)

Detailed explanation of Django views in python (with examples)

不言
Release: 2018-10-11 16:21:08
forward
7445 people have browsed it

This article brings you a detailed explanation of Django views in python (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

A view function (class), referred to as view, is a simple Python function (class) that contains business logic. It accepts Web requests and returns Web responses.

The response can be the HTML content of a web page, a redirect, a 404 error, an XML document, or an image.

Response must be returned no matter what logic the view itself contains. It doesn't matter where the code is written, as long as it is in your current project directory. Nothing more is required - "nothing magical" so to speak.

In order to put the code somewhere, it is a common convention to place the views in a file named views.py in the project or application directory.

Example: A view that 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)
Copy after login

Let us explain the above code line by line:

First, we start with The django.http module imports the HttpResponse class and Python’s datetime library.

Next, we define the current_datetime function. It is the view function. Each view function takes an HttpRequest object as the first parameter, and is usually called request.

Note that the name of the view function is not important; it does not need to be named in a consistent way for Django to recognize it. We named it current_datetime because this name can more accurately reflect the functions it implements.

This view will return an HttpResponse object containing the generated response. Each view function is responsible for returning an HttpResponse object.

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

When the browser requests a page from the server, Django creates an HttpRequest object, which contains metadata about the request. Django then loads the corresponding view, passing this HttpRequest object as the first parameter to the view function.

Each view is responsible for returning an HttpResponse object.

CBV (class based view) and FBV (function based view)

The function-based view is called FBV, and the view can also be written as class-based.

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")
Copy after login

CBV version

# CBV版添加班级 以类的方式实现
from django.views import View
class AddClass(View): # 继承View中的所有属性
    def get(self, request):  # 如果是get请求,就执行此段函数
        return render(request, "add_class.html")
    def post(self, request): # 如果是post,请求就执行此段函数
        class_name = request.POST.get("class_name")
        models.Classes.objects.create(name=class_name)
        return redirect("/class_list/")
Copy after login

Note: When CBV is used, corresponding modifications must be made in urls.py:

# urls.py中,要加括号
url(r&#39;^add_class/$&#39;, views.AddClass.as_view()),
# 注意: Addclass中并没有定义as_view方法,而是继承view中的方法,从而使其按照
  #相应条件执行相应程序.
 
流程
                1. AddPress.as_view()  —— 》 view函数

                2. 当请求到来的时候执行view函数:
 1. 实例化自己写的类   —— 》self
  self = cls(**initkwargs)
 2. self.request = request
                    3. 执行 self.dispatch(request, *args, **kwargs)
                    
 1. 执行父类中的dispatch方法
  1. 判断请求方式是否被允许
   1. 允许的情况
      handler = 通过反射获取 get  post 方法(指的是自己定义的类中的方法) 
                                    
   2. 不允许的情况
      handler = 不允许的方法
                                    
                           3. handler(request, *args, **kwargs)
                                
 2. 返回HttpResponse对象
                    4. 返回HttpResponse对象 给django
Copy after login

By inheriting the view method, it helps to complete the logical business The functions (eight receiving methods such as post, get, filter, etc.) are more concise than FBV

CBV version does not require if judgment and is more modular.

CBV version adds decorator

Methods in a class are not exactly the same as independent functions, so function decorators cannot be applied directly to methods in a class, we need to convert them into method decorators first.

Django provides the method_decorator decorator to convert function decorators into method decorators.

Method 1:

# Be careful when using CBV, request After coming over, the dispatch() method will be executed first. If we need to perform some operations on specific request processing methods in batches, such as get, post, etc., we can manually rewrite the dispatch method here. This dispatch method is the same as adding decoration on FBV. The effect of the device is the same.

##Method 2:


Add decorator to FBV


##request object

When a page is requested, Django will create an HttpRequest object containing the original information of the request.

Django will automatically pass this object to the corresponding view function. Generally, the view function conventionally uses the request parameter to receive this object.


Common values ​​related to requests

path_info Returns the user access url, excluding the domain name

method The string representation of the HTTP method used in the request, expressed in all uppercase letters.

GET A dictionary-like object containing all HTTP GET parameters

POST A dictionary-like object containing all HTTP POST parameters

body The request body, the byte type request.POST data is

Attributes extracted from body

All attributes should be considered read-only unless otherwise stated.

Attributes:
Django encapsulates the request line, header information, and content body in the request message into attributes in the HttpRequest class.
Except for special instructions, everything else is read-only.

0.HttpRequest.scheme

A string representing the request scheme (usually http or https)

1. HttpRequest.body

A string , represents the body of the request message. It is very useful when processing non-HTTP messages, such as binary images, XML, Json, etc.
However, if you want to process form data, it is recommended to use HttpRequest.POST.
In addition, we can also use python's class file method to operate it. For details, refer to HttpRequest.read().

2. HttpRequest.path

A string representing the path component of the request (excluding domain name).

For example: "/music/bands/the_beatles/"

3. HttpRequest.method

A string indicating the HTTP method used in the request. Capital letters must be used.

For example: "GET", "POST"

4, HttpRequest.encoding

A string indicating the encoding method of the submitted data (if it is None, it means using DEFAULT_CHARSET setting, default is 'utf-8').
This attribute is writable and you can modify it to modify the encoding used to access form data.
Any subsequent access to the property (such as reading data from GET or POST) will use the new encoding value.
If you know the encoding of the form data is not DEFAULT_CHARSET, use it.

5. HttpRequest.GET

A dictionary-like object containing all parameters of HTTP GET. Please refer to the QueryDict object for details.

6. HttpRequest.POST

A dictionary-like object. If the request contains form data, the data will be encapsulated into a QueryDict object.

POST requests can have an empty POST dictionary - if a form is sent via the HTTP POST method, but there is no data in the form, the QueryDict object will still be created.

Therefore, you should not use if request.POST to check whether the POST method is used; you should use if request.method == "POST"

In addition: If you use POST to upload If it is a file, the file information will be included in the FILES attribute.

7. HttpRequest.COOKIES

A standard Python dictionary containing all cookies. Both keys and values ​​are strings.

8. HttpRequest.FILES

A dictionary-like object that contains all uploaded file information.

Each key in FILES is the name in , and the value is the corresponding data.

Note that FILES will only contain data if the request method is POST and the submitted

has enctype="multipart/form-data". Otherwise, FILES will be an empty dictionary-like object.

9. HttpRequest.META

A standard Python dictionary that contains all HTTP headers. The specific header information depends on the client and server. Here are some examples:

CONTENT_LENGTH - The length of the request body (is a string).
CONTENT_TYPE - The MIME type of the requested body.
HTTP_ACCEPT - Content-Type that can be received in response.
HTTP_ACCEPT_ENCODING - Acceptable encoding of the response.
HTTP_ACCEPT_LANGUAGE - The language that the response can accept.
HTTP_HOST - HTTP Host header sent by the client.
HTTP_REFERER——Referring page.
HTTP_USER_AGENT - The client's user-agent string.
QUERY_STRING - Query string in single string form (unparsed form).
REMOTE_ADDR——The IP address of the client.
REMOTE_HOST - The host name of the client.
REMOTE_USER - User authenticated by the server.
REQUEST_METHOD - A string, such as "GET" or "POST".
SERVER_NAME - The host name of the server.
SERVER_PORT - The port of the server (is a string).
As you can see from the above, except for CONTENT_LENGTH and CONTENT_TYPE, when any HTTP header in the request is converted into a META key, all letters will be capitalized and the connector will be replaced with an underscore and finally added with the HTTP_ prefix. So, a header called X-Bender will be converted into the HTTP_X_BENDER key in META.

10. HttpRequest.user

An object of type AUTH_USER_MODEL, representing the currently logged in user.

如果用户当前没有登录,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.
Copy after login

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 启用会话的支持时才可用。完整的细节参见会话的文档。

上传文件示例

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("上传OK")
Copy after login

方法

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(&#39;name&#39;)        
&#39;Tony&#39;
>>> request.get_signed_cookie(&#39;name&#39;, salt=&#39;name-salt&#39;)        
&#39;Tony&#39; # 假设在设置cookie的时候使用的是相同的salt
>>> request.get_signed_cookie(&#39;non-existing-cookie&#39;)
...
KeyError: &#39;non-existing-cookie&#39;    
# 没有相应的键时触发异常
>>> request.get_signed_cookie(&#39;non-existing-cookie&#39;, False)
False        
>>> request.get_signed_cookie(&#39;cookie-that-was-tampered-with&#39;)
...
BadSignature: ...    
>>> request.get_signed_cookie(&#39;name&#39;, max_age=60)
...
SignatureExpired: Signature age 1677.3839159 > 60 seconds        
>>> request.get_signed_cookie(&#39;name&#39;, False, max_age=60)
False
Copy after login

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') 装饰你的视图以让响应能够正确地缓存。

注意:键值对的值是多个的时候,比如checkbox类型的input标签,select标签,需要声明:request.POST.getlist('hobby')

Response对象 

与由Django自动创建的HttpRequest对象相比,HttpResponse对象是我们的职责范围了。我们写的每个视图都需要实例化,填充和返回一个HttpResponse。

HttpResponse类位于django.http模块中。 

使用

传递字符串 

from django.http import HttpResponse
response = HttpResponse("Here&#39;s the text of the Web page.")
response = HttpResponse("Text only, please.", content_type="text/plain")
Copy after login

设置或删除响应头信息

response = HttpResponse()
response[&#39;Content-Type&#39;] = &#39;text/html; 
charset=UTF-8&#39;del response[&#39;Content-Type&#39;]
Copy after login

属性

HttpResponse.content:响应内容

HttpResponse.charset:响应内容的编码

HttpResponse.status_code:响应的状态码

JsonResponse对象

JsonResponse是HttpResponse的子类,专门用来生成JSON编码的响应。

from django.http import JsonResponse
response = JsonResponse({&#39;foo&#39;: &#39;bar&#39;})
print(response.content)
b&#39;{"foo": "bar"}&#39;
Copy after login

默认只能传递字典类型,如果要传递非字典类型需要设置一下safe关键字参数。

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

Django shortcut functions
  
render()

Detailed explanation of Django views in python (with examples)

结合一个给定的模板和一个给定的上下文字典,并返回一个渲染后的 HttpResponse 对象。

参数:

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, &#39;myapp/index.html&#39;, {&#39;foo&#39;: &#39;bar&#39;})
Copy after login

上面代码等于

from django.http import HttpResponse
from django.template import loader
def my_view(request):
    # 视图代码写在这里
    t = loader.get_template(&#39;myapp/index.html&#39;)
    c = {&#39;foo&#39;: &#39;bar&#39;}
    return HttpResponse(t.render(c, request))
Copy after login

redirect()

参数可以是:

一个模型:将调用模型的get_absolute_url() 函数

一个视图,可以带有参数:将使用urlresolvers.reverse 来反向解析名称

一个绝对的或相对的URL,将原封不动的作为重定向的位置。

默认返回一个临时的重定向;传递permanent=True 可以返回一个永久的重定向。

示例:

你可以用多种方式使用redirect() 函数。

传递一个具体的ORM对象

将调用具体ORM对象的get_absolute_url() 方法来获取重定向的URL: 

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

传递一个视图名称

def my_view(request):
    ...    
    return redirect(&#39;some-view-name&#39;, foo=&#39;bar&#39;)
Copy after login

传递要重定向到的一个具体的网址

def my_view(request):
    ...
    return redirect(&#39;/some/url/&#39;)
Copy after login

当然也可以是一个完整的网址

def my_view(request):
    ...
    return redirect(&#39;http://example.com/&#39;)
Copy after login

默认情况下,redirect() 返回一个临时重定向。以上所有的形式都接收一个permanent 参数;如果设置为True,将返回一个永久的重定向:

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

The above is the detailed content of Detailed explanation of Django views in python (with examples). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template