Django -- 6. View Layer

Source: Internet
Author: User
Tags server port
View layer view Functions

A view function (view for short) is a simple Python function that accepts Web requests and returns web responses. The response can be the HTML content of a webpage, A redirection, a 404 error, an XML document, or an image... anything. No matter what logic the view contains, a response is returned. It doesn't matter where the code is written, as long as it is under your python directory. There are no more requirements-it can be said that "there is nothing amazing ". To place the code somewhere, the Convention is to place the view name in the project or application directoryViews. py.

The following is a view that returns the current date and time as an HTML document:

from django.shortcuts import render, HttpResponse, HttpResponseRedirect, redirectimport datetimedef current_datetime(request):    now = datetime.datetime.now()    html = "

Let's read the above code line by line:

  • First, we start fromDjango. shortcutsModule importedHttpresponseClass and PythonDatetimeLibrary.

  • Then, we definedCurrent_datetimeFunction. It is a view function. Each view function usesHttprequestThe object is the first parameter, which is usually calledRequest.

    Note that the name of a view function is not important. You do not need to use a uniform naming method for Django to recognize it. We name itCurrent_datetimeBecause the name accurately reflects its functions.

  • This view returnsHttpresponseObject that contains the generated response. Each view function returnsHttpresponseObject.

View layer, master two objects: request object and response object)

Httprequest Object Request attributes

Django encapsulates the request line, header information, and content body in the request message into attributes in the httprequest class. Except for the special instructions, all others are read-only.

/* 1. httprequest. Get is a dictionary-like object that contains all http get parameters. For more information, see querydict object. 2. httprequest. Post is a dictionary-like object. If a request contains form data, the data is encapsulated into a querydict object. The post request can contain an empty post dictionary. If a form is sent through the http post method, but the form does not contain any data, the querydict object will still be created. Therefore, if request. post to check whether the POST method is used; If request should be used. method = "Post". In addition, if you use post to upload files, the file information will be included in the files attribute. Note: when there are multiple key-value pairs, for example, the input tag of the checkbox type and the select tag, you need to use: request. post. getlist ("holobby") 3. httprequest. body is a string that represents the body of the request message. It is useful when processing non-HTTP messages, such as binary images, XML, and JSON. However, if you want to process form data, we recommend that you use httprequest. Post. 4. A string of httprequest. Path indicates the requested path component (excluding the domain name ). For example, "/music/bands/the_beatles/" 5. httprequest. method is a string that indicates the HTTP method used by the request. Uppercase is required. For example, "get" and "Post" 6. httprequest. an Encoding string indicates the encoding method of the submitted data (if it is none, it indicates the default_charset setting is used, default value: 'utf-8 '). This attribute is writable. You can modify it to modify the encoding used for accessing form data. Next, any access to the attribute (for example, reading data from get or post) will use the new encoding value. If you know that the form data encoding is not default_charset, use it. 7. httprequest. Meta is a standard Python dictionary that contains all HTTP headers. The specific header information depends on the client and server. The following is an example: content_length -- the length of the Request body (a string ). Content_type -- MIME type of the Request body. Http_accept -- response to the content-type that can be received. Http_accept_encoding -- the code that the response can receive. Http_accept_language -- the language in which the response can be received. Http_host -- the HTTP Host header sent by the client. Http_referer -- referring page. Http_user_agent -- the User-Agent string of the client. QUERY_STRING -- query string in the form of a single string (unparsed form ). Remote_addr -- IP address of the client. Remote_host -- the host name of the client. Remote_user: the user authenticated by the server. Request_method -- a string, such as "get" or "Post ". SERVER_NAME -- Host Name of the server. Server_port -- the server port (a string ). As you can see from the above, except content_length and content_type, when any HTTP header in the request is converted to the meta key, all the letters are capitalized and the connector is replaced with the underline and the HTTP _ prefix is added. Therefore, a header named X-Bender will be converted to the http_x_bender key in Meta. 8. httprequest. Files is a dictionary-like object that contains all uploaded file information. Each key in files is the name in <input type = "file" name = ""/>, and the value is the corresponding data. Note that files contains data only when the request method is post and the submitted <form> has enctype = "multipart/form-data. Otherwise, files will be an empty dictionary-like object. 9. httprequest. Cookies are a standard Python dictionary that contains all cookies. Both the key and value are strings. 10. httprequest. session a readable and writable dictionary-like object that represents the current session. It is only available when Django enables session support. For more information, see the session documentation. 11. httprequest. User (used in the User Authentication Component) is an auth_user_model object, indicating the user currently logged on. If the user is not currently logged on, the user is set to an instance of Django. contrib. Auth. Models. anonymoususer. You can use is_authenticated () to distinguish them. For example, if request. User. is_authenticated (): # Do something for logged-in users. Else: # Do something for anonymous users. User is only available when Django enables authenticationmiddleware middleware. Anonymous anonymous user class models. anonymoususer Django. contrib. auth. models. the anonymoususer class implements Django. contrib. auth. models. user Interface, but there are several differences: ID is always none. Username is always a null string. Get_username () returns an empty string forever. Is_staff and is_superuser are always false. Is_active is always false. Groups and user_permissions are always empty. Is_anonymous () returns true instead of false. Is_authenticated () returns false instead of true. Set_password (), check_password (), save (), and delete () Cause notimplementederror. New in Django 1.8: added anonymoususer. get_username () to better simulate Django. contrib. Auth. Models. User. */
Common Request Methods
/* 1. httprequest. get_full_path () returns path. If you can add a query string. Example: "/music/bands/the_beatles /? Print = true "2. httprequest. is_ajax () If the request is initiated through XMLHttpRequest, true is returned by checking whether the http_x_requested_with header is a string 'xmlhttprequest '. Most modern JavaScript libraries send this header. If you write your own XMLHttpRequest call (on the browser side), you must manually set this value so that is_ajax () can work. If a response needs to be initiated through Ajax based on whether the request is initiated and you are using some form of cache, such as Django's cache middleware, you should use vary_on_headers ('HTTP _ x_requested_with ') decorate your view so that the response can be cached correctly. */
Httpresponse object

There are three main response objects:

  • Httpresponse ()
  • Render ()
  • Redirect ()

Httpresponse () directly uses a specific string as the response body, which is very simple. So here we will mainly introduce the following two forms.

Render ()

Syntax: render (request, template_name [, context])

Description: combines a given template with a given context dictionary, and returns a rendered httpresponse object.

Parameters:

Request: The request object used to generate the response.

Template_name: the complete name of the template to be used. Optional Parameter

Context: a dictionary added to the template context. The default value is an empty dictionary. If a value in the dictionary is callable, the view will call it before rendering the template.

The render method renders the template syntax in a template page and finally renders it into an HTML page as the response body.

Redirect ()

Pass a hard-coded URL to be redirected

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

It can also be a complete URL:

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

Key: two requests

1) The difference between 301 and 302. Status Codes 301 and 302 indicate redirection, that is, the browser automatically jumps to a new URL address after obtaining the status code returned by the server, this address can be obtained from the response Location header (the user sees that the address a he entered instantly changes to another address B)-this is what they have in common. Their difference is. 301 indicates that the resource of the old address a has been permanently removed (the resource is inaccessible ), while capturing new content, the search engine also switches the old URL to the redirected URL. 302 indicates that the resource of the old address a is still in progress (still accessible ), this redirection only temporarily redirects from the old address a to address B. The search engine captures new content and saves the old URL. Seo302 is better than 301 2) redirection reason: (redirect ). In this case, if no redirection is performed, the old address in the user favorites or search engine database can only give the visitor a 404 page error message, and the access traffic is lost; in addition, some websites that have registered multiple domain names also need to redirect users who access these domain names to the primary site automatically.
About 301 and 302

Redirect can be used to explain append_slash usage!

Django -- 6. View Layer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.