2015-07-11 104 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

相關問題