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

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

Mary-Kate Olsen
Release: 2024-12-23 18:11:09
Original
1017 people have browsed it

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

Sending Data from HTML Form to Python Script in Flask

In Flask, sending data from an HTML form to a Python script involves implementing an HTML form with appropriate attributes and a Python view to handle the data on the server side. Here's how you can accomplish this:

HTML Form Setup

The HTML form needs to specify the following attributes:

  • action: Sets the URL for submitting the form data. Use url_for to generate the URL for the handling view in your script.
  • method="post": Indicates that the data will be submitted using the POST method.
  • enctype="multipart/form-data": Required if the form contains file inputs.

Additionally, each input element that you want to pass data from must have a name attribute.

Python View for Handling Data

Create a Python view to handle the submitted data. This view will access the data using request.form under the name key of the corresponding input. File inputs will be accessible in request.files.

@app.route('/handle_data', methods=['POST'])
def handle_data():
    projectpath = request.form['projectFilepath']
    # Your code to process the data and return a response
Copy after login

Example HTML Form

With these attributes set, your HTML form might look something like this:

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

Conclusion

By following these steps, you can successfully send data from an HTML form to a Python script using Flask. This powerful feature enables interactive user input and data processing in web applications.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template