2017-11-18 83 views
1

所以我用瓶子來連接我的HTML和Python代碼,但我不知道如何從我的HTML代碼中獲取用戶輸入,並將其用作我的Python代碼中的變量。我在下面發佈了我的代碼,請幫助。如何將用戶輸入從html傳遞給python?

這是我的瓶代碼

from bottle import default_app, route, template, post, request, get 

@route('/') 
def showForm(): 
    return template("form.html") 

@post('/response') 
def showResponse(): 
    return template("response.html") 

application = default_app() 

這是要求用戶輸入的輸入

<!DOCTYPE html> 
<html lang = "en-us"> 
    <head> 
     <title>BMI Calculator</title> 
     <meta charset = "utf-8"> 
     <style type = "text/css"> 
      body{ 
       background-color: lightblue; 
      } 
     </style> 
    </head> 

<body> 
    <h1>BMI Calculator</h1> 
    <h2>Enter your information</h2> 
    <form method = "post" 
     action = "response"> 
     <fieldset> 
      <label>Height: </label> 
      <input type = "text" 
      name = "feet"> 
      ft 
      <input type = "text" 
      name = "inches"> 
      in 
      <br> 
      <label>Weight:</label> 
      <input type = "text" 
      name = "weight"> 
      lbs 
     </fieldset> 

     <button type = "submit"> 
       Submit 
     </button> 
    </form> 
</body> 

我的主要形式,並且這是我的響應碼,其顯示當一個頁面用戶點擊提交,我嵌入我的Python代碼,以便能夠計算用戶的bmi

<% 
weight = request.forms.get("weight") 
feet = request.forms.get("feet") 
inches = request.forms.get("inches") 
height = (feet * 12) + int(inches) 
bmi = (weight/(height^2)) * 703 
if bmi < 18.5: 
    status = "underweight" 

elif bmi < 24.9 and bmi > 18.51: 
    status = "normal" 

elif bmi > 25 and bmi < 29.9: 
    status = "overweight" 

else: 
    status = "obese" 
%> 

<!DOCTYPE html> 
<html lang = "en-us"> 
    <head> 
     <title>Calculation</title> 
     <meta charset = "utf-8"> 
    </head> 
<body> 
    <h1>Your Results</h1> 
    <fieldset> 
     <label>BMI : </label> 
     <input type = "text" 
     name = "BMI" 
     value = {{bmi}}> 
     <br> 
     <label>Status:</label> 
     <input type = "text" 
     name = "status" 
     value = {{status}}> 
    </fieldset> 
</body> 

回答

0

它看起來像你甚至不嘗試訪問您的表格數據POST路線。 formsbottle.request對象的屬性保存所有解析的表單數據。 Bottle documentation就如何處理表單數據提供了一個很好的例子。

另外,將邏輯放入模板超出正確頁面渲染所需的範圍實在是一個壞主意。您需要處理路線中的數據或將處理移至單獨的模塊中,以更好地分離責任。

相關問題