2017-11-18 8 views
1

私はhtmlとpythonのコードを接続するためにボトルを使用していますが、私はhtmlコードからユーザ入力を受け取り、私のpythonコードで変数として使用する方法を知らない。私は以下のコードを投稿しました。助けてください。htmlのユーザ入力をPythonに渡すにはどうすればいいですか?

これはこれは、ユーザーの入力

<!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> 

そして、これは、ページを表示する私の応答コードであるために尋ねる私のメインフォームである私のボトルコード

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() 

ですユーザーは私の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ルートでフォームデータにアクセスしようとしていないようです。 formsオブジェクトのプロパティは、すべての解析されたフォームデータを保持しますbottle.requestオブジェクトです。 Bottle documentationは、フォームデータの処理方法の良い例を提供します。

また、正しいページのレンダリングに必要なものを超えてロジックをテンプレートに入れることは、実際には悪い考えです。責任を分かち合うために、ルート内のデータを処理したり、処理を別のモジュールに移す必要があります。

関連する問題