Flask
Published:
This post covers forms in Flask using Calculator App!
Calculator in Flask!
/* static/style.css */
h1{
color: red;
}
.other{
color: blue;
}
<!-- templates/form.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>Calculator</title>
<link rel="stylesheet" href="{{url_for('static', filename='style.css')}}">
</head>
<body align=center>
<h1>CALCULATOR</h1> <br>
<form action={{ url_for('result') }} method="post">
<label for="num_1">Number 1:</label>
<input type="number" name="num_1", placeholder="Enter value">
<!-- <input type="number" name="num_1", value="0"> -->
<br>
<label for="num_2">Number 2:</label>
<input type="number" name="num_2" placeholder="Enter value">
<!-- <input type="number" name="num_2" value="0"> -->
<br>
<label >Operation:</label>
<select name="operation">
<option>Addition</option>
<option>Subtraction</option>
<option>Multiplication</option>
<option>Division</option>
</select>
<br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</body>
</html>
<!-- templates/result.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>RESULT</title>
<link rel="stylesheet" href="{{url_for('static', filename='style.css')}}">
</head>
<body align=center>
<h1>RESULT</h1>
<h4><a class='other' href="{{url_for('index')}}"> Calculator </a></h4>
<form>
<fieldset disabled>
<label for="result"></label>
<input type="text" name="result" placeholder=>
</fieldset>
</form>
</body>
</html>
# calculator.py
from flask import Flask, render_template, request
app = Flask(__name__)
app.config.from_object(__name__)
@app.route('/')
def index():
return render_template('form.html')
@app.route('/result', methods=['POST'])
def result():
num_1 = request.form.get("num_1", type=int)
num_2 = request.form.get("num_2", type=int)
operation = request.form.get("operation")
if(operation == 'Addition'):
result = num_1 + num_2
if(operation == 'Subtraction'):
result = num_1 - num_2
if(operation == 'Multiplication'):
result = num_1 * num_2
if(operation == 'Division'):
result = num_1 / num_2
return render_template('result.html', result=result)
if __name__ == '__main__':
app.run(debug=True)