2012-12-24 19 views
16

Flask 0.9を使用しています。Flask URL Route:複数のURLを同じ機能にルーティングします

/item/<int:appitemid> 
/item/<int:appitemid>/ 
/item/<int:appitemid>/<anything can be here> 

<anything can be here>一部の機能に使用されることはありません。

今私は、同じ機能の3つのURLをルートにしたいです。

私は、この目標を達成するために二度同じ機能をコピーする必要があります。

@app.route('/item/<int:appitemid>/') 
def show_item(appitemid): 

@app.route('/item/<int:appitemid>/<path:anythingcanbehere>') 
def show_item(appitemid, anythingcanbehere): 

は、よりよい解決策はありますか?

答えて

45

デフォルトではNoneの値を持つ可能性のあるパラメータを使用するだけではどうですか?

@app.route('/item/<int:appitemid>/') 
@app.route('/item/<int:appitemid>/<path:anythingcanbehere>') 
def show_item(appitemid, anythingcanbehere=None): 
+0

非常に簡単に、直感的、効果的なソリューションでスニペットを参照してください。 – tmthyjames

4

はい - あなたは、次の構文を使用します。

@app.route('/item/<int:appitemid>/<path:path>') 
@app.route('/item/<int:appitemid>', defaults={'path': ''}) 

http://flask.pocoo.org/snippets/57/