Request and Response in Django

Request and Response in Django

ยท

5 min read

When a page is requested, Django under the hood created a HttpRequest object, this HttpRequest object contains meta information about the request. This is the same request object we talked when we created our view function def profile_view(request):... (check type of request to confirm i.e print(type(request)) # must be HttpRequest class). When a view function receives a HttpRequest object as its first argument, this view function must return and HttpResponse object.

A sample view,

def profile_view(request):             # first parameter HttpRequest Object
    return HttpResponse("Hello World") # view returned HttpResponse Object

The HttpRequest object

Many of us might just ignore this Request object thinking its of no use, but trust me there are lots of meta information about our request, which we may need in our program/view function to properly execute our logic.

Some of the attributes and methods of HttpRequest objects are:

  1. HttpRequest.path (request.path in our view function, which give us path i.e: /profile/)
  2. HttpRequest.path (request.method in our view function, which gives us Uppercase request method i.e: GET, POST, HEAD)
  3. HttpRequest.GET (request.GET in our view function, which gives us all HTTP GET parameters in dict like object)
  4. HttpRequest.POST (request.POST in our view function, which gives us all HTTP POST parameters in dict like object)
  5. HttpRequest.FILES (request. [Text](Link) FILES in our view function, which gives us all uploaded files from HTML form in a dict like object)
  6. HttpRequest.headers (request.headers in our view function, which gives us all HTTP headers in a dict like object)
  7. HttpRequest.user (request.user in our view function, which gives us currently authenticated user. This attribute is set from middleware. We will look into this in later section of our series)

It consist of some useful methods as well i.e: HttpRequest.get_host() HttpRequest.get_port() HttpRequest.is_secure() #https or not which you can try and experiment yourself.

The HttpResponse object

We learnt about HttpRequest object, which was automatically created by the Django itself and get passed to the view function. But on the other hand, its our duty as a programmer to return and HttpResponse object from view function like we did in previous example.

from django.http import HttpResponse

response = HttpResponse("Hello World")

we can also add our content incrementally

response = HttpResponse()
response.write("hello ")
response.write("world")

JsonResponse object

It is also possible to have a JSON encoded response.

from django.http import JsonResponse

response = JsonResponse({"message":"Hi from djangotherightway.com"})

But, remember everything under the hood is a HttpResponse()

complete example,

from django.http import JsonResponse

def message_view(request):
  return JsonResponse({"message":"Hi from djangotherightway.com"})

if you want to serialize and response non-dict objects then make sure you include safe=False in JsonResponse JsonResponse([1,2,3],safe=False)

Returning 404 errors from HttpResponse

Every Http response must have a status code. 404 is one of the status code frequently used to denote that the requested page was not found

from django.http import HttpResponse, HttpResponseNotFound

def home_view(request):
    if some_condition:
        return HttpResponseNotFound("Page not found")
    else:
        return HttpResponse("Page found")

Let's take some examples

  • Finding our request method in our view function
def home_view(request):
    if request.method == 'GET':
        # do something for GET
    elif request.method == 'POST':
        # do something for POST here
    else:
        # fallback? or and error response?
  • Returning custom HTTP status code
from django.http import HttpResponse

def home_view(request):
    if some_condition:
        return HttpResponse(status=403) # 403 means permission denied 
    else:
        return HttpResponse(status=200) # 200 means OK

But, what are Http status code?

  • Status code are some numbers issued by server in response to a client request
  • Status code are divided up into five groups as follows where first digit refers to the category of the response
    • 1XX (informational response)
    • 2XX (Successful)
    • 3XX (Redirection)
    • 4XX (Client error)
    • 5XX (Server error)
  • Examples;
    • If server responds with status code 404 means it lies to Client error group and 404 means Page Not Found
    • If server responds with status code 500 means it lies to Server error group and 500 means Internal Server Error

Now being a backend engineer there lies a confusion, on how to select a status code. Actually this totally depends on the situation you are in and the requirements you are in(has nothing to do with web framework or stacks you are working on) but we always should follow a standard widely accepted by the community. Let's try to understand it more with an example;

  • Status code 3XX means Redirection category, to be more specific let's assume 308 status code which means Permanent Redirection. So to inform a client of a redirection you simply respond with a 308 status code and a Location to where the client should redirect. This way client simply performs a redirection because client knows the use case of 308 status code. But what is a client? Is't this a client side software created by engineers? So, it's a client side engineer duty to implement those, but what if we make changes on status code(maybe 200 instead of 308) to perform this same operation? This is also possible
  • To perform the same redirection work, now server will send 200 status code with some data {'redirect_to':'https://djangotherightway.com'}. This way on the client side we simply implement a logic where we check for redirect_url on 200 status and implement redirection. On a JS client side you will redirect a user to other location using a simple code window.location.replace("https://djangotherightway.com");

So, does this mean we can use any status code for performing operations? The simple answer would be No, this is a suggestion only and my suggestion is Let's follow standards to make our community much more stronger, but what about the example i just explain above? Well, some case might arise up when you need to customize according to your need and may need to skip the standard but try to be on the standard as much as possible

Standard Matters because since 3XX means a redirection have you ever noticed your browser will automatically redirect you to another location incase your browser gets 3XX. Browser does this for making user experience good and doesn't mean browser will react on every status code they see from the server.

Do you want to see this browser behaviour in action? type https://djangotherightway.com/learn in the browser and you will be redirected to https://djangotherightway.com/series/learn all with the help of a simple status code 301 which means Moved Permanently