Flask CRUD Application with MySQL -
Detailed Explanation
1. Importing Modules
- Flask: Main framework to build web apps.
- render_template: To render HTML files (templates).
- request: To get data sent by the client (browser), e.g., form data.
- redirect: To send the user to a different page.
- url_for: To generate URLs dynamically for routes.
- pymysql: Python library to connect and talk to MySQL.
2. Create Flask app instance
app = Flask(__name__)
- Creates a Flask web app object named app.
- __name__ is the name of the current Python module, tells Flask where to look for templates
and static files.
3. Connect to MySQL database
db = pymysql.connect(host='localhost', user='root', password='', database='flask_crud')
cursor = db.cursor()
- Connects to your MySQL server running on your machine (localhost).
- User: 'root', password is blank ('') — change if you have a password.
- Database: 'flask_crud' — the database you created.
- cursor: An object to execute SQL queries and fetch data.
4. Route: Show all users
@app.route('/')
def index():
cursor.execute("SELECT * FROM users")
users = cursor.fetchall()
return render_template('index.html', users=users)
- @app.route('/') means when user visits root URL /.
- SQL query "SELECT * FROM users" selects all users.
- cursor.fetchall() fetches all rows returned by the query as a list of tuples.
- render_template('index.html', users=users) sends users data to the index.html template, so
it can display all users.
5. Route: Create new user
@app.route('/create', methods=['GET', 'POST'])
def create():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
cursor.execute("INSERT INTO users (name, email) VALUES (%s, %s)", (name, email))
db.commit()
return redirect(url_for('index'))
return render_template('create.html')
- @app.route('/create', methods=['GET', 'POST']) accepts GET and POST on /create.
- When method is GET: just show the form to create a user (create.html).
- When method is POST: form was submitted.
- request.form['name'] gets the input named name from the form.
- request.form['email'] gets the input named email.
- Execute an SQL INSERT to add user data to users table.
- db.commit() saves changes in database.
- Redirect user back to homepage (index) to see updated list.
6. Route: Update existing user
@app.route('/update/<int:id>', methods=['GET', 'POST'])
def update(id):
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
cursor.execute("UPDATE users SET name=%s, email=%s WHERE id=%s", (name, email,
id))
db.commit()
return redirect(url_for('index'))
cursor.execute("SELECT * FROM users WHERE id=%s", (id,))
user = cursor.fetchone()
return render_template('update.html', user=user)
- @app.route('/update/<int:id>') URL contains an integer id for the user to update.
- GET request:
- Fetch user data with that id from the database.
- Send user data to update.html form so fields are pre-filled.
- POST request:
- Get updated values from form.
- Execute SQL UPDATE query to change user info where id matches.
- Commit changes and redirect back to homepage.
7. Route: Delete a user
@app.route('/delete/<int:id>')
def delete(id):
cursor.execute("DELETE FROM users WHERE id=%s", (id,))
db.commit()
return redirect(url_for('index'))
- @app.route('/delete/<int:id>') URL with user id to delete.
- Execute SQL DELETE query to remove user by id.
- Commit changes to save.
- Redirect back to homepage to see updated list.
8. Run Flask app
if __name__ == '__main__':
app.run(debug=True)
- Runs the Flask development server if you execute python app.py.
- debug=True enables debug mode — shows errors and reloads server on code changes.
Summary
- Your app talks to MySQL with pymysql.
- / shows a list of all users.
- /create shows form to add user and handles form submission.
- /update/<id> lets you edit an existing user.
- /delete/<id> deletes user by id.
- You use HTML templates (render_template) to show forms and data.
- After every change (create/update/delete), app saves to DB and redirects you to updated
list.
Data flow when creating a user
1. User visits /create → form shows.
2. User types name + email → submits form (POST).
3. Server reads form data → runs INSERT query.
4. Server commits to DB → redirects user to /.
5. Homepage loads → shows new user in the list.