2016-12-07 57 views
1

我發現很多類似於這個,但我不能完全使它的工作。基本上,我有一個按鈕,按下它後,我想將該值發回到燒瓶後端。燒瓶按鈕傳遞變量回到python

HTML按鈕:

<form action="" method="POST" ><button class="btn btn-danger" type="submit" name="delete" value="{{ item2 }}"><span class="glyphicon glyphicon-trash"></span> Delete</button> </form> 

的Python:

@app.route('/', methods=["GET","POST"]) 
def home():  
    if request.method == 'POST': 
     if request.form['delete'] == post_id: 
      (my sql login/cursor stuff....) 
      sql = "DELETE FROM test_table WHERE post_id = ?" 
      c.execute(sql, (post_id,)) 
      return redirect("/") 

正如你所看到的,我用填充的神社鏈接(以及隨後的變量)。它填充按鈕,因爲它應該,但將其發送回我的python腳本不起作用。

UPDATE: 當我運行它,我得到一個內部服務器錯誤。我無法看到路由錯誤是什麼,因爲我無法使調試工作(使用wsgi/werkzeug)。

我認爲我們可以肯定地說是通過不定義post id是爲什麼它不起作用。所以我的問題是,當按鈕發送數據返回到Python時,python抓取什麼值(以及如何)?是name=還是value=還是別的?

+0

你能告訴我們更多關於什麼不起作用嗎?我使用你的代碼在現有的Flask應用程序中創建了一個簡單的視圖,並通過了'request_method =='POST''的測試,並將我重定向回到'/'url。很明顯,我刪除了mysql的東西,並測試了'post_id'值 - 但是我可以測試的部分似乎正常工作(包括按鈕輸入的value屬性)。 – YellowShark

+0

當我單擊按鈕時,出現以下錯誤: 內部服務器錯誤 服務器遇到內部錯誤,無法完成您的請求。服務器過載或應用程序出現錯誤。 –

+0

你期望'post_id'在'if request.form ['delete'] == post_id'中怎麼樣?您尚未定義該變量。 – davidism

回答

2

你的問題是

request.form['delete'] == post_id 

你從按鈕(request.form['delete'])獲得價值,並嘗試在不存在變量post_id值進行比較。

如果你想從按鈕的值,並分配給變量post_id那麼你需要

post_id = request.form['delete'] 

post_id = request.form.get('delete') 

,然後你可以在SQL查詢中使用post_id

@app.route('/', methods=["GET","POST"]) 
def home():  
    if request.method == 'POST': 

     post_id = request.form.get('delete') 

     if post_id is not None: 
      (my sql login/cursor stuff....) 
      sql = "DELETE FROM test_table WHERE post_id = ?" 
      c.execute(sql, (post_id,)) 
      return redirect("/") 
+0

太棒了!這基本上是爲我工作...唯一的區別是我不得不這樣做: 'sql =(「DELETE FROM test_table WHERE post_id =%s」)' 'c.execute(sql,(post_id_delete,))'' –