[英]Flask - How do I use the value of an HTML button in a Python function?
I am new to programming and have only used a little bit of Python in the past.我是编程新手,过去只使用过一点 Python。 I am using Flask to build a website to host a scientific experiment.我正在使用 Flask 来建立一个网站来托管一个科学实验。 I am doing this on pythonanywhere.com.我在 pythonanywhere.com 上执行此操作。 For the last part of the experiment, participants are shown 30 individual images and they have to say if they remember seeing the image in an earlier part of the experiment.在实验的最后一部分,参与者看到了 30 张单独的图像,他们必须说他们是否记得在实验的早期阶段看到过图像。
To do this I have created a javascript function that randomly shows one of 30 images every time changeImage() is run.为此,我创建了一个 javascript function,它在每次运行 changeImage() 时随机显示 30 个图像之一。 Below it are two buttons saying "yes" and "no".下面是两个按钮,分别表示“是”和“否”。 Pressing the button should change the shown image and send "yes" or "no" to the flask_app.py, along with the variable "x" from javascript.按下按钮应更改显示的图像并将“是”或“否”发送到 flask_app.py,以及来自 javascript 的变量“x”。 This is so the Python function can save the number of the image and what answer the participant gives.这样 Python function 可以保存图像的编号以及参与者给出的答案。
Javascript Javascript
var array2 = new Array();
var index = 0
var x = 0
for (var i = 1; i < 31; i++) {
array2.push(i);
}
function changeImage() {
if (array2.length) {
var index = Math.floor(Math.random() * array2.length);
x = array2[index];
var image = "/static/images/image" + x + ".jpg"
document.getElementById('ad').src = image;
array2.splice(index, 1);
}
}
HTML HTML
<body onload="changeImage()">
<div class="w3-row-padding w3-padding-16 w3-center">
<img id="ad" class="img-fluid" src="/static/images/image99.jpg" />
<form action="{{ url_for('recog1') }}" id="answer" method="POST">
<div class="w3-center">
<input type="submit" id="answerY" value="Yes" name="Yes"
style="width:47%;" class="w3-bar-item w3-button w3-padding-medium w3-blue"
onclick= "changeImage();">
<input type="submit" id="answerN" value="No" name="No"
style="width:47%;" class="w3-bar-item w3-button w3-padding-medium w3-blue"
onclick= "changeImage();">
</div>
</form>
</body>
The problem is that I can't get my Python function to take the value of the buttons themselves.问题是我无法让我的 Python function 获取按钮本身的值。 I do succesfully save data in an earlier part of the site where users have to enter their age and gender in a form, but I just can't get it to work when there are no fields to enter the data.我确实成功地将数据保存在网站的早期部分,用户必须在表单中输入他们的年龄和性别,但是当没有输入数据的字段时,我无法让它工作。 The value from the button itself should be saved.按钮本身的值应该被保存。
Python function Python function
@app.route("/recog1", methods=["POST", "GET"])
def recog1():
if request.method == "GET":
return render_template("recog1.html")
Yes = request.form['Yes']
No = request.form['No']
entry_time = datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
#save to file
with open(BASE_DIR + '/userinfo/userinfo.csv', 'a+') as myfile:
myfile.write(
str(entry_time) + ', ' +
str(Yes) + ', ' +
str(No) + ', '
+ '\n')
myfile.close()
return redirect(url_for("thankyou"))
Now, there is a lot wrong with what is done with the data here and it would immediately go to the thankyou page, instead of waiting for thirty button clicks.现在,这里的数据有很多问题,它会立即 go 到感谢页面,而不是等待三十个按钮点击。 I'll change those things later but first the problem is that I can't even get the button values to my python here.我稍后会更改这些内容,但首先问题是我什至无法将按钮值获取到我的 python 此处。 I always get "Bad Request: The browser (or proxy) sent a request that this server could not understand".我总是收到“错误请求:浏览器(或代理)发送了此服务器无法理解的请求”。 I have looked at stackoverflow questions similar to this but they have never been useful to me or more likely, I didn't know how exactly to apply them to my case.我看过与此类似的 stackoverflow 问题,但它们对我来说从来没有用过,或者更有可能的是,我不知道如何将它们准确地应用于我的案例。 Any amount of help would be greatly appreciated and thank you for taking the time to read!任何数量的帮助将不胜感激,并感谢您花时间阅读!
EDIT: To solve the issue, the Yes = request.form['Yes']
and No = request.form['No']
in my python function needed to be replaced with x = request.form['Answer']
, where I set "Answer" as the name for both the buttons in HTML.编辑:为了解决这个问题,我的 python function 中的Yes = request.form['Yes']
和No = request.form['No']
需要替换为x = request.form['Answer']
,其中我将“Answer”设置为 HTML 中两个按钮的名称。
Try this in your python route在您的 python 路线中试试这个
if request.method == 'POST':
if "answerY" in request.form:
print('yes button pressed')
elif "answerN" in request.form:
print('no button pressed')
edit1:编辑1:
Try making a route like this, and then in your javascript function you could reroute to this route or handle it in your form action.尝试制作这样的路线,然后在您的 javascript function 中,您可以重新路由到该路线或在您的表单操作中处理它。
@app.route('/buttonresult/<button_id>', methods=['GET','POST'])
def buttonresult(button_id):
yes_string = ''
no_string = ''
if button_id == 'answerY':
# do something
yes_string = 'Yes'
elif button_id == 'answerN':
# do something
no_string = 'No'
entry_time = datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
#save to file
with open(BASE_DIR + '/userinfo/userinfo.csv', 'a+') as myfile:
myfile.write(
str(entry_time) + ', ' +
str(Yes) + ', ' +
str(No) + ', '
+ '\n')
myfile.close()
return redirect(url_for("thankyou"))
In order to redirect page from javascript function you can do this为了从 javascript function 重定向页面,您可以这样做
# get button_id value somehow
windows.location.href = '/buttonresult/" + button_id
I think maybe I wasn't being very clear in my comment, so I'm posting this answer.我想也许我的评论不是很清楚,所以我发布了这个答案。
Try changing your recog1
function to the following:尝试将您的recog1
function 更改为以下内容:
@app.route("/recog1", methods=["POST"])
def recog1():
print(request.form)
return str(request.form)
When you press either the Yes
or No
button, what gets printed in your terminal/what do you see in the browser?当您按下“是”或“ Yes
No
按钮时,终端中会打印什么/您在浏览器中看到什么? Do you still receive the same error?你仍然收到同样的错误吗?
EDIT - When you press one of the two buttons, only one of the values will show up in request.form
.编辑 - 当您按下两个按钮之一时,只有一个值会显示在request.form
中。 This makes sense if you think about it - you can only ever press one of the two buttons, but not both.如果您考虑一下,这是有道理的——您只能按下两个按钮之一,但不能同时按下两个按钮。 If you press the "Yes" button, request.form
will have a key-value pair for Yes
, but not for No
.如果您按下“是”按钮, request.form
将有一个键值对Yes
,但没有No
。 If you press the "No" button, request.form
will have a key-value pair for No
, but not for Yes
.如果您按下“否”按钮, request.form
将有一个键值对用于No
,但没有用于Yes
。 The way your code is written right now, it assumes request.form
will always have both key-value pairs.您现在编写代码的方式假定request.form
将始终具有两个键值对。 This, of course, can never be true, and so regardless of what button you press, the missing key for the other one results in the error you're seeing.当然,这不可能是真的,因此无论您按下哪个按钮,另一个按钮的缺失都会导致您看到的错误。
You need to check for the presence of the Yes
and No
keys seperately, and then perform an action based on that.您需要分别检查是否存在Yes
和No
键,然后基于此执行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.