python – Flask Form数据在提交时重复

python – Flask Form数据在提交时重复

我试图填充一个当前值的表,然后改变它的目的是找到原始和后的差异.我在下面简化我的代码来复制问题: –

webapp.py

from flask import Flask, render_templatefrom flask_wtf import FlaskFormfrom wtforms import StringField, DecimalField, fieldsimport pandas as pdapp=Flask(__name__)app.config["SECRET_KEY"] = "wtf"class stockForm(FlaskForm): stock=StringField() price= DecimalField() def __init__(self, csrf_enabled=False, *args, **kwargs): super(stockForm, self).__init__(csrf_enabled=csrf_enabled, *args, **kwargs)class stockListForm(FlaskForm): stockItem=fields.FieldList(fields.FormField(stockForm))@app.route("/sEntry", methods=["GET","POST"])def sEntry(): form=stockListForm() stocklist=pd.DataFrame(data=[["abc",10.17],["bcd",11.53],["edf",12.19]],columns=["stock","price"]) for stock in stocklist.itertuples(): sForm=stockForm() sForm.stock=stock.stock sForm.price=stock.price form.stockItem.append_entry(sForm) if form.validate_on_submit(): results = [] for idx, data in enumerate(form.stockItem.data): results.append(data) print(results) del form return render_template("results.html", results=results) print(form.errors) return render_template("sEntry.html",form=form)if __name__=="__main__": app.run(debug=True, use_reloader=True, host="0.0.0.0", port=int("5050"))

sEntry.html

<html lang="en"> <head> <meta charset="utf-8"> </head><body> <form action="" method="POST" name="form"> {{ form.name}} {{ form.hidden_tag() }} <div> <table> <thead > <tr class="col"> <th style="width: 30px">stock</th> <th style="width: 50px">price</th> </tr> </thead> {% for stock in form.stockItem %} <tr class="col"> <td>{{ stock.stock }}</td> <td>{{ stock.price }}</td> </tr> {% endfor %} </table> </div> <p><input type="submit" name="edit" value="Send"></p> </form></body></html>

results.html

<ul>{% for line in results %} <li>{{ line }}</li>{% endfor %}</ul>

如果我要更改一些字段的值,生成的变量结果将包含数据帧中原始3行的6行数据的副本

例如

{"price": Decimal("10.17"), "stock": "abc"}{"price": Decimal("13"), "stock": "bcd"}{"price": Decimal("12.19"), "stock": "edf"}{"price": 10.17, "stock": "abc"}{"price": 11.529999999999999, "stock": "bcd"}{"price": 12.19, "stock": "edf"}

此外,我也有问题我的原始十进制用于变成一些长浮点值,在上面的例子中,我将bcd值从11.53更改为13,原始值变为长浮点数,其余我没有编辑保持原始.

我可以有一个肮脏的解决方案,将结果切成两半并比较两半之间的值,舍入那些长浮点数以找到有变化的值,但似乎非常低效.

有人可以帮忙吗?

解决方法:

首先,您需要在Pandas DataFrame中使用适当的Decimal类型. (可以通过使用Numpy的dtype和对象来处理Pandas).

其次,当POST请求发生时,您正在使用原始数据填充表单.

一些固定的视图函数看起来像这样:

@app.route("/", methods=["GET","POST"])def sEntry(): # Create form and fill it with request data form = stockListForm(request.form) # Set up initial data with proper Decimal objects stocklist=pd.DataFrame(data=[["abc",Decimal("10.17")],["bcd",Decimal("11.53")],["edf",Decimal("12.19")]],columns=["stock","price"]) # Handle valid POST request if form.validate_on_submit(): # Convert form data to dictionary (so we can later easily query stock price) stocks = {i["stock"]: i["price"] for i in form.stockItem.data} # Generate result (as generator) ... results = ((i.stock, i.price, i.price - stocks[i.stock]) for i in stocklist.itertuples()) # ... and push it to template return render_template("results.html", results=results) print(form.errors) # ...build initial form for GET request for stock in stocklist.itertuples(): sForm=stockForm() sForm.stock=stock.stock sForm.price=stock.price form.stockItem.append_entry(sForm) return render_template("sEntry.html",form=form)来源:https://www.icode9.com/content-1-287801.html

免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。

http://vnetpros.com/style/images/nopic.gif
我要收藏
赞一个
踩一下
分享到

分享
评论
首页