Commit 320759a9 authored by Marcel Rieger's avatar Marcel Rieger
Browse files

Add method tool that works with ajax tool.

parent 276e0bf2
......@@ -262,6 +262,9 @@ class Server(object):
from vispa.tools.ajax import AjaxTool
cherrypy.tools.ajax = AjaxTool()
from vispa.tools.method import MethodTool
cherrypy.tools.method = MethodTool()
from vispa.tools.json_parameters import JsonParameters
cherrypy.tools.json_parameters = JsonParameters()
......
# -*- coding: utf-8 -*-
"""
Definition of the vispa method tool.
"""
# imports
import cherrypy
import logging
from vispa import AjaxException
logger = logging.getLogger(__name__)
class MethodTool(cherrypy.Tool):
"""
Basically, the method tool implements the same functionality as cherrypy's built-in "allow"
tool, but in addition, this tool is compliant to our ajax tool.
"""
def __init__(self):
super(MethodTool, self).__init__("on_start_resource", self.callable)
def callable(self, accept=None, reject=None, ajax=True):
"""
Actual tool logic. Checks whether a request is sent with a valid HTTP method using *accept*
and *reject*. Both of them can be strings or iterables of strings. When the request not
accepted and *ajax* is *True*, the ajax tool is used to send an error. Otherwise, a
cherrypy.HTTPError is raised.
"""
# prepare accepted methods
if accept is None:
accept = []
if not isinstance(accept, (list, tuple, set)):
accept = [accept]
accept = [method.upper() for method in accept]
# prepare rejected methods
if reject is None:
reject = []
if not isinstance(reject, (list, tuple, set)):
reject = [reject]
reject = [method.upper() for method in reject]
# get the actual request method
method = cherrypy.request.method.upper()
# method check
has_access = len(accept) == 0 or method in accept
has_access &= len(reject) == 0 or method not in reject
if not has_access:
logger.info("forbidden method: %s" % method)
if len(accept) > 0:
cherrypy.response.headers["Allow"] = ", ".join(accept)
# when access is forbidden and an ajax response should be sent, create a handler that
# replaces the original one, otherwise raise a cherrypy.HTTPError
if ajax:
def handler(*args, **kwargs):
raise AjaxException("Method not allowed", code=405)
cherrypy.serving.request.handler = handler
else:
raise cherrypy.HTTPError(405)
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment