Here’s a comprehensive Python script to collect data from a form (Form1) and store it into a test database using a relational database management system like SQLite. The example below uses Flask for the web framework to handle the form submission and SQLAlchemy for database interaction.
Steps Covered
- Set up Flask app to handle HTTP requests.
- Create a database with SQLAlchemy.
- Define the form and database model.
- Store submitted data into the database.
PYthon Code to Handle HTTP Request
from flask import Flask, render_template, request, redirect, url_forfrom flask_sqlalchemy import SQLAlchemyapp = Flask(__name__)# Configure the SQLite databaseapp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = Falsedb = SQLAlchemy(app)# Define the database modelclass FormData(db.Model):id = db.Column(db.Integer, primary_key=True)name = db.Column(db.String(100), nullable=False)email = db.Column(db.String(120), nullable=False)message = db.Column(db.Text, nullable=True)def __repr__(self):return f"<FormData {self.name}>"# Initialize the databasewith app.app_context():db.create_all()# Route for the form@app.route('/', methods=['GET', 'POST'])def form1():if request.method == 'POST':# Collect form dataname = request.form['name']email = request.form['email']message = request.form.get('message', '')# Validate required fieldsif not name or not email:return "Name and Email are required!", 400# Save to databaseform_data = FormData(name=name, email=email, message=message)db.session.add(form_data)db.session.commit()return redirect(url_for('thank_you'))return render_template('form.html')# Thank you page@app.route('/thank-you')def thank_you():return "<h1>Thank you for your submission!</h1>"# View stored data (optional)@app.route('/view-data')def view_data():all_data = FormData.query.all()return render_template('view_data.html', data=all_data)if __name__ == '__main__':app.run(debug=True)
Create a file named form.html
in the templates
directory:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Form</title></head><body><h1>Submit Your Information</h1><form method="POST" action="/"><label for="name">Name:</label><input type="text" id="name" name="name" required><br><br><label for="email">Email:</label><input type="email" id="email" name="email" required><br><br><label for="message">Message:</label><textarea id="message" name="message"></textarea><br><br><button type="submit">Submit</button></form></body></html>
Create a file named view_data.html
in the templates
directory
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>View Data</title></head><body><h1>Submitted Data</h1><table border="1"><thead><tr><th>ID</th><th>Name</th><th>Email</th><th>Message</th></tr></thead><tbody>{% for item in data %}<tr><td>{{ item.id }}</td><td>{{ item.name }}</td><td>{{ item.email }}</td><td>{{ item.message }}</td></tr>{% endfor %}</tbody></table></body></html>
- Install All Packages i.e pip install flask flask-sqlalchemy.
- Run the Application python app.py
- Open your browser at
http://127.0.0.1:5000/
.