Previous Page Next Page

Understanding the HttpRequest and HttpResponse Classes

Later in this hour, we will discuss how to use the URLconf file to control how Django displays information. You need to understand the basics of Django's HttpRequest and HttpResponse classes. These two classes are simple to use. They allow you to quickly create dynamic code that helps you manage data that gets passed from the web browser through your view code and back out to the web browser.

The HttpRequest object is actually passed into your view function by Django. You use this view to gather and process information about the request in the view function. When you are finished handling the request, the view function is required to return an HttpResponse object.

Retrieving Information from a Web Request Using the HttpRequest Object

The HttpRequest object is a Python class that contains metadata about an HTTP request. The HttpRequest object is passed as the first argument to the view function that is called when the view is activated by a web browser. When you define a view in a views.py file, you must specify a name for the HttpRequest object, just as you did when you edited the people/views.py file in Hour 2, "Creating Your First Website":

def index(request):

When the index function is initiated, you can use the request object to acquire the metadata about the request. The following are some of the most common HttpRequest object attributes you will likely use:

Displaying a Web Page Using the HttpResponse Object

The HttpResponse class in Django's http package allows you to generate a web page as a response to an HTTP request directly from your Python code. Unlike the HttpRequest object, which is created automatically by Django and passed into the view function, you must create your own HttpResponse object. The simplest way to create an HttpResponse object is to import the class from the django.http package using the following code snippet:

from django.http import HttpResponse

There are several ways to build an HTTP response using the HttpResponse object. The simplest method is to create an HTML string and pass it as an argument to the HttpResponse object, as shown in the following code snippet, to generate a web page similar to the one shown in Figure 4.1.

def view_index(request):
    colors = ("BLUE","RED","GREEN")
    html = "<HTML><BODY>\n"
    html += "<H1>Colors Index</H1><HR>\n"
    for c in colors:
        html += "<FONT COLOR=%s><LI>%s</LI></FONT>\n" % (c, c)
    html += "</HTML></BODY>"
    return HttpResponse(html)

Figure 4.1. Web page generated by the view_index code.


You can also treat an HttpResponse object like a file. First, create an HttpResponse object, and then use the write() function to write the HTML code to the object. When you are through writing to the HttpResponse object, use it as a return value for the view function. The following code snippet shows how to use an HttpResponse object as a file to generate the web page shown in Figure 4.2:

def view_calendar(request):
    week week_days = ('Sunday','Monday','Tuesday',\
                 'Wednesday','Thursday','Friday',\
                 'Saturday')
    weeks = 5
    response = HttpResponse()
    response.write("<HTML><BODY>\n")
    response.write("Calendar<HR>\n")
    response.write("<TABLE BORDER=1><TR>\n")
    for d in week_days:
        response.write("<TD>%s</TD>\n" % d)
    response.write("</TR>\n")
    for w in range(1,weeks):
        response.write("<TR>\n")
        for d in week_days:
            response.write("<TD>&nbsp</TD>\n")
        response.write("</TR>\n")
    response.write("</BODY></HTML>")
    return response

Figure 4.2. Web page generated by the view_calendar code.


You can also add and change the HTTP response headers by treating the HttpResponse object like a Python dictionary. The following code snippet sets the mimetype of the HTTP response:

def view index(request):
    response = HttpResponse("<HTML><BODY>Index</BODY></HTML>")
    response['mimetype'] = "text/plain"
    return response

Did you Know?

You do not need to check for the key before deleting the header. Using the Python del function to delete a header from the HttpResponse object, as shown here, does not raise an exception if the key you specify doesn't exist:

del response['mimetype']


Previous Page Next Page