Contents
CherryPy: The Cherry Among Giants

CherryPy: The Cherry Among Giants

“Small but mighty — sometimes the best things come in small packages.” 🍒

The Python web framework arena is like an Avengers movie. There is Django (Iron Man, with everything), FastAPI (Spider-Man, young and fast) and Flask (Captain America, everybody's favorite).

Then there is CherryPy: Ant-Man. Small and underestimated, but perfect when you need it.

Prologue: The framework arena

python
# 2025 Python Web Framework Summit

Django: "I have an admin panel, ORM, authentication, templates..."
FastAPI: "I am async, fast, modern, with automatic documentation..."
Flask: "I am flexible and popular, with 54K GitHub stars..."

CherryPy: "I have... a built-in HTTP server?"

Everyone: *awkward silence*

CherryPy: "And I can do anything in 10 lines of code?"

Developer in the corner: "Show me."

*five minutes later*

Developer: "Damn, that is exactly what I need!"

CherryPy: "I told you. I am the cherry on top." 🍒

Chapter 1: The giants

Giant #1: Django (the colossus)

The “batteries included” philosophy

python
# Django simple API
# File structure:
# myproject/
#   myapp/
#     models.py
#     views.py
#     urls.py
#     serializers.py
#     admin.py
#     apps.py
#     tests.py
#   myproject/
#     settings.py
#     urls.py
#     wsgi.py

# models.py
from django.db import models

class User(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(unique=True)
    
# views.py
from django.http import JsonResponse
from .models import User

def get_users(request):
    users = User.objects.all().values()
    return JsonResponse(list(users), safe=False)

# urls.py (app level)
from django.urls import path
from . import views

urlpatterns = [
    path('users/', views.get_users),
]

# urls.py (project level)
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('myapp.urls')),
]

# settings.py (200+ lines of configuration)
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    # ... 190 more lines
]

# Total: 7 files, 300+ lines
# Setup time: 30 minutes
# Ideal for: Enterprise applications

Advantages: Everything included, a free admin panel, and great support for large projects.

Disadvantages: Overkill for a simple API, a steep learning curve, and heavyweight.

Giant #2: FastAPI (the speedster)

The “modern, fast, async” philosophy

python
# FastAPI simple API
# main.py

from fastapi import FastAPI
from pydantic import BaseModel
from typing import List

app = FastAPI()

class User(BaseModel):
    id: int
    name: str
    email: str

users_db = [
    User(id=1, name="John", email="john@example.com"),
    User(id=2, name="Jane", email="jane@example.com")
]

@app.get("/users", response_model=List[User])
async def get_users():
    return users_db

# Run with: uvicorn main:app --reload

# Total: 1 file, 25 lines
# Setup time: 5 minutes
# Auto-generated OpenAPI documentation at /docs
# Ideal for: Modern APIs

Advantages: Very fast, async support, automatic documentation and type hints.

Disadvantages: Requires Python 3.7+, a smaller ecosystem and an external server (uvicorn).

The micro-framework philosophy

python
# Flask simple API
# app.py

from flask import Flask, jsonify, request

app = Flask(__name__)

users = [
    {"id": 1, "name": "John", "email": "john@example.com"},
    {"id": 2, "name": "Jane", "email": "jane@example.com"}
]

@app.route('/users', methods=['GET'])
def get_users():
    return jsonify(users)

@app.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    user = next((u for u in users if u['id'] == user_id), None)
    return jsonify(user) if user else ('Not found', 404)

if __name__ == '__main__':
    app.run(debug=True)

# Total: 1 file, 25 lines
# Setup time: 5 minutes
# Run with: python app.py
# Ideal for: Everything

Advantages: Popular, huge ecosystem, excellent documentation and easy to learn.

Disadvantages: Needs an external production server, is not async by default and can become chaotic in large projects.

Chapter 2: Enter the cherry 🍒

CherryPy: The outsider

The “object-oriented, minimalist, self-contained” philosophy

python
# CherryPy simple API
# server.py

import cherrypy
import json

class UserAPI:
    def __init__(self):
        self.users = [
            {"id": 1, "name": "John", "email": "john@example.com"},
            {"id": 2, "name": "Jane", "email": "jane@example.com"}
        ]
    
    @cherrypy.expose
    @cherrypy.tools.json_out()
    def index(self):
        """GET /users"""
        return self.users
    
    @cherrypy.expose
    @cherrypy.tools.json_out()
    def show(self, id):
        """GET /users/123"""
        user = next((u for u in self.users if u['id'] == int(id)), None)
        if not user:
            raise cherrypy.HTTPError(404, "User not found")
        return user

if __name__ == '__main__':
    cherrypy.quickstart(UserAPI(), '/users')

# Total: 1 file, 30 lines
# Setup time: 5 minutes
# Run with: python server.py
# Built-in production server! ✨

Wait, what?

Developer: "Where is the external server configuration?"
CherryPy: "Built in."
Developer: "Where is the WSGI config?"
CherryPy: "You do not need one."
Developer: "What about production?"
CherryPy: "Same command. It is production-ready."
Developer: "..."
CherryPy: "😎"

Chapter 3: The secret sauce

Feature #1: Built-in HTTP server

Other frameworks:

bash
# Flask produkcia
pip install gunicorn
gunicorn app:app

# FastAPI produkcia
pip install uvicorn
uvicorn main:app

# Django produkcia
pip install gunicorn
gunicorn myproject.wsgi

# All need an external server!

CherryPy:

bash
# Development
python server.py

# Produkcia
python server.py

# That is all. Same command. 🎉

Why it matters:

python
# Quick testing scenario:
# 10:00 - I need to test an API
# 10:01 - Write a CherryPy API
# 10:05 - python server.py
# 10:06 - Testing!

# vs Flask:
# 10:00 - I need to test an API
# 10:01 - Write a Flask API
# 10:05 - Install gunicorn
# 10:07 - Configure gunicorn
# 10:10 - Troubleshoot gunicorn
# 10:15 - Finally testing!

# Winner: CherryPy (by 10 minutes)

Feature #2: Object-oriented API

CherryPy's natural structure:

python
import cherrypy

class Root:
    @cherrypy.expose
    def index(self):
        return "Home"

class UsersAPI:
    @cherrypy.expose
    def index(self):
        return "List of users"
    
    @cherrypy.expose
    def show(self, id):
        return f"User {id}"

class ProductsAPI:
    @cherrypy.expose
    def index(self):
        return "List of products"

# Mount structure
root = Root()
root.users = UsersAPI()
root.products = ProductsAPI()

cherrypy.quickstart(root, '/')

# URLs automatically:
# / → Root.index()
# /users → UsersAPI.index()
# /users/show/123 → UsersAPI.show(id=123)
# /products → ProductsAPI.index()

# Intuitive! Natural! Pythonic! 🐍

Feature #3: Simple configuration

CherryPy configuration:

python
import cherrypy

config = {
    'global': {
        'server.socket_host': '0.0.0.0',
        'server.socket_port': 8080,
        'server.thread_pool': 10
    },
    '/': {
        'tools.sessions.on': True,
        'tools.auth.on': True
    }
}

cherrypy.quickstart(MyApp(), '/', config)

# A simple dictionary!
# Easy to understand!
# Easy to modify!

Django configuration:

python
# settings.py (200 lines)
ALLOWED_HOSTS = []
INSTALLED_APPS = [...]
MIDDLEWARE = [...]
# ... 180 more lines

# Complex!
# Learning curve!
# Where is the socket configuration?!

Chapter 4: A real-world quick start

Scenario: I need an API in five minutes

Mission:

12:00 - Manager: "Can you quickly build a test API?"
12:05 - Manager: "I need to show it at a meeting!"

Panic: ON 😰

Solution: CherryPy to the rescue!

python
# test_api.py (written in 3 minutes)

import cherrypy
from datetime import datetime

class QuickAPI:
    @cherrypy.expose
    @cherrypy.tools.json_out()
    def index(self):
        """GET / - API info"""
        return {
            "name": "Quick Test API",
            "version": "1.0",
            "status": "running",
            "timestamp": datetime.now().isoformat()
        }
    
    @cherrypy.expose
    @cherrypy.tools.json_out()
    def users(self):
        """GET /users"""
        return [
            {"id": 1, "name": "Alice", "active": True},
            {"id": 2, "name": "Bob", "active": False},
            {"id": 3, "name": "Charlie", "active": True}
        ]
    
    @cherrypy.expose
    @cherrypy.tools.json_out()
    def stats(self):
        """GET /stats"""
        return {
            "total_users": 3,
            "active_users": 2,
            "uptime": "5 minutes",
            "requests": 42
        }

if __name__ == '__main__':
    cherrypy.config.update({
        'server.socket_host': '0.0.0.0',
        'server.socket_port': 8080,
        'log.screen': False
    })
    
    cherrypy.quickstart(QuickAPI(), '/')

# Total time: 3 minutes

Run:

bash
python test_api.py

# CherryPy is running at http://0.0.0.0:8080

Test:

bash
curl http://localhost:8080/
curl http://localhost:8080/users
curl http://localhost:8080/stats

# Everything works! ✅

# Time: 5 minutes
# Manager: "Perfect! Show it!"
# You: 😎

Chapter 5: Advanced quick recipes

Recipe #1: REST API with CRUD

python
import cherrypy

class TaskAPI:
    def __init__(self):
        self.tasks = {
            1: {"id": 1, "title": "Learn CherryPy", "done": True},
            2: {"id": 2, "title": "Build an API", "done": False}
        }
        self.next_id = 3
    
    @cherrypy.expose
    @cherrypy.tools.json_out()
    def index(self):
        """GET /tasks - List all"""
        return list(self.tasks.values())
    
    @cherrypy.expose
    @cherrypy.tools.json_out()
    def show(self, id):
        """GET /tasks/show/1 - Get one"""
        task = self.tasks.get(int(id))
        if not task:
            raise cherrypy.HTTPError(404, "Task not found")
        return task
    
    @cherrypy.expose
    @cherrypy.tools.json_in()
    @cherrypy.tools.json_out()
    def create(self):
        """POST /tasks/create"""
        data = cherrypy.request.json
        task = {
            "id": self.next_id,
            "title": data["title"],
            "done": data.get("done", False)
        }
        self.tasks[self.next_id] = task
        self.next_id += 1
        return task
    
    @cherrypy.expose
    @cherrypy.tools.json_in()
    @cherrypy.tools.json_out()
    def update(self, id):
        """PUT /tasks/update/1"""
        task_id = int(id)
        if task_id not in self.tasks:
            raise cherrypy.HTTPError(404, "Task not found")
        
        data = cherrypy.request.json
        self.tasks[task_id].update(data)
        return self.tasks[task_id]
    
    @cherrypy.expose
    @cherrypy.tools.json_out()
    def delete(self, id):
        """DELETE /tasks/delete/1"""
        task_id = int(id)
        if task_id not in self.tasks:
            raise cherrypy.HTTPError(404, "Task not found")
        
        del self.tasks[task_id]
        return {"message": "Task deleted"}

if __name__ == '__main__':
    cherrypy.quickstart(TaskAPI(), '/tasks')

# Complete CRUD API in 50 lines!

Recipe #2: Static files and API

python
import cherrypy
import os

class WebApp:
    @cherrypy.expose
    def index(self):
        """Serve an HTML page"""
        return open('index.html').read()

class API:
    @cherrypy.expose
    @cherrypy.tools.json_out()
    def data(self):
        """GET /api/data"""
        return {"message": "Hello from the API"}

if __name__ == '__main__':
    config = {
        '/': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': os.path.abspath('static'),
            'tools.staticdir.index': 'index.html'
        }
    }
    
    root = WebApp()
    root.api = API()
    
    cherrypy.quickstart(root, '/', config)

# Serves:
# / → index.html
# /static/style.css → CSS
# /api/data → JSON

# Full-stack in one file! 🚀

Recipe #3: Authentication

python
import cherrypy
from functools import wraps

# Simple auth decorator
def require_auth(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        auth = cherrypy.request.headers.get('Authorization')
        if auth != 'Bearer secret-token':
            raise cherrypy.HTTPError(401, "Unauthorized")
        return f(*args, **kwargs)
    return wrapper

class ProtectedAPI:
    @cherrypy.expose
    @cherrypy.tools.json_out()
    def public(self):
        """GET /public - Without authentication"""
        return {"message": "Public endpoint"}
    
    @cherrypy.expose
    @cherrypy.tools.json_out()
    @require_auth
    def private(self):
        """GET /private - Requires authentication"""
        return {"message": "Secret data", "user": "authenticated"}

if __name__ == '__main__':
    cherrypy.quickstart(ProtectedAPI(), '/')

# Authentication in 20 lines!

Chapter 6: Comparison matrix

CherryPy vs the giants

FeatureDjangoFastAPIFlaskCherryPyWinner
Setup time30 min5 min5 min5 min🤝 Tie
Built-in serverNoNoDev only✅ Production🏆 CherryPy
Lines of code300+252530🤝 Tie
Production readyYesNeeds uvicornNeeds gunicorn✅ Built in🏆 CherryPy
Learning curveSteepMediumEasyEasy🤝 Flask/CherryPy
Popularity🔥🔥🔥🔥🔥🔥🔥🔥🔥🏆 Django/Flask
EcosystemHugeGrowingHugeSmall🏆 Django
OOP friendlyModerateNoNo✅ Very🏆 CherryPy
Async supportYes✅ NativeNoPlugin🏆 FastAPI
Automatic documentationAdmin✅ OpenAPINoNo🏆 FastAPI
Quick prototypesNoYesYes✅ Perfect🏆 CherryPy
Enterprise apps✅ PerfectYesYesModerate🏆 Django

When should you use each?

python
def choose_framework(project):
    if project.type == "Enterprise" and project.needs_admin:
        return "Django"  # Full-stack giant
    
    if project.type == "Modern API" and project.needs_performance:
        return "FastAPI"  # Speedster
    
    if project.type == "Anything" and project.popularity_matters:
        return "Flask"  # Safe choice
    
    if project.type == "Quick test" or project.type == "Prototype":
        return "CherryPy"  # Secret weapon 🍒
    
    if project.needs == "Built-in server" and project.simplicity:
        return "CherryPy"  # Hidden gem

Chapter 7: Hidden gems

Gem #1: Thread pool configuration

python
import cherrypy

cherrypy.config.update({
    'server.thread_pool': 30,  # Handles 30 concurrent requests
    'server.thread_pool_max': 50  # Maximum 50 threads
})

# Simple thread control!
# No external configuration!

Gem #2: Multiple server instances

python
from cherrypy import _cpserver

# Server 1: Public API
server1 = _cpserver.Server()
server1.socket_port = 8080
server1.subscribe()

# Server 2: Admin API
server2 = _cpserver.Server()
server2.socket_port = 8081
server2.subscribe()

cherrypy.tree.mount(PublicAPI(), '/', config1)
cherrypy.tree.mount(AdminAPI(), '/', config2)

cherrypy.engine.start()
cherrypy.engine.block()

# Two servers, one process! 🚀

Gem #3: Request hooks

python
import cherrypy
from datetime import datetime

def log_request():
    """Log every request"""
    print(f"[{datetime.now()}] {cherrypy.request.method} {cherrypy.request.path_info}")

def add_cors():
    """Add CORS headers"""
    cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'

# Register hooks
cherrypy.tools.log_request = cherrypy.Tool('before_handler', log_request)
cherrypy.tools.cors = cherrypy.Tool('before_finalize', add_cors)

config = {
    '/': {
        'tools.log_request.on': True,
        'tools.cors.on': True
    }
}

# Easy middleware!

Chapter 8: Real-world use cases

Use case #1: Rapid prototyping

Situation: The client wants an API demo tomorrow

Timeline:
- 9:00 - Get requirements
- 10:00 - Start coding with CherryPy
- 10:30 - Basic API complete
- 11:00 - Add some features
- 11:30 - Test and fine-tune
- 12:00 - Deploy (the same Python file!)
- 14:00 - Client demo

Result: ✅ Client impressed
Tool: CherryPy (perfect for this!)

Alternative with Django:
- 9:00 - Get requirements
- 10:00 - Set up the Django project
- 11:00 - Still configuring...
- 12:00 - First endpoint works
- 14:00 - Demo postponed until tomorrow

Winner: CherryPy

Use case #2: Mock server for testing

python
# Mock API for testing
import cherrypy
import random

class MockAPI:
    @cherrypy.expose
    @cherrypy.tools.json_out()
    def users(self):
        """Mock users endpoint"""
        return [
            {"id": i, "name": f"User {i}"} 
            for i in range(1, 11)
        ]
    
    @cherrypy.expose
    @cherrypy.tools.json_out()
    def random_delay(self):
        """Simulate a slow endpoint"""
        import time
        time.sleep(random.uniform(1, 3))
        return {"status": "slow response"}
    
    @cherrypy.expose
    def error(self):
        """Simulate an error"""
        raise cherrypy.HTTPError(500, "Simulated error")

if __name__ == '__main__':
    cherrypy.quickstart(MockAPI(), '/mock')

# Perfect for:
# - Frontend development (before the backend is ready)
# - Integration testing
# - Load testing
# - Testing error scenarios

Use case #3: Internal tools

python
# Internal company API
import cherrypy
import sqlite3

class InternalTools:
    def __init__(self):
        self.db = sqlite3.connect('company.db', check_same_thread=False)
    
    @cherrypy.expose
    @cherrypy.tools.json_out()
    def employees(self):
        """GET /employees"""
        cursor = self.db.execute('SELECT * FROM employees')
        return [dict(row) for row in cursor.fetchall()]
    
    @cherrypy.expose
    @cherrypy.tools.json_out()
    def stats(self):
        """GET /stats"""
        cursor = self.db.execute('SELECT COUNT(*) FROM employees')
        return {"total_employees": cursor.fetchone()[0]}

if __name__ == '__main__':
    cherrypy.config.update({
        'server.socket_host': '192.168.1.100',  # Internal IP
        'server.socket_port': 8080
    })
    cherrypy.quickstart(InternalTools(), '/')

# Perfect for internal company tools!

Chapter 9: Limitations (time for honesty)

Limitation #1: Smaller community

GitHub stars:
- Flask: 67K ⭐
- Django: 79K ⭐
- FastAPI: 75K ⭐
- CherryPy: 1.8K ⭐

Reality: fewer
- StackOverflow answers
- Third-party plugins
- Tutorial videos
- Blog posts

Impact:
- Harder to find help
- Fewer ready-made solutions
- More work on your own

Solution:
- Good for experienced developers
- Read the (good) documentation
- The community is small but helpful

Limitation #2: Not “trendy”

python
Job listings:
"Required: Django OR Flask OR FastAPI"
"FastAPI experience is a plus"
"Must know Flask"

CherryPy: *not mentioned*

Reality:
- Will not help your CV
- Less marketable skill
- Niche tool

But:
- Perfect for personal projects
- Great for quick prototypes
- Excellent for internal tools
- A hidden weapon in the toolbox 🔧

Limitation #3: Not async by default

python
# ❌ Not natively async
class API:
    @cherrypy.expose
    def endpoint(self):
        # Synchronous only
        result = slow_operation()
        return result

# vs FastAPI
@app.get("/endpoint")
async def endpoint():
    # Async!
    result = await slow_operation()
    return result

# CherryPy can use gevent, but it is not as elegant

Epilogue: The perfect CherryPy moment

When CherryPy shines:

python
situations = {
    "quick_prototype": True,    # ⭐ Best choice
    "mock_server": True,        # ⭐ Best choice
    "internal_tools": True,   # ⭐ Best choice
    "learning_project": True,     # ⭐ Great choice
    "microservice": True,       # ⭐ Good choice
    "test_api": True,     # ⭐ Perfect choice
    
    "enterprise_app": False,    # ❌ Use Django
    "high_performance_api": False,  # ❌ Use FastAPI
    "trendy_cv_skill": False,   # ❌ Use Flask
    "async_heavy": False        # ❌ Use FastAPI
}

verdict = """
CherryPy is not the best framework for everything.
But for quick prototypes, internal tools and testing?
It is a SECRET WEAPON. 🍒

Small, fast, self-contained and production-ready.
No external server.
No complicated configuration.
Just clean Python OOP.

The cherry on top? It really works. 😎
"""

Conclusion: Embrace the cherry

Final verdict:

python
if needs == "quick_and_dirty":
    return cherrypy  # Fastest route to a result
    
if needs == "production_grade":
    return django  # Batteries included
    
if needs == "modern_performance":
    return fastapi  # Speedster
    
if needs == "popular_and_safe":
    return flask  # Community favorite
    
if needs == "built_in_server":
    return cherrypy  # The only one! 🍒

# Add CherryPy to your toolbox
# Thank me later

My recommendation:

Your framework arsenal:
1. Django - Tank (enterprise)
2. FastAPI - Sports car (performance)
3. Flask - Sedan (reliable daily driver)
4. CherryPy - Motorcycle (fast, agile) 🏍️

Use the right tool for the job.
CherryPy is underrated.
Do not sleep on it.

The truth:

Is CherryPy the best framework? No.
Is it the most popular? No.
Is it the fastest? No.
Will it help you get a job? Probably not.

But can it save you hours on a Friday afternoon
when you need a quick API for testing?

DEFINITELY. 🍒

And sometimes that is exactly what you need.

Written by a developer who uses Django for production, FastAPI for performance, Flask for popularity and CherryPy for “I need this running in five minutes” moments.

Stack: CherryPy 18.8+, Python 3.7+, built-in HTTP server (MVP).

Recommendation: Learn CherryPy, not as your main framework but as a secret weapon in your toolbox. When you need a quick prototype or mock server, you will appreciate it.

P.S. Popularity ≠ quality. Sometimes the outsider is perfect for the task. CherryPy is that outsider. 🍒

P.P.S. The built-in production server is a game changer. No gunicorn, uvicorn or nginx. Just python server.py. Try it and see. 😊

All articles