繁体   English   中英

Python瓶:如何将参数传递给函数处理程序

[英]Python bottle: how to pass parameters into function handler

我试图在将http GET请求发送到特定路由时调用函数,但我想将参数传递给给定函数。 例如,我有以下内容:

    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') ,但它不起作用。 我查看了这个文档 ,但我找不到任何答案。

目前尚不清楚您是在询问如何将路由与闭包相关联,或者只是使用带参数的函数。

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

另一方面,如果您想要“捕获”路由定义时已知的值,并将其烘焙到路由处理程序中,则使用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

我没有瓶子的经验,但似乎route需要一个不带任何参数的回调函数。 为了实现这一点,你可以在你的方法周围创建一些丢弃的包装器,它不接受任何参数。 这通常使用由lambda表达式定义的匿名函数来完成,例如:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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