2016-11-22 39 views
1

我有一個Flask站點,它有一個「搜索欄」,您在其中鍵入特定位置的位置ID,然後單擊Submit以進入頁面該位置,如果存在。下面是目前的形式作用:創建一個用url_for()插入URI變量的Flask搜索欄

<form id="locationinfo" action="{{ url_for('location') }}">

當您單擊Submit你會被帶到/location?info=SITEID,並且工作得很好。我想要做的是稍微改變這種行爲,以便當用戶點擊Submit時,他們將被帶到/location/SITEID/。我在我的主要Flask路徑文件中設置了裝飾器,但我正在努力將這些部分組合在一起以獲得這個簡單的表單。

@app.route("/location/<locationid>/") 
def locations(locationid): 
    ... 
    return locationid 

任何方向將不勝感激!

[當前的完整形式的代碼編輯]

@app.route("/location") 
    def location(): 
     location_id = request.args.get("info") 

<form id="info" action="{{ url_for('location') }}"> 
    <input type="text" name="info" id="locationfield"> 
    <button type="submit">Go!</button> 
</form> 

回答

1

您不能更改HTML表單提交如何他們的領域,他們總是會在查詢字符串或機構(POST) 。一種選擇是使用JavaScript來覆蓋提交事件以執行您自己的提交併使用結果重新渲染。

更簡單的解決方案是在提交後重定向到漂亮的URL。這使「搜索」操作與「顯示」操作分離(即使它們由相同視圖處理)。

@app.route('/location/') 
@app.route('/location/<int:id>/') 
def location(id=None): 
    # redirect to the second form if the id wasn't in the path 
    # raises 400 error if id wasn't in the query 
    if id is None: 
     return redirect(url_for('location', id=request.args['info'])) 

    # id is in the path, continue 
    ... 

如果您想通過id以外的內容進行搜索,稍後可以展開此操作。執行搜索然後重定向到找到的ID。