Cookies are small text files stored in a user's web browser directory. Websites and applications use cookies to validate a user's identity. Without cookies users will have to enter their login credentials on every page.
CherryPy uses the Cookie.SimpleCookie object type of Python's Cookie module to handle cookies. Below is how to perform basic cookie operations in CherryPy:
To send a cookie to a browser, set cherrypy.response.cookie[key] = value.
To retrieve a cookie sent by a browser, use cherrypy.request.cookie[key].
To delete a cookie, send the cookie with its expiration time set to 0:
Eg.:
cherrypy.response.cookie[key] = value
cherrypy.response.cookie[key]['expires'] = 0
We will now design an application which will set user cookies and display them to the user.
Save the below code in a file named 'cookie.py'.
import cherrypy
class application:
def set(self):
cookie = cherrypy.response.cookie
cookie['cookie_name'] = 'cookie_val'
cookie['cookie_name']['path'] = '/'
cookie['cookie_name']['max-age'] = 3600
cookie['cookie_name']['version'] = 1
return "<html><body>Cookies are now stored in your web browser.</body></html>"
def read(self):
cookie = cherrypy.request.cookie
res = """<html><body>There are {} cookies.<br />
Refer to the below list for more information:<br /><br />""".format(len(cookie))
for name in cookie.keys():
res += "name: {}, value: {}<br>".format(name, cookie[name].value)
return res + "</body></html>"
if __name__ == '__main__':
cherrypy.quickstart(application(), '/cookie')
Run the code through the Terminal/Command Line as follows:
python3 cookie.py
Now, if we enter http://localhost:8080/cookie/set in the address bar of a browser a cookie is now stored and we get the output which tells us about the same.
We can see the cookies stored by entering http://localhost:8080/cookie/read in the address bar. The output shows the cookies we set previously.
Comments