Python

Use of Django Request and Response Objects

The Request-response cycle is used to transfer the data between the client and server in all types of web APIs. The client-server architecture is used in the Django framework to implement the web application. The request and response are the two main components of the client-server application. An HttpRequest object is created in the Django application when a client requests any resource. A particular view function is used to handle the request and send the response using the HttpResponse object. The uses of different attributes and methods of HttpRequest and HttpResponse classes of the Django framework will be explained in this tutorial.

Django HttpRequest Class:

HttpRequest class is used to handle the client request that is defined in the django.http module. The attributes of this class are mentioned below.

HttpRequest Attributes:

Attribute Name Purpose
HttpRequest.path The full path of the requested page is returned by this attribute. The scheme or domain is not included in the returned value.
HttpRequest.path_info The path info part of this path is shown by this attribute.
HttpRequest.method The HTTP method used for the request is shown by this attribute.
HttpRequest.scheme The scheme of the request (HTTP or HTTPs) is represented by this attribute.
HttpRequest.body The raw HTTP request body is returned as a byte string by this attribute.
HttpRequest.GET All HTTP GET parameters are returned by this attribute as a dictionary object.
HttpRequest.POST All HTTP POST parameters are returned by this attribute as a dictionary object.
HttpRequest.COOKIES All available cookies are returned by this attribute.
HttpRequest.FILES All uploaded files are contained by this attribute.
HttpRequest.META All available HTTP headers are shown by this attribute.
HttpRequest.content_type The MIME type of the request that is parsed from the CONTENT_TYPE header is shown by this attribute.
HttpRequest.content_params A dictionary object that is included in the CONTENT_TYPE header is returned by this attribute.
HttpRequest.encoding The used current encoding to decode the submitted form data is shown by this attribute.

HttpRequest Methods:

Method Purpose
HttpRequest.get_host() It is used to return the actual hostname of the request.
HttpRequest.get_full_path() It is used to return the path and the query string if available.
HttpRequest.get_port() It is used to return the port number of the request.
HttpRequest.is_secure() If the request is made by using HTTPS, then it returns as True otherwise False.
HttpRequest.is_ajax() If the request is made by using XMLHttpRequest, then it returns as True otherwise False.
HttpRequest.build_absolute_uri (location) It is used to return the absolute URI location.
HttpRequest.get_signed_cookie (key, default=RAISE_ERROR, salt=”, max_age=None) It is used to return the cookie value for a signed cookie or raises a django.core.signing.BadSignature exception for the invalid signature.

Django HttpResponse:

HttpResponse class is used to handle the client response that is defined in the django.http module. The attributes of this class are mentioned below.

HttpResponse Attributes:

Attribute Name Purpose
HttpResponse.status_code HTTP status code of the response is returned by this attribute
HttpResponse.charset The char-set that is used to encode the response is defined by this attribute.
HttpResponse.streaming The default value of this attribute is False.
HttpResponse.content The content is represented in byte string by this attribute.
HttpResponse.reason_phrase The HTTP reason phrase of the response is defined by this attribute.
HttpResponse.closed When the response is closed, then this attribute will return True.

HttpResponse Methods:

Method Description
HttpResponse.__init__(content=”, content_type=None, status=200, reason=None, charset=None) An HttpResponse object with the given page content and content type are initiated by this method.
HttpResponse.__getitem__(header) The value of the particular header name is return by this method.
HttpResponse.__setitem__(header, value) The particular value is set to the particular header name by this method.
HttpResponse.__delitem__(header) The particular header name is deleted by this method.
HttpResponse.setdefault(header, value) The default header value is set by this method.
HttpResponse.has_header(header) The existence of the particular header name is checked by this method.
HttpResponse.write(content) The file-like response object is created by this method.
HttpResponse.getvalue() The value of HttpResponse.content is retrieved by this method.
HttpResponse.readable() The stream-like object of HttpResponse class is created by this method.
HttpResponse.seekable() This method is used to make the response object seek-able.
HttpResponse.tell() This method is used to create an HttpResponse instance as a file-like object.
HttpResponse.flush() This method is used to flush the response object.

Prerequisites:

Before practicing the script of this tutorial, you must complete the following tasks:

A. Install the Django version 3+ on Ubuntu 20+ (preferably)
B. Create a Django project
C. Run the Django server to check the server is working properly or not.

Setup a Django App:

A. Run the following command to create a Django app named reqresapp.

$ python3 manage.py startapp reqresapp

B. Run the following command to create a user for accessing the Django database. If you have made the user before then, you don’t need to run the command.

$ python3 manage.py createsuperuser

C. Add the app name in the INSTALLED_APP part of the settings.py file.

INSTALLED_APPS = [
    …..
    'reqresapp'
]

Modify the Necessary Files:

Modify the views.py file with the following script. The index() function of the script will read the request path, method, and user agent by using three HttpRequest attributes. Next, these values will be sent to the browser by using HttpResponse() method.

views.py

# Import HttResponse
from django.http import HttpResponse

# Define function to handle request and response
def index(request):
    path = request.path
    method = request.method
    userAgent = request.META['HTTP_USER_AGENT']
    # request is handled using HttpResponse object
    return HttpResponse("<center><h1>Testing Django Request Response Cycle</h1><br/>"
                        "<p>Request path : " + path +
                        "</p>Request Method : " + method +
                        "<p>User Agent : " + userAgent + "</p></center>")

Modify the urls.py file with the following script for defining the path to call the index() function of the views.py file.

urls.py

# Import path
from django.urls import path
# Import view
from reqresapp.views import index

# Define path
urlpatterns = [
    path('', index),
]

Run the following command to start the Django server.

$ python3 manage.py runserver

Run the following URL from the browser to check the output of the app.

http://localhost:8000

The following output shows the values of three HttpRequest attributes sent by HttpResponse.

Conclusion:

How the different attributes and methods of HttpRequest and HttpResponse can be used in the Django app are shown in this tutorial. The Django users will be able to use the Django request and response objects after reading this tutorial.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.