【问题标题】:How do I pass user input from html to python?如何将用户输入从 html 传递到 python?
【发布时间】:2017-11-21 16:20:48
【问题描述】:

所以我使用瓶子来连接我的 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>

【问题讨论】:

    标签: python html variables bottle


    【解决方案1】:

    看起来您甚至没有尝试访问POST 路由中的表单数据。 bottle.request 对象的 forms 属性保存所有已解析的表单数据。 Bottle documentation 提供了如何处理表单数据的一个很好的例子。

    此外,将超出正确页面呈现所需的逻辑放入模板中确实是个坏主意。您需要在路由中处理数据或将处理移动到单独的模块中以更好地分离职责。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-04
      • 2017-09-26
      • 2021-02-19
      • 2011-08-25
      • 2021-04-17
      • 2021-06-21
      • 2019-10-13
      • 2020-08-28
      相关资源
      最近更新 更多