Search code examples
pythonroutescherrypy

Map specific url to response with Cherrypy?


I'm writing a web app with CherryPy and I need to map the URL /.well-known/acme-challenge/KH5LEgbLPhDrhJ-BAf7cyTXe8qcN6kL4CJQMOLe1fXU to the response KH5LEgbLPhDrhJ-BAf7cyTXe8qcN6kL4CJQMOLe1fXU.8bOE0CjbktH8JYB_jq5aFEqbG-37XhHjDAIhWppNkdQ inorder to obtain a ssl certificate.

I've tried using an alias such like

cherrpypy.expose("/.well-known/acme-challenge/KH5LEgbLPhDrhJ-BAf7cyTXe8qcN6kL4CJQMOLe1fXU")
def ssl_cert_map(self):
    return "KH5LEgbLPhDrhJ-BAf7cyTXe8qcN6kL4CJQMOLe1fXU.8bOE0CjbktH8JYB_jq5aFEqbG-37XhHjDAIhWppNkdQ"

however when I try to access it at /.well-known/acme-challenge/KH5LEgbLPhDrhJ-BAf7cyTXe8qcN6kL4CJQMOLe1fXU I get a 404 error. How would I be able to make it so /.well-known/acme-challenge/KH5LEgbLPhDrhJ-BAf7cyTXe8qcN6kL4CJQMOLe1fXU gives me KH5LEgbLPhDrhJ-BAf7cyTXe8qcN6kL4CJQMOLe1fXU.8bOE0CjbktH8JYB_jq5aFEqbG-37XhHjDAIhWppNkdQ ?


Solution

  • You don't mention the URL in the cherrypy.expose method. The expose method exposes your class method to be used by Cherrypy.

    In order to map your URL to a specific method, you gotta use the RoutesDispatcher.

    example:

    import cherrypy
    
    class Root:
    
        cherrpypy.expose
        def ssl_cert_map(self):
            return "KH5LEgbLPhDrhJ-BAf7cyTXe8qcN6kL4CJQMOLe1fXU.8bOE0CjbktH8JYB_jq5aFEqbG-37XhHjDAIhWppNkdQ"
    
    app_dispatcher = cherrypy.dispatch.RoutesDispatcher()
    
    app_dispatcher.connect(
    name='ssl-cert',
    route='/.well-known/acme-challenge/KH5LEgbLPhDrhJ-BAf7cyTXe8qcN6kL4CJQMOLe1fXU',
    action='ssl_cert_map',
    controller=Root())
    
    if __name__ == '__main__':
    
        server_config = {
            '/': {
                'request.dispatch': app_dispatcher
            }
        }
        cherrypy.tree.mount(root=None, config=server_config)
        cherrypy.engine.start()
    

    Reference: cherrypy - URL dispatcher