Here's an example of a Flask web application that renders a form with two input fields:
Tested with Python 3.11, Flask and csv python modules.
This code defines a Flask web application with a single route (‘/’) that supports both GET and POST methods. When the user visits the page via GET, the application renders an HTML template named index.html. When the user submits the form via POST, the application retrieves the values of the name and email fields from the request and returns a greeting message that includes those values.
Code app.py
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route(‘/’, methods=[‘GET’, ‘POST’])
def index():
if request.method == ‘POST’:
name = request.form[‘name’]
email = request.form[’email’]
return f”Hello {name} ({email})!”
return render_template(‘index.html’)
if __name__ == ‘__main__’:
app.run(debug=True)
This template defines a simple form with two input fields: a text input for the name field and an email input for the email field. When the user submits the form, the values of these fields will be sent to the server via a POST request.
Code templates/index.html
<!doctype html>
<html>
<head>
<title>My Flask Form</title>
</head>
<body>
<h1>Welcome to My Flask Form!</h1>
<form method=”post”>
<label for=”name”>Name:</label>
<input type=”text” id=”name” name=”name”><br>
<label for=”email”>Email:</label>
<input type=”email” id=”email” name=”email”><br>
<input type=”submit” value=”Submit”>
</form>
</body>
</html>
Now… test and run your application. We will add the save to csv file by updating our app.py file next.
How do I save the user input into a csv file?
You can save the data submitted through the Flask form to a CSV file by using the csv module in Python. Here’s an updated version of the Flask application that saves the data to a CSV file named data.csv:
Updated Code app.py
import csv
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route(‘/’, methods=[‘GET’, ‘POST’])
def index():
if request.method == ‘POST’:
name = request.form[‘name’]
email = request.form[’email’]
with open(‘data.csv’, mode=’a’, newline=”) as csvfile:
writer = csv.writer(csvfile)
writer.writerow([name, email])
return f”Hello {name} ({email})! Your data has been saved to the CSV file.”
return render_template(‘index.html’)
if __name__ == ‘__main__’:
app.run(debug=True)
In this updated version, we import the csv module and open the data.csv file in append mode using the with statement. We create a csv.writer object and use its writerow method to write a new row to the CSV file with the name and email values.
When the user submits the form, the data is saved to the CSV file and a message is returned to the user indicating that their data has been saved.
Note that we pass newline=” as a parameter to the open function. This is required to ensure that the CSV file is written with the correct line endings, as different operating systems use different conventions for line endings.