CherryPy provides a straightforward mechanism for handling different HTTP methods (GET, POST, PUT, DELETE) by allowing developers to define methods within their CherryPy application classes corresponding to each HTTP method.
Handling Different HTTP Methods :1. Decorator-based Routing : CherryPy uses decorators to associate specific HTTP methods with corresponding handler methods in the application class.
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​
2. Method Naming Convention : Developers can also define methods with specific names that correspond to HTTP methods. For example, defining methods like '
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​
Request Dispatching : When a request arrives, CherryPy's dispatcher examines the incoming request's method and matches it to the corresponding handler method defined within the application. It then invokes the appropriate method to process the request.
For instance:
* A GET request is typically handled by a method named
index()
or
GET()
.
* A POST request is handled by a method annotated with
@cherrypy.expose
and named
POST()
.
* Similarly, PUT requests are handled by a method named
PUT()
, and
DELETE
requests are handled by a method named
DELETE()
.
CherryPy's flexibility in allowing developers to define methods corresponding to specific HTTP methods or using decorators to specify the method association offers an organized and structured way to handle different types of HTTP requests within the application.