gpt4 book ai didi

python - Flask 表单数据在提交时重复

转载 作者:太空宇宙 更新时间:2023-11-03 11:18:47 27 4
gpt4 key购买 nike

我正在尝试填充当前值表,然后更改它以找到原始值和之后的差异。我在下面简化了我的代码以重现该问题:-

网络应用.py

from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, DecimalField, fields
import pandas as pd

app=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>

结果.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'}

此外,我也有一些问题,我原来的 Decimals 用于转换为一些长浮点值,在上面的例子中,我将 bcd 值从 11.53 更改为 13,原始值变为长 float ,其余我没有编辑的保持不变原创。

我可以有一个肮脏的解决方案,将结果分成两半,比较两半之间的值,舍入那些长 float 以找到发生变化的值,但看起来效率很低。

有人可以帮忙吗?

最佳答案

首先,您需要在 Pandas DataFrame 中使用正确的 Decimal 类型。 (这可以由 Pandas 通过将 Numpy 的 dtype 与对象一起使用来处理)。

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

有些固定的 View 函数看起来像这样:

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

关于python - Flask 表单数据在提交时重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47396941/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com