Description
This article focuses on the view (views.py), which involves routing configuration, defining views, request objects, response objects, State hold, and so on.
One, routing configuration
1. Configuration location (settings.py root_urlconf)
The urls.py that root_urlconf points to in settings.py is the primary routing configuration file.
2. Modify the main route file (Test2.urls)
1 fromDjango.conf.urlsImportURL, include2 fromDjango.contribImportAdmin3 4Urlpatterns = [5URL (r'^admin/', Admin.site.urls),6 #to apply booktest routing files7URL (r'^booktest/', Include ('Booktest.urls'))8]
Urlpatterns is a list of URL () instances, URLs (regular expressions, view functions, names name)
To write urlconf note points:
If you need to capture a value from the URL, you need to set a pair of parentheses around it, such as: URL (r ' ^pro/(\d+)$ ', Views.pro, name= ' Pro '), and the corresponding request URL is [/HTTP/ 127.0.0.1:8000/PRO/112] The red part here is the parameter that needs to be uploaded to the request.
You do not need to add a leading backslash, as should be written as "test/" instead of writing "/test/".
The r preceding each regular expression indicates that the string is not escaped.
Regular expression non-named group, passed to the view by positional parameters
URL (r ' ^ ([0-9]+)/$ ', views.detail, name= ' detail ')
The parameters here are in the order of the regular matches, corresponding to the parameter position of the view. Corresponding detail methods such as: def detail (request, ID)
A regular expression named group, passed to the view by keyword argument, the keyword parameter in this case is ID
URL (r ' ^ (? P<id>[0-9]+]/$ ', views.detail, name= ' detail ')
Pass? The p< parameter name > corresponds to the view parameter name one by one.
Parameter matching rules: takes precedence over named arguments, and uses positional parameters if no named arguments are used.
Each captured parameter is passed to the view as a normal Python string.
3, including other Urlconfs
Create a urls.py file in your app, define the urlconf in your app, and then use include in your project's urls.py:
Matching process: First match with the main urlconf, and then use the remainder to match the application's urlconf, such as:
Use include to remove the redundancy of the urlconf, that is, the part of the completed match will not be used in the next match.
The namespace is defined in the include by namespace for inverse parsing.
4, the URL of the inverse analysis
If you use hard-coded links in your views and templates, it's not as easy to maintain when urlconf changes.
Workaround: Dynamically generate a link address when making a link by pointing to the name of the urlconf
Views: Using the Django.core.urlresolvers.reverse () function
Templates: Using URL template tags
Second, define the view (view function)
def detail (request, ID)
The view essence is a function, the parameter of the view: A HttpRequest instance, a positional parameter obtained from a regular expression, and a keyword parameter obtained through a regular expression group.
In the application directory, the default views.py file, the general view is defined in this file.
If you have too many processing functions, you can define functions into different py files (not recommended, multiple applications are recommended, i.e. new apps are used)
Iii. Request Object
After the server receives the HTTP protocol request, it creates a HttpRequest object based on the message.
The first parameter of the view function is the HttpRequest object.
The API for the HttpRequest object is defined in the Django.http module.
1. Properties
path: A string that represents the full path of the requested page and does not contain a domain name.
method: A string that represents the HTTP request method used by the request, with the common value of GET, POST.
encoding: A string that represents the encoding of the data being submitted.
If none is the default setting for using the browser, typically Utf-8
This property is writable and can be modified to modify the encoding used to access the form data, followed by any access to the property using the new encoding value.
get: A dictionary-like object (querydict object ) that contains all the arguments for how a GET is requested.
Post: A dictionary-like object (querydict object ) that contains all the parameters of the POST request method.
files: A dictionary-like object that contains all the uploaded files.
Cookie: A standard Python dictionary that contains all the cookies and the key values are strings.
session: A read-and-write dictionary-like object that represents the current session and is available only if Django enables session support, as described in "state hold."
2. Methods
Is_ajax (): Returns True if the request was initiated through XMLHttpRequest .
3. Querydict Object
Defined in Django.http.QueryDict.
The properties of the request object get, post are objects of type querydict.
Unlike a Python dictionary, an object of type querydict is used to handle a condition with multiple values for the same key.
Method Get (): Gets the value according to the key:
Only one value of the key can be obtained.
If a piece has more than one value at a time, get the last value.
Method GetList (): Gets the value according to the key:
Returns the value of the key as a list and can get multiple values for a key
4. Get Properties
Request. get[' key ']
Request. Get.get (' key ')
Request. Get.getlist (' key ')
5. Post Properties
Request. post[' key ']
Request. Post.get (' key ')
Request. Post.getlist (' key ')
Iv. Response Objects
The API for the HttpResponse object is defined in the Django.http module.
HttpRequest objects are created automatically by Django, and HttpResponse objects are created by programmers.
Returns data directly without invoking the template.
Invoke template
1. Members of the response
Property:
Context: Represents the returned content, string type.
CharSet: Represents the encoded character set used by response, the string type.
Status_code: The status code of the HTTP response for the response.
Content-type: Specifies the MIME type of the output.
Method:
Init: Instantiating a HttpResponse object using page content
Write (CONTETN): writes as a file.
Flush (): Outputs the buffer in a Wei-jian way.
Set_cookie (Key, value= ", Nax_age=none, Expires=none): Sets the cookie.
Both key and value are string types;
Max_age is an integer that indicates that it expires after a specified number of seconds
Expires is a datetime or Timedelta object, and the session expires at this specified date/time, noting that datetime and Timedelta values can be serialized only when Pickleserialize is used
Max_age and expires two select one
If you do not specify an expiration time, it expires after two weeks.
Delete_cookie (key): Deletes the specified key cookie if the key does not exist and nothing happens.
2, sub-class Httpresponseredirect
Redirect, service-side jump, the first parameter of the constructor is used to specify the address of the redirect:
Recommended use of Reverse parsing
3, sub-class Jsonresponse
Returns JSON data, typically used for asynchronous requests. __init__ (data), which helps the user create a JSON-encoded response, the parameter data is a Dictionary object.
The default content-type for Jsonresponse is Application/json.
4. Shorthand function
Render View Render
redirect
V. State retention
1. Enable session
Projects created using Django-admin startproject MyApp are enabled by default session
Open just modify the settings.py file
Disable session: Delete The two values specified above, disabling sessions will save some of the performance cost.
2. Use session
After a session is enabled, each HttpRequest object will have a session property, which is an object of a class dictionary
Get (' key ', Default=none): Gets the value of the session based on the key.
Clear (): Clear all sessions.
Flush (): Deletes the current session data and deletes the session's cookie.
Del request.session[' member_id ': delete session
[Python] Getting Started with the Django Framework 3--in-depth view