Django's View (View) system view of Django

Django's View (View)

  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 views.py file.

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)

Let's explain the above code line by line:

  • First of all, from the  django.http import the module HttpResponse class, as well as Python's datetime library.

  • Then, we define current_datetime function. It is the view function. Each view function using HttpRequest 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. We will name it the current_datetime , because this name can more accurately reflect the function it implements.

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

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

  We've written before are based on the view function, called FBV. The view can also be written as class-based.

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

1, FBV edition:

# FBV version add classes
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")

2, CBV version:

# CBV version add classes
from django.views import View


class AddClass(View):

    # Is get on with the write request def get ()
    def get(self, request):
        return render(request, "add_class.html")

    # Is a post with a request to write def post ()
   def post(self, request):
        class_name = request.POST.get("class_name")
        models.Classes.objects.create(name=class_name)
        return redirect("/class_list/")

Request operation code in an operation code and FBV Version # corresponding to the above request corresponding to the same

  note:

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

# Urls.py in
url(r'^add_class/$', views.AddClass.as_view()),
# Views. Class name .as_view ()

Add to the view decorator

1, the 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 right
    return inner


# FBV version add classes
@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")

2, the 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 version add classes
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/")

  

# Pay attention when using CBV, the request came first performs dispatch () This method, if required quantities of a specific request processing methods, such as get, post, and so do some of the operations time, where we can manually rewrite the dispatch method, the dispatch methods to increase and decorators in the FBV the same effect.

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')
Further reading on the CBV

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

1, common values ​​relating to the request

  • path_info      return the user to access url, not including the domain
  • method         used in the request HTTP method (POST, GET, etc.) a string representation, showing 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

2, property

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

Attributes:
  The row django Request packets, the header information, to the contents of the package body 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 ().

 

2.HttpRequest.path

  A string representing the path component (Domain) request.

  For example: " / Music / bands Scrap / the_beatles / "



3.HttpRequest.method

  A string representing the request using the HTTP method. You must use uppercase.

  例如:"GET""POST"

 

4.HttpRequest.encoding

  A string representing the encoded data submission (if the indication None DEFAULT_CHARSET set, the default is ' UTF-. 8 ' ).
   This property is writable, you can modify it to modify the encoded form data access used.
   Next, any access to the properties (e.g., reading data from the GET or POST) encoding will use the new values.
   If you know the encoding is not DEFAULT_CHARSET form data, then use it.

 

5.HttpRequest.GET 

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

 

6.HttpRequest.POST

  A dictionary-like object, if the request is included in the form data, the data will be packaged into QueryDict objects.

  POST requests can with an empty POST dictionary - if via HTTP POST method sends a form, but the form does not have any data, QueryDict objects will still be created.
   Therefore, you should not use IF request.POST to check whether you are using the POST method; you should use IF request.method == " POST " 

  Also: If you use the POST uploaded file, the file information will be included in FILES property.

 7.HttpRequest.COOKIES

  A standard Python dictionary containing all of the cookie. And keys are string values.

 

8.HttpRequest.FILES

  A dictionary-like object containing all the uploaded file information.
   Each key is FILES <INPUT type = " File " name = "" /> The name, the value compared with the corresponding data.

  Note that, FILES only POST method request is submitted and <form> = with the enctype " multipart / form-Data " in the case of only
   It contains data. Otherwise, FILES will be a blank dictionary-like object.

 

9.HttpRequest.META

   A standard Python dictionary containing all the HTTP headers. Specific header information depends on the client and the server, the following are some examples:

    CONTENT_LENGTH - the length of the body of the request (a string).
    MIME type text request - CONTENT_TYPE.
    HTTP_ACCEPT - response may receive the Content - the Type.
    HTTP_ACCEPT_ENCODING - response may be received encoded.
    HTTP_ACCEPT_LANGUAGE - response may be received language.
    HTTP_HOST - HTTP Host header sent by customer.
    HTTP_REFERER —— Referring 页面。
    HTTP_USER_AGENT - Client the User - Agent string.
    QUERY_STRING - single string in the form of a query string (not parsed form).
    REMOTE_ADDR - IP address of the client.
    REMOTE_HOST - host name of the client.
    REMOTE_USER - after user authentication server.
    REQUEST_METHOD - a string, such as " the GET " or " the POST " .
    SERVER_NAME - host name of the server.
    SERVER_PORT - server port (a string).
   Can be seen from the above, and in addition CONTENT_LENGTH CONTENT_TYPE, any HTTP request header is converted to META key,
    Will all capital letters replaced by an underscore and hyphen final with HTTP_ prefix.
    So called X- - Bender converted into a head in the META HTTP_X_BENDER bond.

 
10.HttpRequest.user

  AUTH_USER_MODEL an object type, it indicates that the user currently logged on.

  If the user is not currently logged in, user will be set to an instance of django.contrib.auth.models.AnonymousUser. You can () to distinguish them by is_authenticated.

    E.g:

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

       Only available when the user is enabled only when Django AuthenticationMiddleware middleware.

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

    Anonymous User
    class models.AnonymousUser

    django.contrib.auth.models.AnonymousUser django.contrib.auth.models.User class implements the interface, but with the following several points:

    id is always None.
    username is always an empty string.
    get_username () always returns an empty string.
    is_staff and is_superuser forever to False.
    is_active forever to False.
    groups and user_permissions forever empty.
    is_anonymous () returns True instead of False.
    is_authenticated () returns False instead of True.
    set_password()、check_password()、save() 和delete() 引发 NotImplementedError。
    New in Django 1.8:
    New AnonymousUser.get_username () to better simulate django.contrib.auth.models.User.

 

11.HttpRequest.session

   I can read a dictionary-like objects but also to write, and represents the current session. Only available when Django enable support sessions.
    Complete documentation for details see session.
request property related

  Upload file example

  Front page:

   :( note add back-end functions corresponding relationship)

  What is look at the back end to get

   result

  The uploaded files are saved in the project:

def upload(request):
    """
    Before saving the file to upload, the data need to be stored somewhere. When the default upload files less than 2.5M, the entire contents of django will upload the file into memory. A memory read from and write disk once.
    But when the upload file is large, django will upload files written to a temporary file and stored in the system temporary folder.
    :param request: 
    :return: 
    """
    if request.method == "POST":
        # 从请求的FILES中获取上传文件的文件名,file为页面上type=files类型input的name属性值
        filename = request.FILES["upload_file"].name
        # 在项目目录下新建一个文件
        with open(filename, "wb") as f:
            # 从上传的文件对象中一点一点读
            for chunk in request.FILES["upload_file"].chunks():
                # 写入本地文件
                f.write(chunk)
        return HttpResponse("上传OK")
上传文件示例代码

3,方法

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

  注意:键值对的值是多个的时候,比如checkbox类型的input标签,select标签,需要用:

request.POST.getlist("hobby")

Response对象 

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

  HttpResponse类位于django.http模块中。

  1. HttpResponse --> 返回字符串内容
  2. render --> 返回一个html页面
  3. redirect --> 返回一个重定向(告诉浏览器再去访问另外的网址)

  4. JsonResponse 

1,使用

  传递字符串

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

  设置或删除响应头信息

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

2,属性

  HttpResponse.content:响应内容

  HttpResponse.charset:响应内容的编码

  HttpResponse.status_code:响应的状态码

JsonResponse对象

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

def json_test(request):
    data = {'foo': 'bar'}
    # 把data序列化成json格式的字符串

    # import json
    # response = json.dumps(data)  

    # 下面的到代码帮我们完成了上面的两句代码
    from django.http import JsonResponse
    response = JsonResponse(data )
    return response

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

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

Django shortcut functions

官方文档

 1,render()

 

 结合一个给定的模板和一个给定的上下文字典,并返回一个渲染后的 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, 'myapp/index.html', {'foo': 'bar'})

  上面的代码等于:

from django.http import HttpResponse
from django.template import loader

def my_view(request):
    # 视图代码写在这里
    t = loader.get_template('myapp/index.html')
    c = {'foo': 'bar'}
    return HttpResponse(t.render(c, request))

2,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)

  传递一个视图的名称

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

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

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

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

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

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

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

扩展阅读: 

临时重定向(响应状态码:302)和永久重定向(响应状态码:301)对普通用户来说是没什么区别的,它主要面向的是搜索引擎的机器人。

A页面临时重定向到B页面,那搜索引擎收录的就是A页面。

A页面永久重定向到B页面,那搜索引擎收录的就是B页面。

 

 

Django之视图https://www.cnblogs.com/liwenzhou/articles/8305104.html

 

Guess you like

Origin www.cnblogs.com/eternity-twinkle/p/11654417.html