Cherrypy allows to define functions to be so called „tools“ (cherrypy docs). These helper functions might be „hooked“ at various processing points within cherrypys serving process: on_start_resource, before_request_body, before_handler, before_finalize, on_end_resource, before_error_response, after_error_response, on_end_request.
Making the tool is working straight forward. According to the working draft http://www.w3.org/TR/cors/ cross origin access allowance needs to be declared within the response header (see RFC for further information on CORS headers). The following example will add a response header to allow CORS to any („*“) client; change the ‚*‘ to an uri-scheme have provide more granular scaling.
…cherrypy.response.headers[„Access-Control-Allow-Origin“] = „*“ #
attaching the function to a process stage hook needs to be done in the main proc:
…cherrypy.tools.CORS = cherrypy.Tool(‚before_finalize‘, CORS)
# insert tool declaration within def main() or even directly
# before cherrypy.tree.mount command to prevent Error like
If you try to declare the toll earlier an TypeError starting with:
The ‚CORS‘ Tool does not accept positional arguments … is likely to be thrown.
Like with other cherrypy tools you might use them globally by adding „cherrypy.tool.CORS.on : True“ to the general.configs or by using the decorator @cherrypy.tools.CORS right after the exposure decorator of a