Web UI for Python function

Question:

I have a python function that takes a series of integers as inputs and returns another series of integers. I’d like to distribute the function in the form of a web app.

The landing page should consist of a web form with a series of integer fields (with input validation), drop-down fields and a submit button. The submit button triggers the said python function and returns the results which should be rendered in an html table.

I am a complete novice with web development, but after some research it appears that flask is the most appropriate framework for me to use for the above task. My problem is that the documentation I have encountered so far deals primarily with blog development and therefore not particularly relevant for the type of app I am after.

I am therefore seeking any pointers (sample code, books, articles) or guidance to get me started with my task. In its simplest form, what I’m looking for is:

  • web form that takes one integer (1-10) and a second integer (1-5) from a drop down list
  • web form returns error if user enters invalid integer (<1, >10)
  • on submit button python function calculates the sum of the two integers
  • result is presented on the web form

All guidance appreciated.

Asked By: zanzu

||

Answers:

Well it’s quite simple really, it’s all about how you present a form in html template, getting your view to get the form data, and passing the context back to the template.

I’ve quickly mocked a sample like what you want (nothing fancy, just back to the basic and show you how these work together), it’s only a few lines of code in 2 files main.py (core file, like a view logic) and a template calculation.html:

main.py

from flask import Flask
from flask import render_template
from flask import request

app = Flask(__name__)

@app.route("/", methods=['GET', 'POST'])
def calculation():
    result = 0
    error = ''
    # you may want to customize your GET... in this case not applicable
    if request.method=='POST':
        # get the form data
        first = request.form['first']
        second = request.form['second']
        if first and second:
            try:
                # do your validation or logic here...
                if int(first)>10 or int(first)<1:
                    raise ValueError
                result = int(first) + int(second)
            except ValueError:
                # you may pass custom error message as you like
                error = 'Please input integer from 1-10 only.'
    # you render the template and pass the context result & error
    return render_template('calculation.html', result=result, error=error)

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

templates/calculation.html

<h1>Calculation</h1>
<form method="POST">
    <input type="text" name="first" value="">
    <select name="second">
        <option value="1" selected>1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
    </select> 
    <input type="submit" value="Submit">
    {% if result %}
    <p>
        <label name='result'>Answer is: {{ result }}</label>
    </p>
    {% endif %}
    {% if error %}
    <p>
    <label name="error">{{ error }}</label>
    </p>
    {% endif %}
</form>

Hopefully these are self explanatory and you can get to understand how to work with the basic of Flask and forms etc.

Read Flask Doc, and try to follow through, they are quite simple really and once you nail the basic, you may start looking for intermediate and advance topic.

FYI, there is an extension for WTForms called Flask-WTF, it is very handy when dealing with forms, although nothing stops you just doing everything in plain html form like above code.

Hope this helps and I wish you like the simplicity and flexiblity Flask brings you.

Answered By: Anzel

With NiceGUI you can build such UIs with a few lines of Python:

from nicegui import ui

i = ui.number(format='%d')
j = ui.select([1, 2, 3, 4, 5])
results = ui.table({
    'columnDefs': [{'field': 'i'}, {'field': 'j'}, {'field': 'sum'}],
    'rowData': [],
}).classes('max-h-40')

def calculate():
    if not 1 <= i.value <= 10:
        ui.notify('Invalid input')
        return
    results.options['rowData'].append({'i': i.value, 'j': j.value, 'sum': i.value + j.value})
    results.update()

ui.button('Calculate', on_click=calculate)

ui.run()

enter image description here

HTML, JS and CSS are not required.

For this example I made use of ui.table, which builds on AG Grid and allows you to create pretty data tables. But you could display a simple ui.label as well.

(Disclaimer: I’m one of the developers of NiceGUI.)

Answered By: Falko
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.