Answer the question
In order to leave comments, you need to log in
Validating valid input in Python/Flask?
Help me write a program that will check the correctness of the entered answer to a mathematical expression, but with the main condition - sessions. Now the non-working code is:
def index():
form = NameForm()
first = random.randint(0,10)
second = random.randint(0,10)
answer = first * second
if form.validate_on_submit():
if answer == int(form.ans.data):
flash('Right')
return redirect(url_for('index'))
Answer the question
In order to leave comments, you need to log in
Help write a program that will check the correctness of the entered answer to a mathematical expression,More or less like this. You show the user (when receiving a GET request) two numbers. On the form, in addition, there must be two hidden input fields with the same numbers. Anti-forgery protection (so that the user adds exactly the numbers that were sent to him) can be implemented using a csrf token or self-hashing of two values (the first option is preferable). When receiving a POST request, compare the sum of numbers (from hidden fields) with user input and draw conclusions.
from flask import Flask, render_template, request
from wtforms import TextField, HiddenField
from flask.ext.wtf import Form
from random import randint
app = Flask(__name__)
app.secret_key = 'perkele 9000'
class TestForm(Form):
answer = TextField("answer")
val1 = HiddenField("val1")
val2 = HiddenField("val2")
@app.route('/', methods=["POST", "GET"])
def test():
if request.method == 'POST':
form = TestForm(request.form)
try:
if int(form.val1.data) + int(form.val2.data) == int(form.answer.data):
return "OK!"
except ValueError:
pass
return "Not OK!"
if request.method == 'GET':
form = TestForm()
form.val1.data = randint(1,99)
form.val2.data = randint(1,99)
return render_template('template.html', form = form)
if __name__ == '__main__':
app.debug = True
app.run()
<html>
<head>
<title>Test your arithmetic skills</title>
</head>
<body>
<table>
<tr><td>Calculate <b>{{form.val1.data}} + {{form.val2.data}}</b></td></tr>
<tr>
<td>
<form method=post action="{{ url_for('test') }}">
{% for field in form %}
{{field}}
{% endfor %}
<input type=submit value="OK">
</form>
</td>
</tr>
</table>
</body>
</html>
yes, my friend, you still need to learn and learn.
https://jsfiddle.net/b9pdaqsd/
advice
$view_2 = isset($_GET['view_2']) ? @intval($_GET['view_2']) : null;
if (!$view_2)
return false;
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question