Django uses the request and response objects
When requesting a page, Django wraps the requested metadata data into a HttpRequest object, and Django loads the appropriate view method, passing the HttpRequest object as the first argument to the view method. Any view method should return a HttpResponse object.
We use these two objects extensively in this book; This appendix explains the HttpRequest and HttpResponse objects in detail.
HttpRequest
The HttpRequest represents an HTTP request from Uesr-agent.
Most of the important request information appears as a property of the HttpRequest object (see Table H-1). All other properties are read-only except for the session.
Table H-1. HttpRequest properties of an object
Attribute |
Description |
Path |
The full path of the requested page, excluding the domain name-for example, "/music/bands/the_beatles/". |
Method |
The string representation of the HTTP method used in the request. All uppercase. For example: if Request.method = = ' GET ': Do_something () elif Request.method = = ' POST ': Do_something_else () |
GET |
A class Dictionary object that contains all the HTTP GET parameters. See the Querydict documentation. |
POST |
A class Dictionary object that contains all the HTTP POST parameters. See the Querydict documentation. It is also possible for the server to receive an empty POST request. That is, the form form submits the request through the HTTP POST method, but the form can have no data. Therefore, you cannot use the statement if request. Post to determine whether to use the HTTP POST method; if Request.method = = "POST" (see Method property in this table). Note: Post does not include file-upload information. See the Files property. |
REQUEST |
For convenience, this property is the collection of post and get properties, but it is special to look up the Post property before looking for the Get property. Learn PHP's $_request. For example, if get = {"name": "John"} and post = {"Age": ' 34 '}, the value of request["name"] is "John" and the value of request["age" is "34". It is strongly recommended to use get and POST because the two properties are more explicit and the code written is easier to understand. |
COOKIES |
A standard Python Dictionary object that contains all cookies. Keys and values are both strings. See chapter 12th for a more detailed explanation of cookies. |
FILES |
A class Dictionary object that contains all the uploaded files. Each key in files is the value of the Name property in the <input type= "file" name= "/> Tag. Each value in files is also a standard Python Dictionary object that contains the following three keys:
- FileName: Upload file name, expressed in Python string
- Content-type: Content type for uploading files
- Content: Uploading the original contents of a file
Note: Files has data only if the request method is post and the request page <form> has the enctype= "Multipart/form-data" attribute. Otherwise, FILES is an empty dictionary. |
META |
Contains a dictionary of all available HTTP header information. Example:
- content_length
- content_type
- query_string: Unresolved original query string
- Remote_add R: Client IP address
- remote_host: client hostname
- server_name: Server host name
- server_port: Server port
M These headers in the ETA are prefixed with the HTTP_ most key, for example:
- http_accept_encoding
- http_accept_language
- http_host: HTTP Host header information sent by Customer
- http_referer:referring page
- http_user_agent: Client's user-agent string
- Http_x_ben Der:x-bender header information
|
User |
is a Django.contrib.auth.models.User object that represents the currently logged on user. If the access user is not currently logged in, user is initialized to an instance of Django.contrib.auth.models.AnonymousUser. You can use the user's is_authenticated () method to tell if a person is logged in: If request.user.is_authenticated (): # do something for logged-in users. Else # do something for anonymous users. This property is available only if you activate Authenticationmiddleware in Django For a more detailed explanation of the certification and the user, see Chapter 12th. |
Session |
The only writable property that represents the Dictionary object for the current session. This property is available only if session support in Django is activated. See chapter 12th. |
Raw_post_data |
Raw HTTP POST data, not resolved. Advanced processing is useful. |
The request object also has some useful methods, see table H-2:
Table H-2. HttpRequest Methods |
Method |
Description |
__GETITEM__ (Key) |
Returns the key value of the Get/post, takes the post first, and then takes the get. If the key does not exist, throw keyerror. This is where we can access the HttpRequest object using dictionary syntax. For example, request["foo" is equivalent to request first. post["foo"] then request. get["foo") operation. |
Has_key () |
Check the request. GET or request. Whether the key specified by the parameter is included in the post. |
Get_full_path () |
Returns the request path that contains the query string. For example, "/music/bands/the_beatles/?print=true" |
Is_secure () |
If the request is secure, returns True, that is, the HTTPS request is being made. |
querydict Object
In the HttpRequest object, the Get and post properties are instances of the Django.http.QueryDict class. Querydict A dictionary-like custom class for handling multiple-valued single-touch situations. Because some HTML form elements, for example, <selectmultiple= "multiple", will pass multiple values to a single key.
The Querydict objects are immutable (immutable) unless they are created by copy (). This means that we cannot change the request directly. POST and request. The properties of the get.
QUERYDICT implements all the standard dictionary methods. Also includes some unique methods, see table H-3.
Table H-3. How querydicts differ from standard dictionaries. |
Method |
Differences from Standard DICT implementation |
__getitem__ |
The processing of a standard dictionary is a little different, that is, if the key corresponds to multiple value,__getitem__ (), the last value is returned. |
__setitem__ |
The set parameter specifies the value list of key (a Python list). Note: It can only be called on a mutable querydict object (that is, a copy of the Querydict object produced by copy). |
Get () |
If key corresponds to more than one value,get (), the last value is returned. |
Update () |
The arguments can be querydict, or they can be standard dictionaries. Unlike the standard dictionary update method, this method adds a dictionary items instead of replacing them: >>> q = querydict (' a=1 ')
>>> q = q.copy () # to make it mutable
>>> q.update ({' A ': ' 2 '})
>>> q.getlist (' a ') [' 1 ', ' 2 ']
>>> q[' A '] # returns the last
[' 2 '] |
Items () |
Unlike the standard dictionary's items () method, this method uses the __getitem__ () of the single-valued logic: >>> q = querydict (' a=1&a=2&a=3 ')
>>> Q.items ()
[(' A ', ' 3 ')] |
VALUES () |
A bit different from the values () method of the standard dictionary, the method uses the __getitem__ () of the single-valued logic: |
In addition, Querydict also has some methods, see table H-4.
H-4. Additional (non-dictionary) Querydict methods |
Method |
Description |
Copy () |
Returns a copy of the object, implemented internally using the Python standard Library's copy.deepcopy (). The copy is mutable (can be changed)-that is, you can change the value of the copy. |
GetList (Key) |
Returns all values corresponding to the parameter key, returned as a python list. If key does not exist, an empty list is returned. It ' s guaranteed to return a list of some sort: |
Setlist (Key,list_) |
Set the value of key to List_ (unlike __setitem__ ()). |
Appendlist (Key,item) |
Add item to the internal list associated with key. |
Setlistdefault (Key,list) |
Unlike SetDefault, it takes a list instead of a single value as a parameter. |
Lists () |
and items () is a little different, it returns all values of key as a list, for example: >>> q = querydict (' a=1&a=2&a=3 ')
>>> q.lists ()
[(' A ', [' 1 ', ' 2 ', ' 3 '])] |
UrlEncode () |
Returns a string formatted as a query string (e.g., "a=2&b=3&b=5"). |
A Complete Example
For example, here is an HTML form:
<form action= "/foo/bar/" method= "POST" >
<input type= "text" name= "Your_Name"/>
<select multiple= "multiple" name= "bands" >
<option value= "Beatles" >the beatles</option>
<option value= "who" >the who</option>
<option value= "Zombies" >the zombies</option>
</select>
<input type= "Submit"/>
</form>
If the user enters "JohnSmith" in the Your_Name field and selects "The Beatles" and "the Zombies" in the multi-box, the following is the contents of the Django Request object:
>>> request. get{}
>>> request. POST
{' your_name ': [' John Smith '], ' bands ': [' Beatles ', ' Zombies ']}
>>> request. post[' Your_Name ']
' John Smith '
>>> request. post[' bands ']
' Zombies '
>>> request. Post.getlist (' bands ')
[' Beatles ', ' Zombies ']
>>> request. Post.get (' your_name ', ' Adrian ')
' John Smith '
>>> request. Post.get (' Nonexistent_field ', ' Nowhere man ')
' Nowhere man '
HttpResponse
For HttpRequest objects, it is created automatically by Django, but the HttpResponse object must be created by ourselves. Each view method must return a HttpResponse object.
The HttpResponse class is in Django.http.HttpResponse.
Construction httpresponses
In general, you can construct a HttpResponse object by passing the page contents of a string representation to the HttpResponse constructor:
>>> response = HttpResponse ("Here's the text of the Web page.")
>>> response = HttpResponse ("Text only, please.", mimetype= "Text/plain")
But if you want to add content incrementally, you can use response as a Filelike object:
>>> response = HttpResponse ()
>>> Response.Write ("<p>here's the text of the Web page.</p>")
>>> Response.Write ("<p>here ' s another paragraph.</p>")
You can also pass a iterator as a parameter to HttpResponse without passing a hard-coded string. If you use this technique, here are a few things to keep in mind:
· Iterator should return a string.
· If HttpResponse is initialized with iterator, the HttpResponse instance cannot be used as a Filelike object. Doing so will throw an exception.
Finally, again, HttpResponse implements the Write () method, which allows you to use the HttpResponse object wherever you want to filelike the object. See chapter 11th for some examples.
Set Headers
You can use the dictionary syntax to add, delete headers:
>>> response = HttpResponse ()
>>> response[' X-django ' = "It's the best."
>>> del response[' x-php ']
>>> response[' X-django ']
"It's the best."
You can also use the Has_header (header) method to detect if a header exists.
Do not set the cookie headers manually; see chapter 12th for a detailed explanation of how cookies are handled in Django.
HttpResponse sub-class
Django contains many HttpResponse subclasses that are used to handle different HTTP response types (see table H-5). Like HttpResponse, these subclasses are in Django.http.
Table H-5. HttpResponse Subclasses |
Class |
Description |
Httpresponseredirect |
The constructor accepts a single parameter: the URL to which the redirect is redirected. Can be a full URL (e.g, ' http://search.yahoo.com/') or a relative URL (e.g., '/search/'). Note: This will return the HTTP status code 302. |
Httpresponsepermanentredirect |
Same as Httpresponseredirect, but returns a permanent redirect (HTTP Status Code 301). |
Httpresponsenotmodified |
Constructors do not require arguments. Use this to designate a page hasn ' t been modified since the user's last request. |
Httpresponsebadrequest |
Returns the status code. |
Httpresponsenotfound |
Return to 404 status code. |
Httpresponseforbidden |
Return to 403 status code. |
Httpresponsenotallowed |
Return to 405 status code. It requires a required parameter: A list of allowed methods (e.g., [' GET ', ' POST ']). |
Httpresponsegone |
Return to 410 status code. |
Httpresponseservererror |
Return to the status code. |
Of course, you can also define your own HttpResponse subclasses that are not included in the table above.
return Errors
It is easy to return an HTTP error code in Django. The Httpresponsenotfound, Httpresponseforbidden, Httpresponseservererror and other subclasses are described above. Returning instances of these subclasses in the view method is OK, for example:
def my_view (Request):
# ...
If foo:
Return Httpresponsenotfound (' Else
Return HttpResponse ('
When returning httpresponsenotfound, you need to define the HTML for the error page:
Return Httpresponsenotfound ('
Because the 404 error is the most commonly used HTTP error, there is a more convenient way to handle it.
For convenience, and the entire site has a consistent 404 error page is also friendly, Django provides a Http404 exception class. If a Http404,django is thrown in a view method, it will be captured and returned to the standard error page with an error code 404.
From django.http import Http404
def detail (Request, poll_id):
Try
p = Poll.objects.get (pk=poll_id)
Except Poll.doesnotexist:
Raise Http404
Return Render_to_response (' polls/detail.html ', {' Poll ': P})
In order to use the Http404 exception, you need to create a template file. When an exception is thrown, the template file is displayed. The filename of the template file is 404.html, which is created under the template root directory.
Custom 404 (Not Found) View Method
When the Http404 exception is thrown, Django loads a special view method to handle the 404 error. By default, it is django.views.defaults.page_not_found, responsible for loading and rendering 404.html template files.
This means that we must define the 404.html template file at the template root, which applies to all 404 exceptions.
The Page_not_found view method should be able to handle almost 99% of web apps, but if you want to reload the view method, you can specify handler404 as a custom 404 Errpr View method in the Urlconf file, like this:
From django.conf.urls.defaults Import *
Urlpatterns = Patterns ("',
...
)
handler404 = ' Mysite.views.my_custom_404_view '
Django determines the 404 view method by locating the handler404 in the urlconf file. By default, Urlconfs contains the following line of code:
From django.conf.urls.defaults Import *
In the django/conf/urls/defaults.py module, the handler404 is assigned a value of ' django.views.defaults.page_not_found '.
Attention:
· If the request URL does not match any regular expression in the Django urlconf file, the 404 view method is called.
· If you do not define your own 404 view-using the default 404 view, you still have a job to do: Create a 404.html template file in the template root directory. By default, 404 view will use the template to handle all 404 errors.
· If debug is set to True (in the setting module), the 404 View method will not be used, instead, traceback information.
Custom (Server Error) View Method
Similarly, Django produces special behavior when the view code runs out of error. If the view method produces an exception, Django will invoke the default view method, Django.views.defaults.server_error, which loads the rendered 500.html template file.
This means that we must define the 500.html template file in the template root directory, which applies to all server errors.
The Server_error view method should be able to handle almost 99% of web apps, but if you want to reload the view method, you can specify handler500 as a custom server error view method in the Urlconf file, like this:
From django.conf.urls.defaults Import *
Urlpatterns = Patterns ("',
...
)
handler500 = ' Mysite.views.my_custom_error_view '
Django's HttpRequest object