【问题标题】:How to save to a list every input I receive from the same html form?如何将我从同一个 html 表单收到的每个输入保存到列表中?
【发布时间】:2020-02-25 10:41:52
【问题描述】:

如何将我从同一个表单收到的每个输入保存到列表中? 希望如何将用户输入的每个权重保存在列表中。 是否可以保存用户插入的所有权重?如果他重新加载页面?

这是表格:

<form action="/send" method="POST">
    <label for="">Weight</label>
    <input type="text" name="weight">
    <label for="">Height</label>
    <input type="text" name="height">
    <input type="submit" value="submit">
    <br>

<div class="alert">
    {{ BMI }}
</div>

这是烧瓶应用程序:


   from flask import Flask, render_template, url_for, request
   import schedule


   app = Flask(__name__)

   @app.route('/', methods=['GET', 'POST'])
   def index():
    return render_template('index.html')

   @app.route('/send', methods=['GET', 'POST'])
   def send():
    if request.method=='POST':
        weight = request.form['weight']
        height = request.form['height']
        a = float(weight)
        b = float(height)
        BMI = a/(b**2)
        weights = []
        weights.append(weight)
        return render_template('index.html', BMI=BMI, weights = weights)

【问题讨论】:

  • 您的路线已损坏。这将在每个 GET 请求上崩溃,因为您没有 return 任何东西
  • 一旦返回,视图内的所有内容都将消失。你想要的是某种数据库来存储价值然后返回index.html
  • 你要么需要数据库,要么需要使用session对象来持久化数据
  • 我返回 BMI 计算结果。
  • 不是你没有的 GET 请求

标签: python flask web-development-server


【解决方案1】:

您需要一些东西来在请求之间保留这些数据。如果您只需要很短的时间,您可以使用sessionFlask-Session 的文档似乎显示它现在是从 flask.ext.session 导入的,但我的版本是作为 from flask_session import Session 导入的。

下面是一个最小但完整的玩具示例来展示它是如何工作的(在这种情况下,我只存储 BMI,但您可以在会话字典中存储多个列表)。需要注意的是,如果使用 Flask 自带的默认 session,它的存储容量是很小的;这就是我将会话数据保存到文件的原因。

如果您需要数据保留更长时间(即永久),那么您需要使用数据库。需要注意的一点:两次 有人主张将此数据存储在全局变量中。这对于 Web 应用来说是很糟糕的,因为多个用户会开始践踏彼此的数据,更不用说多个进程会开始不同步了。

from flask import Flask, render_template_string, request, session
from flask_session import Session

app = Flask(__name__)
app.config['SECRET_KEY'] = b'_5#y2L"F4Q8z\n\xec]/'
app.config['SESSION_TYPE'] = 'filesystem'
sess = Session()
sess.init_app(app)

homepage_template = """
<form method="POST" action="{{ url_for('bmi_submission') }}" id="bmi_form">
Weight: <input type="text" name="weight" value=""><br>
Height: <input type="text" name="height" value=""><br>
<input type="submit" value="Submit">
</form>
<div id="result_div"></div>

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
   $("#bmi_form").submit(function(e) {
       e.preventDefault();
       var form = $(this);
       var url = form.attr('action');

       $.ajax({
           type: "POST",
           url: url,
           data: form.serialize(),
           context: form,
           success: function(resp) {
               $("#result_div").html(resp); 
           }
       });
   });
</script>
"""

@app.route('/', methods=['GET'])
def homepage():
    return render_template_string(homepage_template)


@app.route('/calc_bmi', methods=['POST'])
def bmi_submission():
    weight = request.form.get('weight')
    height = request.form.get('height')
    a = float(weight)
    b = float(height)
    BMI = a/(b**2)

    if session.get('bmi'):
        session['bmi'].append(BMI)
    else:
        session['bmi'] = [BMI]

    return '<br>'.join([str(item) for item in session['bmi']])

if __name__ == '__main__':
    app.run()

【讨论】:

  • 谢谢!我将使用数据库。
猜你喜欢
  • 2021-01-18
  • 1970-01-01
  • 2020-08-14
  • 2021-09-15
  • 1970-01-01
  • 2016-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多