2017-11-18 520 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就如何处理表单数据提供了一个很好的例子。

另外,将逻辑放入模板超出正确页面渲染所需的范围实在是一个坏主意。您需要处理路线中的数据或将处理移至单独的模块中,以更好地分离责任。

相关问题