Django View summary [URLs match, HttpRequest object, HttpResponse object, object serialization acceptance and case]

Source: Internet
Author: User
Tags object serialization set cookie

Features of the View:

Receives the request, processes it, and returns the reply.

The contents returned by the view are:
    • HttpResponse object or Sub-object
    • Render returns an object of HttpResponse
    • Jsonresponse is a subclass of HttpResponse
    • Httpresponseredirect is also a httpresonse subclass.
    • Redirect is a shorthand for httpresponseredirect.

Summary : So the content returned by the view is generally: Render,redirect,jsonresponse,httpresponse

Define a view function in two steps: Defining a View

View functions defined in view.py

def index (request):p Assreturn httpresponse ("Hello python")

Note: You must set a parameter in the parameter: request (the object with request HttpRequest) needs to return a HttpResponse object returned to the browser to display the content

Parameters may also include:

    • The keyword parameters obtained from the regular expression group.
    • The positional parameters obtained from the regular expression group.
Two: Configure URLTo configure the URL process:
    • Include URL files for specific applications in your project's URLs file, and include specific URLs and view correspondence in your application's URLs file.
    • A URL configuration item is defined in a list called Urlpatterns, where each element is a configuration item, and each configuration item invokes a URL function.
Two kinds of syntax for URL functions
    • URL (' Regular expression ', include (' Applied URLs file '))
    • The URL (' regular expression ', the name of the view function).
Development-Time Method:
    • 1. Configure the URL file in the project
Urlpatterns = [    url (r ', include ("app name. URLs")]
    • 2. Create a urls.py file in the app to match
Urlpatterns = [    url (R ' ^index$=$ ', corresponding matching function),    # The exact match is done here)
The matching process for URLs

Url:http://127.0.0.1:8000/aindex/?a=3

# Urls.pyurl in the project (R ' ^a ', include (' Booktest.urls ')), # urls.py configuration URL in the app (R ' ^index/$ ', Views.index),
    1. Remove the domain name and the following parameters, leaving the/aindex/, then the front/remove, leaving the aindex/
    2. Take index/first to the project in the url.py file from the top to bottom of the match, after the successful execution of the corresponding processing action, is to match the successful part of the a character removal, and then take the rest of the index to the application of the urls.py file from the top to bottom of the match.
    3. If the match succeeds, the corresponding view is invoked to produce the content returned to the client. A 404 error is generated if the match fails.
Error message:
    • 404: The page cannot be found, after debugging mode is turned off, a standard error page is displayed by default, and if you want to display a custom page, you need to customize a 404.html file under the Templates directory.
    • 500: Server-side error.
    • 400: Illegal client request error.

If you want to see the error view instead of debugging information, you need to modify the debug entry for the test3/setting.py file.

debug = False # debug Off allowed_hosts = [' * ',] #表示允许所有的地址访问
To capture URL parameters:

When a URL match is made, the desired captured part is set to a regular expression group so that the Django framework automatically passes the contents of the corresponding group as parameters to the view function after the match succeeds.
1) Position parameters
Positional parameters, parameter names can be arbitrarily specified

URL (r ' ^delete_ (\d)/$ ', Views.show_add_cookie),

2) keyword parameter: Name the regular expression group on the basis of the positional parameters.
? p< Group name >
Note: The keyword parameter, the view parameter name must be the same as the regular expression group name.

URL (r ' ^ (delete (? p<bid>\d+))/$ ', Views.show_arg),

Note: Do not mix the two parameters in a way that only one parameter can be used in a regular expression.

HttpRequest Object

When the server receives an HTTP protocol request, it creates a HttpRequest object based on the requested information, which does not need to be created, and the first parameter of the view must be an HttpRequest object

Property:
    • 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 method used by the request, and the common values are: ' GET ', ' POST '.
      • In the browser, give the address to make a request using Get method, such as hyperlink.
      • Click the form's Submit button in the browser to initiate the request if the form's method is set to post.
    • Encoding: A string that represents the encoding of the data being submitted.
      • If none is the default setting for using the browser, it is generally utf-8.
      • This property is writable and can be modified to modify the encoding used to access the form data, and then any access to the property will use the new encoding value.
    • Get: A dictionary-like object that contains all the arguments for how a get is requested.
    • Post: A dictionary-like object that contains all the parameters of the Post request method.
    • Files: A dictionary-like object that contains all the uploaded files.
    • Cookies: A standard Python dictionary that contains all the cookies, keys, and values as strings.
    • Session: A read-and-write dictionary-like object that represents the current session and is available only when Django enables session support, as detailed in "State hold."
Get property:

Request format: Used at the end of the request address, followed by "key = value" in the format of splicing, multiple key-value pairs with & connection.
Example: The URL is as follows

Http://www.itcast.cn/?a=10&b=20&c=python

The request parameters are:

A=10&b=20&c=python

Summarize:

    • Parse request parameters, key ' A ', ' B ', ' C ', value ' 10 ', ' 20 ', ' Python '.
    • In Django, you can use the Get property of the HttpRequest object to get the parameters requested by the Get method.
    • The Get property returns an object of type querydict, and the key and value are string types.
    • Keys are determined by the developer as they write the code.
    • Values are generated based on the data.
Psot Properties:

When using a form form request, Method mode is post and the POST request is initiated, the Post property of the HttpRequest object is used to receive the parameter, and the Post attribute returns an object of type Querydict.
How to submit parameters :

    • The value of the Value property of the control Name property is the value of the key, which constitutes a key-value pair submission.

Summarize:

    • If the control does not have a Name property, it is not committed.
    • For a CheckBox control, the value of the Name property is the same as a group, and the selected item is committed with a one-key multi-value case.
    • The key is the value of the control's Name property, which is written by the developer.
    • Values are filled in or selected by the user.
    • The value of the post submission can be seen in the browser's request body
Querydict object:

The properties of the HttpRequest object get, post are querydict types of objects and Python dictionaries, objects of type querydict are used to handle the same key with multiple values
method Get ():

Get a value by key if a key has more than one value at a time, the last value is obtained

Returns a value of None if the key does not exist, you can set the default value for subsequent processing
Example:

Dict.get (' key ', default value)

can be shortened to

dict[' key ']

Method GetList ():

Gets the value from the key, the value is returned as a list, and all the values of the specified key can be obtained
Returns an empty list if the key does not exist [], you can set a default value for subsequent processing
Example:

Dict.getlist (' key ', default value)
HttpResponse Object Properties
    • Content: Indicates what is returned.
    • CharSet: Represents the coded character set used by response, which defaults to Utf-8.
    • Status_code: Returns the HTTP response status code.
    • Content-type: Specifies the MIME type of the returned data, which defaults to ' text/html '.
Method
    • Init: The initialization of the returned content is completed after the HttpResponse object is created.
    • Set_cookie: Set cookie information.
    • Write: Writes data to the response body.
    • A cookie is a piece of plain text information that a Web site stores in a browser in a key-value pair format for user tracking.
      • 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.
      • Max_age and expires two choose one.
      • If you do not specify an expiration time, the cookie expires when you close the browser.
Set_cookie (Key, value= ", Max_age=none, Expires=none)
    • Delete_cookie (key): Deletes the cookie for the specified key and does not occur if key does not exist.
Sub-class Jsonresponse

When using JavaScript to initiate an AJAX request in the browser, the JSON-formatted data is returned, and the class Jsonresponse inherits from the HttpResponse object, which is defined in the Django.http module and receives the dictionary as a parameter when the object is created.
The Content-type of the Jsonresponse object is ' Application/json '.

Example

def get_data_by_ajax (Request): "" "    wait two seconds to send Request" ""    time.sleep (2)    return Jsonresponse ({"res": 1})
Sub-class Httpresponseredirect

When a logical processing is done, it is not necessary to render the data to the client, but to go back to the other pages, such as the success of the addition, the success of the modification, the data list is displayed after successful deletion, and the list view of the data has been developed, there is no need to rewrite the code of the list, but to go to this view At this point, you need to simulate the effect of a user request, from one view to another, called a redirect.

    • Django provides Httpresponseredirect object implementation redirection, which inherits from HttpResponse and is defined in the Django.http module.
    • The returned status code is 302.
    • redirect Shorthand function redirect
    • Page redirection: Instead of returning to the page, the server tells the browser to request another URL.

Example

def demo_redirect (Request): "" "Page redirect" ""    return redirect ('/index/')
Serialization of query Set objects

Operations that require the serialization of a query set when returning JSON data
Import:

From Django.core import serializers

Using the method inside the serializers
# Serialization of query sets

Books = Serializers.serialize (' json ', books) # "parameter a serialized parameter of type parameter

# returns the resulting value

Jsonresponse ({' Books ': books})

# to the template file is a string into a JSON object

Books = $.parsejson (data.books)
# Books is a JSON object for each element of an array for each array
case of Object serialization
def Get_book (Request):     """ get a view of book information """ = BookInfo.objects.all ()    #  serializes the query set books =         Serializers.serialize ('json', books)    return Jsonresponse ({"books": Books})
View Code
<!    DOCTYPE html>        $(function() {$.get ('/get_book1/',function(data) {//turn a string into a JSON objectBooks =$.parsejson (data.books) content= ' '//iterating over one of the objects gets the property valueContent + = ' <tr> '$.each (books[0].fields,function(Key, Val) {content+ = ' <td> ' +key+ ' </td> '}) Content+ = ' </tr> '//facilitates printing out each object$.each (Books,function(index, data) {content+ = ' <tr> '//traverse the value of the fields that print each of the objects inside$.each (Data.fields,function(Key, Val) {content+ = ' <td> ' +val+ ' </td> '}) Content+ = ' </tr> '                })                $(' #tab '). Append (Content)})})</script>Template Code

Django View summary [URLs match, HttpRequest object, HttpResponse object, object serialization acceptance and case]

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.