Search code examples
pythoncherrypy

CherryPy: Perform specific action if user goes to specific URL


I'm new to CherryPy so please bear with me. What I'd like to do is perform a specific action when a user goes to a specific URL. The URL will mostly always be the same except for one part. The URL will be something like: http://myserver.mydomain.com/show_item.cgi?id=12345. The URL will always be the same except for the 12345. I want to take the "string of numbers", plop them into a variable, and re-direct to another URL that will be built on the fly based on that variable. I have the logic for building out the URL -- I just don't know how to "intercept" the incoming URL and extract the "string of numbers". Any help would be greatly appreciated.


Solution

  • Oh, it was not clear from your question that you really wanted to mock CGI-like file handler URL. Though the answer is still there, it may be harder to find because of recent changes in documentation.

    You can use dots in a URI like /path/to/my.html, but Python method names don’t allow dots. To work around this, the default dispatcher converts all dots in the URI to underscores before trying to find the page handler. In the example, therefore, you would name your page handler def my_html.

    So with the following you can navigate your browser to http://127.0.0.1:8080/show_item.cgi?id=1234.

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    
    import cherrypy
    
    
    config = {
      'global' : {
        'server.socket_host' : '127.0.0.1',
        'server.socket_port' : 8080,
        'server.thread_pool' : 8
      }
    }
    
    
    class App:
    
      @cherrypy.expose
      def show_item_cgi(self, id):
        raise cherrypy.HTTPRedirect('https://google.com/search?q={0:d}'.format(int(id)))
    
    
    if __name__ == '__main__':
      cherrypy.quickstart(App(), '/', config)