Python Learning (32)--django View System

Source: Internet
Author: User
Tags http post

Reprinted from: http://www.cnblogs.com/liwenzhou/articles/8305104.html

Django View (view)

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

The response can be a Web page of HTML content, a redirect, a 404 error, an XML document, or a picture.

Returns a response regardless of the logic contained in the view itself. It doesn't matter where the code is written, as long as it's under your current project directory. there is no more to ask for--it can be said that "there is no magic place". In order to place the code somewhere, it is agreed that idiomatic will place the view in a file named views.py in the Project (project) or in the application (APP) directory.

First,A simple view

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

 from Import HttpResponse Import datetime def Current_datetime (Request):     = Datetime.datetime.now ()    "" % now return HttpResponse (HTML)    

Let's explain the above code row by line:

  • we start with   django.http module imported httpresponse class, and Python < Span class= "Pre" >datetime Library.

  • then we defined current_datetime Function. It is the view function. each view function uses The HttpRequest object is used as the first parameter and is commonly referred to as request .

    Note that the name of the view function is not important; we named it current_datetime because the name can accurately reflect the functionality it implements.

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

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

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

Each view is responsible for returning a HttpResponse object.

Ii. CBV and FBV

All we've written before is a function-based view, called FBV. You can also write a view as class-based.

#in urls.pyURL (r'^login.html$', views. Login.as_view ()),#in views.py fromDjango.viewsImportViewclassLogin (View):defDispatch (self, request, *args, * *Kwargs):Print('before') obj= Super (login,self). Dispatch (Request, *args, * *Kwargs)Print(' After')        returnobjdefGet (self,request):returnRender (Request,'login.html')     defPost (self,request):Print(Request. Post.get ('User'))        returnHttpResponse ('Login.post')

When using CBV, please note that the request will be executed first dispatch () This method, if the need for a batch of specific request processing methods, such as Get,post, and so on, we can manually override the Dispatch method, This dispatch method has the same effect as adding a decorator to the FBV.

Iii. Request Object

Official documents

Property

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

Property: Django encapsulates the request line, header information, and content body in the request message into attributes in the HttpRequest class. Except for special instructions, the others are read-only. " " 0.httprequest.scheme represents a string that requests a scheme (typically HTTP or HTTPS) 1. Httprequest.body A string that represents the body of the request message.  It is useful when dealing with non-HTTP forms of messages, such as binary images, Xml,json, and so on.  However, if you are working with form data, it is recommended that you use Httprequest.post. In addition, we can also use the Python class file method to manipulate it, the details refer to Httprequest.read ().  2.httprequest.path A string that represents the requested path component (without a domain name). For example: "/music/bands/the_beatles/" 3.httprequest.method a string that represents the HTTP method used by the request.  You must use uppercase.   For example: "GET", "POST" 4.httprequest.encoding a string that represents the encoding of the submitted data (if None is the setting using Default_charset, the default is ' Utf-8 ').   This property is writable and you can modify it to modify the encoding used to access the form data.   Next, any access to the property, such as reading data from GET or POST, will use the new encoding value. If you know that the encoding of the form data is not default_charset, use it. 5.httprequest.get A dictionary-like object that contains all the parameters of an HTTP GET. Please refer to the Querydict object for details.  6.httprequest.post A dictionary-like object that is encapsulated as a Querydict object if the request contains form data.   The POST request 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 is still created. Therefore, if request should not be used. Post to check if the Post method is used; if Request.method = = "POST" should be used in addition: if you use post to upload a file, the file information will be included in the Files property. 7.httprequest.cookies A standard Python dictionary that contains all the cookies. Both the key and the value are strings. 8.httprequest.filES A dictionary-like object that contains all the uploaded file information.  Each key in FILES is <input type= "file" name= ""/> Name, and the value is the corresponding data. Note that FILES contain data only if the requested method is post and the <form> with enctype= "Multipart/form-data" is present. 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, and here are some examples: the length of the body of the content_length--request (is a string).    The MIME type of the body of the content_type--request.    The http_accept--responds to the content-type that can be received.    The http_accept_encoding--response can receive the encoding.    The http_accept_language--responds to the languages that can be received.    http_host--the HTTP HOST header sent by the customer service side.    Http_referer--referring page.    The user-agent string for the http_user_agent--client.    query_string--the query string as a single string (in unresolved form).    The IP address of the remote_addr--client.    The host name of the remote_host--client.    remote_user--the user after server authentication.    request_method--a string, such as "GET" or "POST".    The host name of the server_name--server.   The port of the server_port--server (is a string).    As you can see from above, any HTTP header in the request is converted to a META key except Content_length and CONTENT_TYPE, all uppercase letters are capitalized and the connector is replaced with an underscore, followed by a HTTP_ prefix. So, a head called X-bender is converted to the Http_x_bender key in META. 10.httprequest.user A An object of type Auth_user_model that represents the currently logged-on user. If the user is not currently logged in, the username is set to an instance of Django.contrib.auth.models.AnonymousUser.    You can differentiate them by is_authenticated ().    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 user class models. The Anonymoususer Django.contrib.auth.models.AnonymousUser class implements the Django.contrib.auth.models.User interface, but has the following distinct points: ID is always non    E.    Username is always an empty 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 () raise Notimplementederror. New in Django 1.8: New Anonymoususer.get_username () to better simulate django.contrib.auth.models.User. 11.httprequest.session is a readable andWrites a dictionary-like object that represents the current session.    Available only if Django enables session support. See the documentation for the session for complete details." "
Method
" "1.httprequest.get_host () returns the original host of the request from Http_x_forwarded_host (if Use_x_forwarded_host is turned on, default is False), and Http_host header information is returned.  If these two headers do not provide a corresponding value, use server_name and Server_port, which are described in detail in pep 3333.  Use_x_forwarded_host: A Boolean value that specifies whether the X-forwarded-host header is preferred and can be used only if the proxy has the header set. For example: "127.0.0.1:8000" NOTE: When the host is behind multiple agents, the Get_host () method will fail. Unless you use middleware to rewrite the header of the agent.  2.httprequest.get_full_path () returns path if the query string can be added. For example: "/music/bands/the_beatles/?print=true" 3.httprequest.get_signed_cookie (Key, Default=raise_error, salt= ", Max_  Age=none) Returns the value of the signed cookie and returns django.core.signing.BadSignature if the signature is no longer valid.  If the default parameter is supplied, no exception is thrown and the value of default is returned. The optional parameter salt can be used to provide additional protection against security key brute force attacks.        The Max_age parameter is used to check the timestamp of the cookie to ensure that the cookie does not take longer than max_age seconds. Copy Code >>> request.get_signed_cookie (' name ') ' Tony ' >>> request.get_signed_cookie (' NA Me ', salt= ' name-salt ') ' Tony ' # assumes that you are using the same salt >>> request.get_signed_cookie when setting cookies (' Non-existi        Ng-cookie ') ... Keyerror: ' Non-existiNg-cookie ' # triggers exception when no corresponding key >>> 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 > Seconds >>> request.get_signed_cookie (' name ', False, max_age=60) False Copy Code 4.httprequest.is_secure () returns True if the request is secure, that is, the request was initiated over HTTPS.  5.httprequest.is_ajax () returns True if the request was initiated through XMLHttpRequest, by checking that the corresponding header of the http_x_requested_with is the string ' XMLHttpRequest '. Most modern JavaScript libraries will send this header.  If you write your own XMLHttpRequest call (on the browser side), you must manually set this value to allow Is_ajax () to work. If a response needs to be initiated by Ajax based on the request, and you are using some form of cache such as the Django cache middleware, you should use Vary_on_headers (' Http_x_requested_with ') Decorate your view to allow the response to be cached correctly." "

Note: The value of a key-value pair is multiple, such as the input tag of the checkbox type, and the select tag, which needs to be:

Request. Post.getlist ("hobby")

Iv. Response Objects

The HttpResponse object is our area of responsibility compared to the HttpRequest object that was created automatically by Django. Each view we write needs to be instantiated, populated, and returned with a HttpResponse.

The HttpResponse class is located in the Django.http module.

Use

Passing strings

 from Import  = HttpResponse ("Here's the text of theWeb page. "  = HttpResponse ("Text only, please. ", content_type="text/plain")

Set or delete response header information

Response = HttpResponse () response['content-type'text/html; Charset=utf-8'del response['content-type']
Property

Httpresponse.content: Response Content

Httpresponse.charset: Encoding of response content

Httpresponse.status_code: Status code of the response

V. Jsonresponse objects

Jsonresponse is a subclass of HttpResponse that is specifically used to generate JSON-encoded responses.

 from Import  = jsonresponse ({'foo'bar'})print  (response.content) b'{"foo": "Bar"}'

The default is to pass only the dictionary type, and if you want to pass a non-dictionary type, set the Safe keyword parameter.

Response = Jsonresponse ([1, 2, 3], Safe=false)

Vi. Django Shortcut functions

Official documents

Render ()

Render (Request, template_name[, context])

Combines a given template and a given context dictionary, and returns a rendered HttpResponse object.

Its default Content-type header is set to Application/json.

Parameters:     Request: The requested object used to generate the response.     Template_name: The full name of the template to use, optional parameter     context: A dictionary that is added to the template context. The default is an empty dictionary. If a value in the dictionary is callable, the view is called before the template is rendered.     Content_Type: The MIME type to use for the generated document. The default is the value set by Default_content_type.     Status: The state code of the response. The default is 200.

A simple example:
 from Import Render def My_view (Request):     # the code for the view is written here    return ' myapp/index.html ', {'foo'bar'})

The code above equals:

 fromDjango.httpImportHttpResponse fromDjango.templateImportLoaderdefMy_view (Request):#The View code is written here .t = loader.get_template ('myapp/index.html') C= {'Foo':'Bar'}    returnHttpResponse (T.render (c, request))
Redirect ()

The parameters can be:

    • A model: the get_absolute_url () function of the model will be called
    • A view that can have parameters: urlresolvers.reverse will be used to reverse the resolution of the name
    • An absolute or relative URL that will remain intact as the redirected location.

A temporary redirect is returned by default, and passing permanent=true can return a permanent redirect.

Example:

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

Passing an object (ORM related)

The Get_absolute_url () method is called to get the redirected URL:

 from Import  def  My_view (Request)    : ... = MyModel.objects.get (...)     return Redirect (object)

Pass the name of a view

def My_view (Request):     ... return Redirect ('some-view-name', foo='bar')

Pass a specific URL to redirect to

def My_view (Request):     ... return Redirect ('/some/url/')

Of course, it could be a full web site.

def My_view (Request):     ... return Redirect ('http://example.com/')

By default,redirect () returns a temporary redirect. all of the above forms receive a permanent parameter, and if set to True, a permanent redirect is returned:

def My_view (Request):     ... = MyModel.objects.get (...)     return Redirect (object, Permanent=true)

Extended reading:

Temporary redirection (Response status code: 302) and permanent redirection (Response status code: 301) is no different for ordinary users, it is mainly for the search engine of the robot.

A page temporarily redirect to the B page, that search engine included is a page.

A page is permanently redirected to page B, the search engine contains the B page.

Python Learning (32)--django View System

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.