我不能代表 Django,但在 CherryPy 中,您可以通过单个配置条目为每个 HTTP 动词拥有一个函数:
request.dispatch = cherrypy.dispatch.MethodDispatcher()
然而,我也见过一些不理想的情况。
一个例子是硬重定向,无论动词如何。
另一种情况是大多数处理程序只处理 GET。在这种情况下,有一千个页面处理程序都名为“GET”,这尤其令人烦恼。在装饰器中表达比在函数名称中表达更漂亮:
def allow(*methods):
methods = list(methods)
if not methods:
methods = ['GET', 'HEAD']
elif 'GET' in methods and 'HEAD' not in methods:
methods.append('HEAD')
def wrap(f):
def inner(*args, **kwargs):
cherrypy.response.headers['Allow'] = ', '.join(methods)
if cherrypy.request.method not in methods:
raise cherrypy.HTTPError(405)
return f(*args, **kwargs):
inner.exposed = True
return inner
return wrap
class Root:
@allow()
def index(self):
return "Hello"
cowboy_greeting = "Howdy"
@allow()
def cowboy(self):
return self.cowboy_greeting
@allow('PUT')
def cowboyup(self, new_greeting=None):
self.cowboy_greeting = new_greeting
我看到的另一个常见的方法是查找与数据库中的资源相对应的数据,无论动词如何,都会发生这种情况:
def default(self, id, **kwargs):
# 404 if no such beast
thing = Things.get(id=id)
if thing is None:
raise cherrypy.NotFound()
# ...and now switch on method
if cherrypy.request.method == 'GET': ...
CherryPy 试图不为您做出决定,但如果您想要的话,它会使其变得简单(一句台词)。