Search code examples
pythonparameter-passingbottle

Python bottle: how to pass parameters into function handler


I am trying to call a function when an http GET request is sent to a specific route, but I would like to pass parameters to the given function. For example, I have the following:

    self.app.route('/here', ['GET'], self.here_method)

where self.here_method(self) is called when a GET request is sent to the /here route. Instead, I would like to call the method self.here_method(self, 'param'). How can I do this? I tried self.app.route('/here', ['GET'], self.here_method, 'param'), but it does not work. I reviewed this documentation, but I could not find any answers.


Solution

  • It's not clear whether you're asking how to associate your route with a closure, or simply with a function that takes a parameter.

    If you simply want to take parameters as part of your your URI, use Bottle's dynamic path routing.

    If, on the other hand, you want to "capture" a value that's known at the time of route definition, and bake that into your route handler, then use functools.partial.

    Here's an example of both.

    from bottle import Bottle
    import functools
    
    app = Bottle()
    
    # take a param from the URI
    @app.route('/hello1/<param>')
    def hello1(param):
        return ['this function takes 1 param: {}'.format(param)]
    
    # "bake" in a param value at route definition time
    hello2 = functools.partial(hello1, param='the_value')
    app.route('/hello2', ['GET'], hello2)
    
    app.run(host='0.0.0.0', port=8080)
    

    And an example of its output:

    % curl http://localhost:8080/hello1/foo
    127.0.0.1 - - [11/Jul/2015 18:55:49] "GET /hello1/foo HTTP/1.1" 200 32
    this function takes 1 param: foo
    
    % curl http://localhost:8080/hello2
    127.0.0.1 - - [11/Jul/2015 18:55:51] "GET /hello2 HTTP/1.1" 200 38
    this function takes 1 param: the_value