Python Web framework: Views View function

Source: Internet
Author: User
Tags response code what web server python list

What is the life cycle of the Django request?

To put it simply, find the corresponding function (or class) and return the string (or return the rendered string after reading the HTML) by matching the URL correspondence.

Dissected as follows:

1. 当用户在浏览器中输入url时,浏览器会生成请求头和请求体发给服务端,请求头和请求体中会包含浏览器的动作(action),这个动作通常为get或者post,体现在url之中.2. url经过Django中的wsgi,再经过Django的中间件,最后url到过路由映射表,在路由中一条一条进行匹配,,一旦其中一条匹配成功就执行对应的视图函数,后面的路由就不再继续匹配了.3. 视图函数根据客户端的请求查询相应的数据.返回给Django,然后Django把客户端想要的数据做为一个字符串返回给客户端.4. 客户端浏览器接收到返回的数据,经过渲染后显示给用户.


1. Routing system

To design a URL for an app, you need to create a Python module, often called a URLconf(URL configuration). This module is purely Python code and contains a simple map of the URL pattern (simple regular expression) to the Python function (your view). because it is purely Python code, it can be dynamically constructed.

The URL configuration (URLconf) is like the directory of the Web site that Django supports. Its essence is the URL pattern and the mapping table between the view functions to invoke for that URL pattern; In this way, tell Django that calling this code for that URL calls that code for that URL.

Urlpatterns =[url (regular expression, views view function, parameter, alias),] parameter description: A regular expression string a callable object, A string that is typically a view function or a specified view function path, optionally a default parameter (in dictionary form) to pass to the view function an optional name parameter fromDjango.conf.urlsImportURL from.ImportViews Urlpatterns=[url (r'^articles/2003/$', views.special_case_2003),#1. Single Route CorrespondenceURL (r'^articles/([0-9]{4})/$', views.year_archive),#2. Regular-based routingURL (r'^manage/(? p<name>\w*)', views.manage,{'ID': 333}),#3. Add additional parametersURL (r'^index/(\d*)', Views.index, Name='H2'),#4. Set the name for the route map

After you set the name, you can call it in a different place, such as:

 from Import URL  from Import = [    #...    URL (r'^articles/([0-9]{4})/$', views.year_archive, name='  News-year-archive'),    #...]

Use build URLs in templates

<a href="{% url ' news-year-archive '%}">2012 archive</a><ul>{   for in year_list%}<li><a href="{% url ' news-year-archive ' Yearvar%}">{{Yearvar}} archive</a></li>{% endfor%}</ul>

Use the Generate URL in a function

 from Import Reverse  from Import Httpresponseredirect def redirect_to_year (Request):     #  ...    Year = 2006    #  ...    return Httpresponseredirect (Reverse ('news-year-archive', args= (year,)))

Use the Get URL custom Get_absolute_url () method in model

2. Views function

Two core objects are generated in an HTTP request:

HTTP Request: HttpRequest object

HTTP response: HttpResponse object

2.1 Properties and methods of the HttpRequest object:

Path: A string that represents the full path of the requested page and does not contain a domain name.
For example: "/music/bands/the_beatles/"

Httprequest.path_info
Under certain Web server configurations, the URL portion of the host name is divided into the script prefix section and the path Information section. The Path_info property will always contain the path information section, regardless of what Web server is used. Using it instead of path makes it easier for code to switch between test and development environments.
For example, if the app's Wsgiscriptalias is set to "/minfo", when Path is "/minfo/music/bands/the_beatles/" Path_info will be "/music/bands/the_ Beatles/".

Method: The string representation of the HTTP method used in the request. All uppercase.
GET: Class Dictionary object containing all httpget parameters
POST: Class Dictionary object with all HttpPost parameters
For example
ifreq.method== "GET":
Do_something ()
ElseIf req.method== "POST":
Do_something_else ()
It is also possible for the server to receive an empty post request, that is, the form form forms submit the request through the HttpPost method, but there may be no data in the form, so ifreq cannot be used. Post to determine if the HttpPost method is used; ifreq.method== "POST" should be used

Cookies: A standard Python Dictionary object containing all cookies; keys and values are strings.

Files: A class Dictionary object that contains all the uploaded files, and each key in files is <inputtype= "file" name= ""/> Tag
The value of the Name property, and each value in files is also a standard Python Dictionary object that contains the following three keys:

FileName: Upload file name, in string representation
Content_Type: Uploading Files to ContentType
Content: Uploading the original contents of a file


User: is a Django.contrib.auth.models.User object that represents the currently logged-on user. If you access the user's current
Without logging in, user will be initialized to an instance of Django.contrib.auth.models.AnonymousUser. You
The user's is_authenticated () method can be used to identify whether the users are logged in:
Ifreq.user.is_authenticated (); only authenticationmiddleware in Django is activated
This property is only available when

Session: The only read-write property that represents the current session's Dictionary object, which is only available if you have activated the session support in Django.

Httprequest.meta

1 Httprequest.meta2 A standard Python dictionary that contains all the HTTP headers. The specific header information depends on the client and server, and here are some examples:3 4 The length of the body of the content_length--request (is a string). 5 the MIME type of the body of the content_type--request. 6http_accept--response to a content-that can be receivedType. 7 the http_accept_encoding--response can receive the encoding. 8 the http_accept_language--responds to the languages that can be received. 9 http_host--the HTTP HOST header sent by the customer service side. Ten http_referer--referring page.  Onehttp_user_agent--Client-side user-The agent string.  A 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.  the remote_user--The user after server authentication.  -request_method--A string, for example"GET"Or"POST".  - the host name of the server_name--server.  -The port of the server_port--server (is a string).
View Code

Httprequest.get_full_path ()
Returns the path if the query string can be added.
For example: "/music/bands/the_beatles/?print=true"
, such as: http://127.0.0.1:8000/index33/?name=123,

Querydict.getlist (key, default) returns the data of the requested key as a Python list. If the key does not exist and no default value is provided, an empty list is returned. It guarantees that a list of some type is returned, unless the default value is not a list.

2.2 HttpResponse Objects:

For HttpRequest objects, it is created automatically by Django, but the HttpResponse object must be created by ourselves. Each view request processing method must return a HttpResponse object.

HttpResponse class in Django.http.HttpResponse

Common methods for extending on HttpResponse objects:

1) Passing a string: A typical application is to pass a string as the content of the page to the HttpResponse constructor:

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

2) pass-through iterator

Finally you can pass to httpresponse an iterator instead of a string. HttpResponse will immediately process the iterator, save its contents as a string, and discard it

If you need to respond in the form of a data stream from an iterator to a client, you must replace it with the Streaminghttpresponse class.

3)页面跳转: redirect("路径")

4) Render

 from Import Renderrender (Request, Template_name, context=none, Content_type=none, Status=none, Using=none)

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

In layman's words, the content of the context is loaded into a file defined in templates and rendered by a browser.

Request: is a fixed parameter, nothing to say. Note the path name for the file defined in Template_name:templates. For example 'templates\polls\index.html', parameters will be written ' polls\index.html ' context: To pass in the file for rendering rendered data, the default is the dictionary format content_type: The MIME type to use for the generated document. The default is the value set by Default_content_type. The response code for STATUS:HTTP, which defaults to 200.using: The name of the template engine used to load the template. 

Once you create a Template object, you can use the context to pass the data to it. A context is a collection of variables and their values.

Context is represented in Django as the context class, in the Django.template module. Its constructor has an optional parameter: A dictionary-mapped variable and their value. Call the render () method of the template object and pass the context to populate the template:

 from Import Context, template>>> t = template ('My name is {{name}}}. ' )>>> c = Context ({'name''Greg'  })>>> T.render (c) u'My name is Greg. '

Python Web framework: Views View function

Related Article

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.