目前尚不清楚是否你問如何將您的路線與閉合相關聯,或者乾脆採用一個參數的函數:這通常是使用由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
很好的解決!但是在這種情況下建議的閉包不起作用,因爲'route'將'self'傳遞給回調函數。這個簡單的修復工作:'lambda:self.here_method(myParam ='param')'。上面描述的Python的部分函數也可以工作。正如上面的@ ron.rothman所描述的,這隻有在參數在函數定義時已知時纔有效。 – modulitos