Table of contents
1.
Introduction 📝 🔖
2.
Cookies 🎫
3.
Using sessions 🌐
4.
Filesystem backend ⚙️
5.
Memcached backend🖥️
6.
Other backends🎛️
7.
Frequently Asked Question❓
7.1.
What is cherrpy?
7.2.
What is the use of cookies?
7.3.
Is CherryPy free and open source?
7.4.
Is CherryPy a web server?
7.5.
What exactly is the CherryPy framework?
8.
Conclusion ✉️
Last Updated: Mar 27, 2024
Easy

Cookies module and sessions in cherryPy

Author Alok Pandey
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction 📝 🔖

Have you heard the word cherryPy? No, it's not any fruit name, CherryPy is a Python web framework that provides a user-friendly interface to the HTTP protocol for Python developers. It's also known as a web application library. In this article, we will discuss the Cookies module and sessions in cherryPy. We will also discuss the Filesystem backend and Memcached backend.

Cookies module and sessions in cherryPy

Cookies 🎫

To manage cookies, CherryPy employs Python's Cookie module, specifically the Cookie.SimpleCookie object type.

  • Set cherrypy.response.cookie[key] = value  to send a cookie to a browser.
     
  • Cherrypy.request.cookie[key]  is used to retrieve a cookie sent by a browser.
     
  • To delete a cookie (on the client side), send it with the expiration time set to 0:
     
cherrypy.response.cookie[key] = value
cherrypy.response.cookie[key]['expires'] = 0
You can also try this code with Online Python Compiler
Run Code


It is critical to recognize that request cookies are not automatically copied to response cookies. Clients will send the same cookies with each request, so cherrypy.request.cookie should be filled in each time. However, because the server does not have to send the same cookies with each response, cherrypy.response.cookie is usually empty. To "delete" (expire) a cookie, you must first set cherrypy.response.cookie[key] = value and then set its expires attribute to 0.

Example:

import cherrypy
class MyCookieApp(object):
    @cherrypy.expose
    def set(self):
        cookie = cherrypy.response.cookie
        cookie['cookieName'] = 'cookieValue'
        cookie['cookieName']['path'] = '/'
        cookie['cookieName']['max-age'] = 3600
        cookie['cookieName']['version'] = 1
        return "<html><body>Hello,you can see your cookies</body></html>"

    @cherrypy.expose
    def read(self):
        cookie = cherrypy.request.cookie
        res = """<html><body>Hello, Welcome %s cookies.<br />
               You can see the cookies list/values:<br />""" % len(cookie)
        for name in cookie.keys():
            res += "name: %s, value: %s<br>" % (name, cookie[name].value)
        return res + "</body></html>"


if __name__ == '__main__':
    cherrypy.quickstart(MyCookieApp(), '/cookie')
You can also try this code with Online Python Compiler
Run Code

 

Using sessions 🌐

Sessions are a popular mechanism for developers to identify users and synchronize their activity. CherryPy does not activate sessions by default because it is not a required feature; to enable it, simply add the following settings to your configuration:

[/]
tools.sessions.on: True
You can also try this code with Online Python Compiler
Run Code

 

cherrypy.quickstart(home, '/', "home.conf")
You can also try this code with Online Python Compiler
Run Code


Sessions are stored in RAM by default, so if you restart your server, all of your current sessions will be lost. You can instead store them in Memcached or on the filesystem.

The following is how you use sessions in your applications:

import cherrypy

@cherrypy.expose
def index(self):
	if "count" not in cherrypy.session:
		cherrypy.session["count"] = 0
	cherrypy.session["count"] = 1
You can also try this code with Online Python Compiler
Run Code


Every time the index page handler is called in this snippet, the current user's session's 'count' key is increased by one.

CherryPy determines which session to use by inspecting the cookie that is sent with the request. This cookie contains the session identifier that CherryPy uses to retrieve the user's session from storage.

Filesystem backend ⚙️

Using a filesystem is a simple way to ensure that your sessions are not lost between reboots. In Cherry Py each session is saved in its own file in the directory specified by the user.

[/]
tools.sessions.on: True
tools.sessions.storage_class = cherrypy.lib.sessions.FileSession
tools.sessions.storage_path = "/any/directory"
You can also try this code with Online Python Compiler
Run Code

Memcached backend🖥️

Memcached is a widely distributed key store on top of your RAM. We can use this package if you want to share sessions outside of the CherryPy process.

It is necessary to Install the Python Memcached package, which can be demonstrated by installing cherrypy[memcached_session]. The following code demonstrates the use of the Python Memcached package:

[/]
tools.sessions.on: True
tools.sessions.storage_class = cherrypy.lib.sessions.MemcachedSession
You can also try this code with Online Python Compiler
Run Code

Other backends🎛️

Any other library can implement a session backend. Simply subclass cherrypy.lib.sessions.Session  and mark it as tools.sessions.storage_class.

Frequently Asked Question❓

What is cherrpy?

CherryPy is a Python web framework that provides a user-friendly interface to the HTTP protocol for Python developers.

What is the use of cookies?

Cookies allow websites to remember you, your website logins, shopping carts, and other information. They can, however, be a goldmine of private information for criminals to snoop on.

Is CherryPy free and open source?

CherryPy is an open-source project, so contributions are welcome. If you're interested, you can fork CherryPy on GitHub and submit a pull request with your changes.

Is CherryPy a web server?

In Brief: CherryPy WSGI Web Server. It is a modular component that can serve any Python WSGI web application.

What exactly is the CherryPy framework?

CherryPy is an object-oriented web application framework that is written in Python. It is intended for the rapid development of web applications by wrapping the HTTP protocol, but it remains at a low level and does not provide much more than RFC 7231 defines.

Conclusion ✉️

In this article, we have extensively discussed the Cookies module and sessions in cherryPy in detail. If you would like to learn more, check out our articles on

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. 

Enroll in our courses and refer to the mock test and problems available.

Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow. 

Happy Coding!

Live masterclass