CherryPy is a minimalist, object-oriented Python framework for building web applications. Known for its simplicity and robustness, CherryPy allows developers to create web applications as if they were simply building any other Python program, without the need to write extensive boilerplate code.
This article provides a detailed overview of CherryPy, along with coding examples to help you get started.
Key Features of CherryPy
- Object-Oriented Design: CherryPy treats classes and methods as first-class citizens, making the framework intuitive and Pythonic.
- HTTP/1.1-Compliant Web Server: CherryPy includes a built-in multi-threaded HTTP server that can handle multiple requests.
- Cross-Platform: It works seamlessly across platforms like Windows, Linux, and macOS.
- Flexible Configuration: Provides a robust configuration system for server and application settings.
- Minimal Dependencies: Lightweight, making it ideal for smaller applications or integrating into larger projects.
Installing CherryPy
To begin using CherryPy, you need to install it. Use pip to install CherryPy:
pip install cherrypy
Creating Your First CherryPy Application
Below is a step-by-step guide to building a basic web application using CherryPy.
Setting Up a Basic CherryPy Application
Create a file app.py with the following content:
import cherrypy
class HelloWorld:
@cherrypy.expose
def index(self):
return "Hello, World! Welcome to CherryPy!"
# Start the CherryPy application
if __name__ == "__main__":
cherrypy.quickstart(HelloWorld())
Explanation:
cherrypy.expose: This decorator exposes the method as a web-accessible URL endpoint.index: Acts as the default method for the root URL/.
Run the Application: Execute the script with:
python app.py
Open your browser and navigate to http://127.0.0.1:8080. You will see the message: Hello, World! Welcome to CherryPy!

Handling Parameters
Modify the HelloWorld class to accept URL parameters.
import cherrypy
class HelloWorld:
@cherrypy.expose
def greet(self, name="Guest"):
return f"Hello, {name}! Welcome to CherryPy!"
if __name__ == "__main__":
cherrypy.quickstart(HelloWorld())
Output:

Access URL: Visit http://127.0.0.1:8080/greet?name=John to see Hello, John! Welcome to CherryPy!
Step 3: Serving Static Files
CherryPy can also serve static files, such as images or CSS.
import os
class StaticServer:
@cherrypy.expose
def index(self):
return "Static file serving demo!"
config = {
'/static': {
'tools.staticdir.on': True,
'tools.staticdir.dir': os.path.abspath('./static')
}
}
if __name__ == "__main__":
cherrypy.quickstart(StaticServer(), '/', config)
Explanation:
A directory named static is already created where you have saved your .py file . You just need to place the image or css file inside the static directory or folder and run the below link.
tools.staticdir.on: Enables static file serving.tools.staticdir.dir: Specifies the directory containing static files.
Place a file image.png in the static directory, then visit http://127.0.0.1:8080/static/image.png to view the file.
Note: In my case the image name is 04.png, so my url is http://127.0.0.1:8080/static/04.png
Output:

Advanced Configuration
CherryPy allows detailed configuration through a cherrypy.config dictionary or a file.
import cherrypy
import os
class ConfigApp:
@cherrypy.expose
def index(self):
return "This app uses advanced configuration!"
config = {
'global': {
'server.socket_host': '127.0.0.1',
'server.socket_port': 9090,
'log.screen': True
}
}
if __name__ == "__main__":
cherrypy.config.update(config)
cherrypy.quickstart(ConfigApp())

Explanation:
server.socket_host: Specifies the server’s IP.server.socket_port: Sets a custom port.
Visit http://127.0.0.1:9090 to see the output.
Let us create a CherryPy application: CherryPy: a “Simple Weather Logger” that lets users log weather updates for their location and view past entries.
import cherrypy
from datetime import datetime
class WeatherLogger:
def __init__(self):
self.weather_data = []
@cherrypy.expose
def index(self):
"""Home page displaying the weather log and form to add new entries."""
weather_log = "<table border='1'>"
weather_log += "<tr><th>Date</th><th>Location</th><th>Weather</th></tr>"
for entry in self.weather_data:
weather_log += f"<tr><td>{entry['date']}</td><td>{entry['location']}</td><td>{entry['weather']}</td></tr>"
weather_log += "</table>"
return f"""
<html>
<head><title>Weather Logger</title></head>
<body>
<h1>Weather Logger</h1>
<h2>Log Weather:</h2>
<form method="post" action="add">
<input type="text" name="location" placeholder="Location" required />
<input type="text" name="weather" placeholder="Weather (e.g., Sunny, Rainy)" required />
<button type="submit">Log Weather</button>
</form>
<h2>Past Weather Logs:</h2>
{weather_log}
</body>
</html>
"""
@cherrypy.expose
def add(self, location, weather):
"""Adds a new weather entry."""
self.weather_data.append({
"date": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"location": location,
"weather": weather
})
raise cherrypy.HTTPRedirect("/")
if __name__ == "__main__":
cherrypy.quickstart(WeatherLogger())
Features
- Log Weather Updates: Users can input the location and weather description.
- View Past Logs: Displays a table of all logged weather entries with timestamps.
- Dynamic Interaction: Updates happen dynamically in the browser.
How to Run the Application
- Save the script as
weather_logger.py. - Run the script using
python weather_logger.py
Open your browser and navigate to http://127.0.0.1:8080.
User Interface
- Weather Log Table: Displays a log of past weather entries with the date, location, and description.
- Input Form: Simple input form for adding new weather entries.
Benefits of Using CherryPy
- Simplicity: Its design philosophy makes it easier to learn and use.
- Performance: The built-in HTTP server is optimized for speed.
- Integration: Easily integrates with third-party libraries like SQLAlchemy, Jinja2, and more.
- Extensibility: Allows customization of the request/response lifecycle through tools.
CherryPy stands out as a versatile, lightweight, and Pythonic web framework that brings simplicity and power to web application development. Its object-oriented approach seamlessly integrates web development with the design philosophies of Python, making it an attractive choice for developers who want to build robust web applications without the overhead of complex configurations or dependencies.
Why Choose CherryPy?
- Minimalistic Design: CherryPy allows developers to focus on the logic and functionality of their application rather than boilerplate code. This makes it ideal for smaller projects or prototypes.
- Scalability and Extensibility: Despite its lightweight nature, CherryPy is powerful enough to scale to handle larger applications. Its modular architecture supports the integration of third-party libraries and custom tools.
- Built-In HTTP Server: The framework comes with a fast, HTTP-compliant server that simplifies deployment. This feature is especially useful for those who need a ready-to-go solution for serving their applications.
- Cross-Platform Support: CherryPy runs seamlessly on various operating systems, ensuring consistency and reliability regardless of the development environment.
- Community and Longevity: Being one of the older frameworks in Python’s ecosystem, CherryPy has a stable community, and its long history attests to its reliability and continued relevance.
Applications of CherryPy
CherryPy’s simplicity and flexibility make it suitable for a wide range of use cases:
- Microservices: Its lightweight nature makes it a great fit for building REST APIs or microservices that are part of a larger ecosystem.
- Prototyping: Developers can quickly prototype and test ideas without worrying about the complexities of larger frameworks.
- Standalone Applications: CherryPy’s embedded HTTP server can power small-scale web applications or administrative tools.
- Integration: Its ability to integrate with libraries like SQLAlchemy, Jinja2, and others expands its utility for more complex applications.
When to Consider Alternatives
While CherryPy excels in simplicity and modularity, there are scenarios where other frameworks might be more suitable:
- If your project requires a full-stack framework with built-in solutions for templating, database integration, and user authentication, frameworks like Django or Flask might be better.
- For applications heavily reliant on asynchronous processing, frameworks like FastAPI.





Leave a Reply