【发布时间】:2018-07-23 14:23:05
【问题描述】:
我是 Flask 的新手,我正在尝试构建一个简单的网络应用程序。基本上我在主页上有一个文本输入框和一个提交按钮。
点击提交后,它会根据输入的文本显示一些结果(现在它已在下面的代码中硬编码)以及 2 个按钮(正/负)将输入的文本添加到特定文件(带有“正面”或“负面”标签)。
但是,我面临的问题是这 2 个按钮:单击时它们什么都不做。
这是我现在拥有的:
Python Flask 应用程序
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html')
@app.route('/process-data', methods=['GET', 'POST'])
def process_data():
if request.method == 'GET':
return render_template('index.html')
if request.method == 'POST':
# get the text from the form that was filled in
input_text = request.form['text']
# if submit button is clicked
if request.form['submit'] == 'Submit':
final_result = 'stackoverflow is the best'
if request.form['submit'] == 'Positive':
f = open('dataset/dataset.tsv', 'a')
f.write(input_text + '\t' + 'positive')
# if negative button is clicked
if request.form['submit'] == 'Negative':
f = open('dataset/dataset.tsv', 'a')
f.write(input_text + '\t' + 'negative')
# show the result on the page
return render_template('index.html', result=final_result, text=input_text)
index.html 文件
<!doctype html>
<form action="/process-data" method="post" role="form">
<label for="text">Text:</label>
<input type="text" name="text" placeholder="Input sentence here">
<input type="submit" name="submit" value="Submit">
</form>
{% if result is not none %}
{{ result }}
<h2>Add to dataset</h2>
<form action="/process-data" method="post" role="form">
<label for="add-dataset">This sentence was:</label>
<input type="submit" name="submit" value="Positive">
<input type="submit" name="submit" value="Negative">
</form>
{% endif %}
</html>
【问题讨论】: