Bartłomiej 'furas' Burek
furas.pl
# prywatne notatki - Python, Linux, Machine Learning, etc.

Flask: Sum values in form[GB]

It uses the same function to render empty form and later to get values from form, calculate sum and render page with results.

It uses request.form to get values from form. Because inputs have the same name so it use .getlist to get all values.

Later it convert values to float, sum them and use {{ result }} to put sum in form.

from flask import Flask, request, render_template_string

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():

    if request.method == 'POST':
        vals = request.form.getlist('daily_calories')
        val1 = float(vals[0])
        val2 = float(vals[1])
        result = val1 + val2
    else:
        val1 = ''
        val2 = ''
        result = ''

    return render_template_string('''
<form action="/" method="POST">
      <p>Input 1: <input type="number" name="daily_calories" value="{{ val1 }}"></p>
      <p>Input 2: <input type="number" name="daily_calories" value="{{ val2 }}"></p>
      <input type="submit" value="Calculate">
      <p>Result: <input type="number" name="result_dc" value="{{ result }}"></p>
</form>
''', val1=val1, val2=val2, result=result)

if __name__ == '__main__':
    app.run()

Similar example using only JavaScript to get values, calculate sum and put it in form. It blocks button to send data to server and flask doesn't have to calculate it.

If user doesn't use JavaScript then it will not work and it would need mix with previous version.

from flask import Flask, request, render_template_string

app = Flask(__name__)

@app.route('/')
def index():
    return render_template_string('''
<form action="/" method="POST">
      <p>Input 1: <input type="number" name="daily_calories" value="" id="val1"></p>
      <p>Input 2: <input type="number" name="daily_calories" value="" id="val2"></p>
      <input type="submit" value="Calculate" id="button_calculate">
      <p>Result: <input type="number" name="result_dc" value="" id="result"></p>
</form>
<script>
var val1_input = document.getElementById("val1");
var val2_input = document.getElementById("val2");
var result_input = document.getElementById("result");
var button_input = document.getElementById("button_calculate");
button_input.onclick = function() {
    result_input.value = parseFloat(val1_input.value) + parseFloat(val2_input.value);
    return false; // don't send to server
}
</script>
''')

if __name__ == '__main__':
    app.run()

This example uses pure JavaScript to set AJAX to different url which send result.

from flask import Flask, request, render_template_string

app = Flask(__name__)

@app.route('/')
def index():
    return render_template_string('''
<form action="/" method="POST">
      <p>Input 1: <input type="number" name="daily_calories" value="" id="val1"></p>
      <p>Input 2: <input type="number" name="daily_calories" value="" id="val2"></p>
      <input type="submit" value="Calculate" id="button_calculate">
      <p>Result: <input type="number" name="result_dc" value="" id="result"></p>
</form>
<script>
var val1_input = document.getElementById("val1");
var val2_input = document.getElementById("val2");
var result_input = document.getElementById("result");
var button_input = document.getElementById("button_calculate");

button_input.onclick = function(event) {
    var formData = new FormData();

    formData.append('val1', val1_input.value)
    formData.append('val2', val2_input.value)

    var request = new XMLHttpRequest();

    request.onreadystatechange = function() {
        if(request.readyState == 4 && request.status == 200)
        {
            //alert(request.responseText);
            result_input.value = request.responseText;
        }
    }

    request.open('POST', "/calculate");

    // execute the request
    request.send(formData);

    return false; // don't send button to server
}
</script>
''')

@app.route('/calculate', methods=['POST'])
def calcualte():
    val1 = float(request.form.get('val1'))
    val2 = float(request.form.get('val2'))

    return str(val1+val2)

if __name__ == '__main__': 
    app.run()

And the same with jQuery

from flask import Flask, request, render_template_string

app = Flask(__name__)

@app.route('/')
def index():
    return render_template_string('''<!DOCTYPE html>
<html>
<head>
<!-- can't be `slim` version because it has not `$.ajax` -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>

<form action="/" method="POST">
      <p>Input 1: <input type="number" name="daily_calories" value="" id="val1"></p>
      <p>Input 2: <input type="number" name="daily_calories" value="" id="val2"></p>
      <input type="submit" value="Calculate" id="button_calculate">
      <p>Result: <input type="number" name="result_dc" value="" id="result"></p>
</form>

<script>$(function() {
    $('#button_calculate').click(function(e) {

        var val1_input = $('input[id=val1]').val();
        var val2_input = $('input[id=val2]').val();

        $.post({
            url: "/calculate",
            data: {
                "val1": val1_input, 
                "val2": val2_input
            },
            success: function(data){
                $('#result').val(data);
            },
            error: function(){
                console.log('in error');
            }
        });

        e.preventDefault();
    });
});
</script>
</body>
</html>
''')

@app.route('/calculate', methods=['POST'])
def calcualte():
    val1 = float(request.form.get('val1'))
    val2 = float(request.form.get('val2'))
    print(val1+val2)
    return str(val1+val2)

if __name__ == '__main__':
    app.run()
Książki: python-dla-kazdego-podstawy-programowania python-wprowadzenie python-leksykon-kieszonkowy python-receptury python-programuj-szybko-i-wydajnie python-projekty-do-wykorzystania black-hat-python-jezyk-python-dla-hackerow-i-pentesterow efektywny-python-59-sposobow-na-lepszy-kod tdd-w-praktyce-niezawodny-kod-w-jezyku-python aplikacje-internetowe-z-django-najlepsze-receptury