Adrian
Adrian

Reputation: 907

how to assign python function to value attribute in dropdown list in HTML

I have a website with a dropdown list and I'd like to assign python function to each option. Once the user will click submit button Python function should be triggered and the user should see the output (in this case it is just print in the console). I am using Flask to run this website.

This is my html code:

<div class="form-inline align-items-center">
    <label class="mr-sm-2 col-form-label-lg">Trusted Content</label>

    <select class="custom-select" onchange="showDiv('hiddenform', this)">
        <option value="" selected disabled>Choose option</option>
        <option value="1">Previous version</option>
        <option value="2">Current version</option>
        <option value="3">From Excel</option>
    </select>
    <form method="POST" action="" enctype="multipart/form-data"
          class="collapse row justify-content-center mx-auto" id="hiddenform">
        <div class="input-group p-2">
            <div class="custom-file">
                <input type="file" class="custom-file-input pointer" name="file">
                <label class="custom-file-label pointer" for="customFile">Choose
                    file</label>
            </div>
        </div>
    </form>

<div class="modal-footer">
    <button id="rightdiv" onclick="GoToGAPAnalysis()" type="button"
            class="btn btn-primary">Submit
    </button>
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>

And these are my python functions that I will like to assign. The function connects to my database and it works fine when I am running it in PyCharm but I don't know how to run this function on my website:

def current_version(current_version_df):
    get_current_version = current_version_df.groupby('product_ID').max()['version']
    db_connection = create_engine(
        "mysql+pymysql://{user_name}:{user_password}@localhost/{db}".format(**load_credentials()))
    get_current_version = pd.read_sql("SELECT * FROM product WHERE code = '88300162513';", con=db_connection)
    print(get_current_version)
    return get_current_version


def previous_version(previous_version_df):
    get_previous_version = previous_version_df[previous_version_df.groupby('product_ID')['version'].transform('max').sub(1).eq(df['version'])]
    db_connection = create_engine(
        "mysql+pymysql://{user_name}:{user_password}@localhost/{db}".format(**load_credentials()))
    get_previous_version = pd.read_sql("SELECT * FROM product WHERE code = '88300162513';", con=db_connection)
    print(get_previous_version)
    return get_previous_version

I know that my functions just print the result but I'd like to understand the logic behind assigning Python/Flask functions to my dropdown list in HTML. I'd like to assign def current_version to value="2" and def get_previous_version to value="1".

Upvotes: 0

Views: 464

Answers (1)

shiny
shiny

Reputation: 678

You want to make an endpoint in flask and call it with javascript. Here is an example:

python

# app.py
from flask import Flask, jsonify, request, render_template
app = Flask(__name__)

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

    # POST request
    if request.method == 'POST':
        print('Incoming..')
        print(request.get_json())  # parse as JSON
        return 'OK', 200

    # GET request
    else:
        message = {'greeting':'Hello from Flask!'}
        return jsonify(message)  # serialize and use JSON headers

@app.route('/test')
def test_page():
    # look inside `templates` and serve `index.html`
    return render_template('index.html')

js

// GET is the default method, so we don't need to set it
fetch('/hello')
    .then(function (response) {
        return response.text();
    }).then(function (text) {
        console.log('GET response text:');
        console.log(text); // Print the greeting as text
    });

// Send the same request
fetch('/hello')
    .then(function (response) {
        return response.json(); // But parse it as JSON this time
    })
    .then(function (json) {
        console.log('GET response as JSON:');
        console.log(json); // Here’s our JSON object
    })

source: https://healeycodes.com/javascript/python/beginners/webdev/2019/04/11/talking-between-languages.html

Upvotes: 2

Related Questions