简体   繁体   中英

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.

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

I have no experience with bottle, but it seems that route expects a callback function that does not take any parameters. To achieve this, you could create some throw-away wrapper around your method, which does does not accept any parameters. This is done typically using an anonymous function defined by a lambda expression , something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM