Jake Shorty
Jake Shorty

Reputation: 727

How do I use Flask to pass a Python function input from an HTML form?

I'm working on a web app with Flask but am a novice and am struggling to learn with the documentation. Within a form on a webpage, I have a table of images which are all buttons. I have a Python script, that when passed a specific string will retrieve a small piece of text data from an API. For each cell in the table, my HTML is in this format:

<form action="/" method="POST">
    <table>
     <thead></thead>
     <tbody><tr>
        <td><input type=image src="image.jpg" name="SNOWY OWL" value="SNOW"/></td>
        <td><input type=image src="image.jpg" name="BARD OWL" value="BARD"/></td>
        <td><input type=image src="image.jpg" name="BARN OWL" value="BARN"/></td>
     </tr></tbody>
    </table>
</form>

When passed with the string in the value= attribute of <input>, a function in my Python script can return what I'm looking for.

Is there a simple method using Flask to take this value= attribute and plug it into a Python function, and return the results in text on the webpage?

Upvotes: 2

Views: 3583

Answers (1)

1478963
1478963

Reputation: 1216

You have to give all the cells the same name so that flask can return the value like this:

  <td><input type=image src="image.jpg" name="SNOWY OWL" value="SNOW"/></td>`
  <td><input type=image src="image.jpg" name="SNOWY OWL" value="BARD"/></td>`
  <td><input type=image src="image.jpg" name="SNOWY OWL" value="BARN"/></td>`

Your Python code would be:

@app.route('/', methods = ['POST'])
def choose():
    print( request.form.get('SNOWY OWL',None),"CLICKED!")
    return render_template('index.html')

How it works is as follows: request.form.get("NAMEOFTHECLICKED","WHATTORETURNIFNOSUCHNAME")

The Following is printed:

('BARD', "CLICKED!")

('BARN', "CLICKED!")

Upvotes: 2

Related Questions