2015-11-25 45 views
1

我通常使用的method version來處理瓶路由如何在提供靜態文件時將@ bottle.route轉換爲bottle.route()?

bottle.route("/charge", "GET", self.charge) 

瓶文檔很大程度上依賴於@route裝飾處理路由和我有一個情況下,我不知道如何轉換成我最喜歡的版本。在serving static files的文檔使用示例

from bottle import static_file 

@route('/static/<filename:path>') 
def send_static(filename): 
    return static_file(filename, root='/path/to/static/files') 

有沒有辦法把它們變成某種

bottle.route("/static", "GET", static_file) 

建設的?特別是我很困惑如何通過filenameroot參數static_file

回答

2

接受的答案並不能很好地解決您的問題,所以我會提醒您。您似乎試圖使用Bottle的static_file作爲路由目標,但它並不意味着以這種方式使用。正如您引用的示例所示,static_file意味着從內呼叫路由目標函數。下面是一個完整的工作示例:

import bottle 

class AAA(object): 
    def __init__(self, static_file_root): 
     self.static_file_root = static_file_root 

    def assign_routes(self): 
     bottle.route('/aaa', 'GET', self.aaa) 
     bottle.route('/static/<filename:path>', 'GET', self.send_static) 

    def aaa(self): 
     return ['this is aaa\n'] 

    def send_static(self, filename): 
     return bottle.static_file(filename, self.static_file_root) 

aaa = AAA('/tmp') 
aaa.assign_routes() 
bottle.run(host='0.0.0.0', port=8080) 

用法示例:

% echo "this is foo" > /tmp/foo 
% curl http://localhost:8080/static/foo 
this is foo 

希望這有助於。

+0

這很簡單嗎? :)我會發誓,我試了幾次。非常感謝(切換接受的答案和+1) – WoJ

1

由於您要使用單一方法,因此您必須自行將參數傳遞給static_file,並且首先使用re解析它們。

的代碼看起來是這樣的:

from bottle import Router 

app.route('/static/:filename#.*#', "GET", static_file(list(Router()._itertokens('/static/:filename#.*#'))[1][2], root='./static/')) 

這是有點長,如果你想外界分析參數,比你可以添加其他解析功能。

我知道你想讓所有的路由器看起來乾淨整齊,但裝飾器是豐富的功能,但保持功能本身乾淨,爲AOP,所以爲什麼不嘗試在這種情況下使用裝飾器。

+0

謝謝。這並不是說我不喜歡裝飾器版本,但我不能在課堂上的方法中使用它。 ''bottle.route(「/ aaa」,「GET」,self.aaa)''而裝飾'def aaa(self)'的'@ bottle.route(「/ aaa」)'不會('TypeError:aaa )缺少1個需要的位置參數:'self'') – WoJ