import cherrypy
class HelloWorld(object):
@cherrypy.expose
def index(self):
return "Hello World!"
cherrypy.quickstart(HelloWorld())​
Source : Cherrypy
pip install cherrypy​
mkdir my_cherrypy_project
cd my_cherrypy_project​
app.py
' :import cherrypy
class HelloWorld:
@cherrypy.expose
def index(self):
return "Hello, world!"
if __name__ == '__main__':
cherrypy.quickstart(HelloWorld())​
* Run the CherryPy application : Run your app.py
file using Python:python app.py​
http://localhost:8080
to see the "Hello, world!" message.app.py
file to include more advanced configurations as needed. For example:@cherrypy.expose
are made available as accessible endpoints via HTTP.log.access_file
or log.error_file keys
in your global configuration.cherrypy.config.update({'log.access_file': '',
'log.error_file': ''})​
log.screen
to False
in your global configuration.cherrypy.config.update({'log.screen': False})​
import cherrypy
class MyResource:
@cherrypy.expose
def index(self):
# Default method for GET requests
pass
@cherrypy.expose
@cherrypy.tools.json_in()
def POST(self):
# Handler method for POST requests
pass
@cherrypy.expose
def PUT(self, *args, **kwargs):
# Handler method for PUT requests
pass
@cherrypy.expose
def DELETE(self):
# Handler method for DELETE requests
pass​
def GET(self)
', 'def POST(self)
', 'def PUT(self)
', and 'def DELETE(self)
' explicitly indicates the handling of those respective HTTP methods.import cherrypy
class MyResource:
@cherrypy.expose
def index(self):
# Default method for GET requests
pass
@cherrypy.expose
@cherrypy.tools.json_in()
def POST(self):
# Handler method for POST requests
pass
def PUT(self, *args, **kwargs):
# Handler method for PUT requests
pass
def DELETE(self):
# Handler method for DELETE requests
pass​
index()
or GET()
.@cherrypy.expose
and named POST()
.PUT()
, and DELETE
requests are handled by a method named DELETE()
.import cherrypy
class HelloWorld:
@cherrypy.expose
def index(self):
# Initialize session tool
cherrypy.tools.sessions.on = True
# Access session data
session = cherrypy.session
if 'count' not in session:
session['count'] = 0
session['count'] += 1
return f"Hello! You've visited this page {session['count']} times."
if __name__ == '__main__':
conf = {
'/': {
'tools.sessions.on': True,
# Other session/cookie configurations
}
}
cherrypy.quickstart(HelloWorld(), '/', conf)​
import cherrypy
from jinja2 import Environment, FileSystemLoader
class HelloWorld:
@cherrypy.expose
def index(self):
env = Environment(loader=FileSystemLoader('templates'))
template = env.get_template('index.html')
return template.render(message="Hello, CherryPy and Jinja2!")
if __name__ == '__main__':
cherrypy.quickstart(HelloWorld())​
templates
' folder containing 'index.html
' within your project directory. It uses Jinja2
to render the 'index.html' template with a simple message.@cherrypy.tools.asyncio()
, allowing developers to mark specific methods or endpoints within their CherryPy application as asynchronous.import cherrypy
class MyAsyncApp:
@cherrypy.expose
@cherrypy.tools.asyncio()
async def async_endpoint(self):
# Asynchronous handling here
pass​
* Asyncio Integration : CherryPy leverages Python's asyncio
framework to handle asynchronous I/O operations, enabling CherryPy applications to perform non-blocking I/O operations and concurrent handling of requests.asyncio
module, which was introduced in Python 3.7.import cherrypy
class ProtectedResource:
@cherrypy.expose
@cherrypy.tools.auth_basic(realm='MyRealm')
def secure_endpoint(self):
# Endpoint accessible only with valid credentials
pass​
import cherrypy
class ProtectedResource:
@cherrypy.expose
@cherrypy.tools.authorize(groups=['admin'])
def admin_section(self):
# Accessible only to users with 'admin' role
pass​
cherrypy.lib.auth_basic
: Provides basic HTTP authentication.cherrypy.lib.sessions
: Can be used for session-based authentication.@cherrypy.tools.auth_basic
: Decorator to protect endpoints with basic authentication.@cherrypy.tools.authorize
: Decorator to enforce authorization checks on endpoints. ProxyPass
directive to forward requests to the CherryPy application's address.<VirtualHost *:80>
ServerName example.com
ProxyPass / http://127.0.0.1:8080/ # Forward requests to CherryPy
ProxyPassReverse / http://127.0.0.1:8080/
</VirtualHost>​
proxy_pass
directive to forward requests to the CherryPy application's address.server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:8080; # Forward requests to CherryPy
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}​
X-Real-IP
and X-Forwarded-For
to preserve the original client IP when requests pass through the reverse proxy.sqlite3
, psycopg2
, pymysql
, pyodbc
, or others to interact with databases without an ORM layer, depending on the specific database being used.import cherrypy
class ErrorHandler:
@cherrypy.expose
def handle_error(self):
# Custom error handling logic
pass
cherrypy.config.update({'error_page.default': '/handle_error'})​
import cherrypy
class MyErrorPage:
@cherrypy.expose
def not_found(self):
# Custom handling for 404 Not Found error
pass
cherrypy.config.update({'error_page.404': '/not_found'})​
import cherrypy
class MyResource:
@cherrypy.expose
@cherrypy.tools.response_headers(headers=[('Content-Type', 'text/plain')])
def custom_error(self):
raise cherrypy.HTTPError(status=500, message="Custom Error")​