Home >Backend Development >Python Tutorial >How to Submit HTML Form Data to a Flask Python Script?

How to Submit HTML Form Data to a Flask Python Script?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-23 14:19:17737browse

How to Submit HTML Form Data to a Flask Python Script?

Submitting User Input from HTML Form to a Python Script in Flask

To pass user input from an HTML form to a Python script in Flask, the form and its elements must be configured appropriately.

HTML Form Configuration:

  • Set an action attribute on the
    tag that specifies the URL of the Python script that will handle the submitted data.
  • Set the method attribute to "post" to submit the data as form data using the POST method.
  • Include an enctype attribute with the value "multipart/form-data" if the form contains any file inputs.
  • Give each input element a unique name attribute.

Python Script Configuration:

Define a view in the Python script to handle the submitted data with appropriate parameters for the input element's name. For example, the following view handles the "projectFilepath" input:

@app.route('/handle_data', methods=['POST'])
def handle_data():
    projectpath = request.form['projectFilepath']
    # ... Your code to process the input

Example HTML Form:

<form action="{{ url_for('handle_data') }}" method="post" enctype="multipart/form-data">
    <input type="text" name="projectFilepath" placeholder="Spot your project files">
    <input type="submit" value="Spot">
</form>

Additional Considerations:

  • The url_for function generates the URL for the designated view dynamically based on the Flask application's route configuration.
  • The Python script will have access to the submitted data from the input elements through the request.form or request.files objects, depending on the type of input.

The above is the detailed content of How to Submit HTML Form Data to a Flask Python Script?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn