![](/img/trans.png)
[英]Python Bottle json_dumps - pass parameter to default handler function
[英]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.