Sending data from HTML form to a Python script in Flask

Sending data from HTML form to a Python script in Flask

The form tag needs some attributes set:

  1. action: The URL that the form data is sent to on submit. Generate it with url_for. It can be omitted if the same URL handles showing the form and processing the data.
  2. method=post: Submits the data as form data with the POST method. If not given, or explicitly set to get, the data is submitted in the query string (request.args) with the GET method instead.
  3. enctype=multipart/form-data: When the form contains file inputs, it must have this encoding set, otherwise the files will not be uploaded and Flask wont see them.

The input tag needs a name parameter.

Add a view to handle the submitted data, which is in request.form under the same key as the inputs name. Any file inputs will be in request.files.

@app.route(/handle_data, methods=[POST])
def handle_data():
    projectpath = request.form[projectFilepath]
    # your code
    # return a response

Set the forms action to that views URL using url_for:

<form action={{ url_for(handle_data) }} method=post>
    <input type=text name=projectFilepath>
    <input type=submit>
</form>

You need a Flask view that will receive POST data and an HTML form that will send it.

from flask import request

@app.route(/addRegion, methods=[POST])
def addRegion():
    ...
    return (request.form[projectFilePath])
<form action={{ url_for(addRegion) }} method=post>
    Project file path: <input type=text name=projectFilePath><br>
    <input type=submit value=Submit>
</form>

Sending data from HTML form to a Python script in Flask

Leave a Reply

Your email address will not be published. Required fields are marked *