Understanding Cookies ?? in Django
A cookie is a small piece of data usually containing useful information about the client/user. When a user sends a request to the webserver, the webserver returns a response along with some cookies. These cookies are stored on the user's browser. For subsequent requests sent, e.g a POST, GET, e.t.c the cookies are sent along with the request to the webserver.
Analogy for easy understanding ??
Think of the transmission of cookies between the webserver and the user(can also be called your browser) like a tennis match. Now lets give our players (webserver and the user) some names;
When the game begins, Anita (the webserver) serves the tennis ball (the cookie) to Tife (the browser). The ball has a note attached to it with some information, like Tife’s preferences or session details. Tife catches the ball and keeps it. Every time Tife wants to play (make a request), she hits the ball back to Anita with that note still attached, so Anita remembers who Tife is and how the game is going. This back-and-forth continues throughout the match (session), ensuring they both stay in sync.
Uses of Cookies ??
Cookies are used for multiple applications including but not limited to;
Setting Cookies
In django, setting cookies initially takes place in the view e.g
def set_view(request: HttpRequest) -> HttpResponse:
response = HttpResponse(f"<h1>Hello you</h1>")
# Store user cookie in clients machine
response.set_cookie("name", "tinubu")
response.set_cookie("theme", "dark")
return response
From the code snippet above we can see that the response object contains an attribute called set_cookie this attribute stores the cookie in the form of name:value pairs in the client's machine. For a better way of visualising the cookies on the browser see fig.1.
Figure1: A snapshot of the chrome devtools window displaying the cookies that were set by the code snippet above
Getting Cookies
In order to get cookies in django we must use the request.COOKIES argument which accesses the cookies that were retreived from the client.
def get_view(request: HttpRequest) -> HttpResponse:
name: str | None = request.COOKIES.get("name")
response = HttpResponse(f"your name is {name}")
return response
The .get() statement is used to retrieve the specific value of the cookie by utilising the key parameter.
Deleting Cookies
def delete_view(request: HttpRequest) -> HttpResponse:
"""The delete view is used to delete a cookie from the both the client and the server"""
response = HttpResponse("deleted")
response.delete_cookie("name")
return response
Updating Cookies
When updating cookies we can also use the set_cookie() method. The method would update the specific cookie based on the key.
领英推荐
def update_view(request: HttpRequest) -> HttpResponse:
response = HttpResponse("Updated")
response.set_cookie("name", "christabel")
return response
The set_cookie() method
In the set_cookie() django provides us with various attributes in this document we would go over some of them.
def set_view(request: HttpRequest) -> HttpResponse:
response = HttpResponse(f"<h1>Hello you</h1>")
# Store user cookie in clients machine
response.set_cookie("name", "jerry", httponly=True)
response.set_cookie("theme", "dark")
return response
We arrive at this response from our browser console;
Figure two: A snapshot of the browser console.
As you can see from fig.2 above the cookie "name":"jerry" is not visible to our javascript console whereas the "theme:"dark" without the httponly attribute is visible.
Using cookies with the render() function.
As you must have noticed from our code snippets we have been making use of the HttpResponse() Object rather than the "traditional" render() function. This was done to simply understand cookies without bothering about where the templates, context or other attributes would go in the render() function. Now, with our current understanding of cookies we can revert back to our render() function as we were used too by simply just changing the HttpResponse() object to the render() function this is because the HttpResponse() object and the render() function are both of type HttpResponse we can fact check that with the code snippet below;
def set_view(request: HttpRequest) -> HttpResponse:
response = render(template_name="jschool/home.html", request=request)
print(type(response))
return response
Within our terminal we would get a response shown in fig.3 below; Figure Three: Vs code Terminal snippet
Limitations of cookies
Conclusion
Cookies play a crucial role in web development, providing a simple mechanism to store, retrieve, and manage user-specific data across different sessions. In Django, handling cookies is quite straightforward with built-in methods like setcookie(), request.COOKIES, and deletecookie(). By understanding how to set, retrieve, update, and delete cookies, developers can create more personalized and secure web applications. However, while cookies are useful, they come with limitations such as size restrictions and potential security concerns. It's important to use them judiciously, especially in sensitive applications, and take advantage of attributes like secure and httponly to ensure privacy and protection.
With this knowledge, you're better equipped to manage cookies effectively in your Django applications! ??
Acknowledgements
I would like to express my gratitude to the following resources, which were invaluable in helping me create this documentation:
Thank you to these platforms for sharing knowledge and helping in the creation of this blog post.