How To Set, Get & Delete HTML Browser Cookies Using Python?
Python is one of the most powerful scripting languages out there which is known for being aesthetically beautiful when it comes to the codes. A couple of days back, a reader mailed me a question seeking help about how he could use Python to set browser cookies required for the login mechanism which he was trying to build using Python from scratch.
The user was not using any Python web based framework such as Django or Web2py. So here, in this article we will show you how to set HTML browser cookies and then retrieve them and finally delete those cookies all using Python programming language.
Setting HTML Browser Cookies in Python
In order to set HTML browser cookies in a client's browser using python, you just need these two lines of code:
#!/usr/bin/python print 'Set-Cookie:UserID=12345;' #sets the cookie print("Location:<NEWURL>") #redirects to a new page
The above code snippet will create a cookie named UserID in the browser and then set it's value to 12345. After this the user will be redirected to a new page. Please note that, you have to necessarily reload the page or send the user to a new page in order to successfully store the cookies.
Also make sure that you do not print anything before the lines in the code above where the cookie is being stored, else you will never be able to store the cookies in the client browser.
Setting, reading or retrieving HTML Browser Cookies in Python
Once the cookie is set you need to read the value of these cookies. Doing this is also very easy and using the following code snippet you can retrieve all the cookies that have been set in your browser.
#!/usr/bin/python
import Cookie, os
try:
cookie = Cookie.SimpleCookie(os.environ["HTTP_COOKIE"])
return cookie["UserID"].value
except (Cookie.CookieError, KeyError):
return "Error!!!"
The above snippet will retrieve the value of the Cookie UserID which we had set in the previous para and will print it's output. If there is some kind of error in retrieving the cookie, then the error message gets printed.
Deleting a HTML Browser Cookie in Python
Deleting a browser cookie using Python is as simple as setting the cookie. However, when we want to delete a cookie, we just need to set it to an empty value. Here is how we do it:
#!/usr/bin/python print 'Set-Cookie:UserID="";' #sets the cookie to empty value / deletes the cookie print("Location:<NEWURL>") #redirects to a new page
If you find any difficulty understanding this tutorial, then do let us know in the comments section.