Taking user input from HTML form as a variable for Python script [duplicate] Taking user input from HTML form as a variable for Python script [duplicate] flask flask

Taking user input from HTML form as a variable for Python script [duplicate]


templates/index.html

<form method="POST">    <input name="variable">    <input type="submit"></form>

app.py

from flask import Flask, request, render_templateapp = Flask(__name__)@app.route('/')def my_form():    return render_template('index.html')@app.route('/', methods=['POST'])def my_form_post():    variable = request.form['variable']    return variable


I guess you have set up and endpoint to run that script, an URL mapped to a function. In that case you need to call it from the form action.

for example

@app.route('/my-function')def your_function(parameters):    "code to do something awesome"    return "the result of your function"

So, in your form you should:

<form class="userinput" method="GET" action="/my-function">    <input type="text" placeholder="Search..">    <button type="submit"></button></form>

That should do the trick.

Go to the Flask home page for more examples.