2015-07-11 106 views
1

我试图调用一个函数,当一个HTTP GET请求发送到特定的路由,但我想传递参数给定的函数。例如,我有以下几点:Python瓶:如何将参数传递给函数处理程序

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

当一个GET请求发送到/here,途径self.here_method(self)被调用。相反,我想打电话给方法self.here_method(self, 'param')。我怎样才能做到这一点?我试过self.app.route('/here', ['GET'], self.here_method, 'param'),但它不起作用。我回顾了this documentation,但我找不到任何答案。

回答

1

目前尚不清楚是否你问如何将您的路线与闭合相关联,或者干脆采用一个参数的函数:这​​通常是使用由lambda expression定义匿名函数,像完成。

如果您只想将参数作为URI的一部分,请使用Bottle的动态path routing

另一方面,如果您想“捕获”在路由定义时已知的值,并将其烘焙到您的路由处理程序中,请使用functools.partial

下面是两个例子。

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) 

,其输出的一个例子:

% 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 
1

我没有使用瓶子的经验,但似乎route预计没有任何参数的回调函数。为了达到这个目的,你可以在你的方法周围创建一些丢弃的包装,它不接受任何参数。

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

很好的解决!但是在这种情况下建议的闭包不起作用,因为'route'将'self'传递给回调函数。这个简单的修复工作:'lambda:self.here_method(myParam ='param')'。上面描述的Python的部分函数也可以工作。正如上面的@ ron.rothman所描述的,这只有在参数在函数定义时已知时才有效。 – modulitos

相关问题