2013-01-21 30 views
2

如何才能捕獲所有的路由,只處理目錄和處理文件?燒瓶:如果路徑是目錄或文件,句柄捕獲所有的url不同

下面是一個簡單的例子

from flask import Flask 
app = Flask(__name__) 

@app.route('/foo') 
def foo_file(): 
    return 'Queried: foo file' 

@app.route('/foo/') 
def foo_dir(): 
    return 'Queried: foo dir' 

@app.route('/<path:path>') 
def file(path): 
    return 'Queried file: {0}'.format(path) 

@app.route('/') 
@app.route('/<path:path>/') 
def folder(path): 
    return 'Queried folder: {0}'.format(path) 

if __name__ == '__main__': 
    app.run() 

當我訪問http:\\127.0.0.1:5000\foo它要求foo_file()http:\\127.0.0.1:5000\foo\它調用foo_dir()。但查詢http:\\127.0.0.1:5000\barhttp:\\127.0.0.1:5000\bar\均呼叫 file()。我該如何改變它?

我知道我可以檢查尾部斜線並手動重新路由,我只是想知道是否有另一種方法。

回答

6

你可能只是這樣做......

@app.route('/<path:path>') 
def catch_all(path): 
    if path.endswith('/'): 
     return handle_folder(path) 
    else: 
     return handle_file(path) 
+0

那是什麼,我ccurrently做。我只想着在Flask中是否有內置的方法來做到這一點。 – P3trus

+0

我嘗試交換原始示例中定義文件和文件夾函數的順序,但Flask重定向強制結束斜線。所以我認爲這是要走的路 - 保持簡單。 – FogleBird

相關問題