PFFY 2 Packs Unisex Beanie Hats for Men and Women Knit Winter Beanies
15% OffBlue Marble Ice Cream Organic Vanilla, 14 oz (Frozen)
$39.99 (as of November 11, 2024 23:50 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)Flask is a popular Python web framework that is often used for building web applications and APIs. Combined with SQLAlchemy, a Python SQL toolkit and ORM, Flask provides a simple yet powerful way to create a CRUD (Create, Read, Update, Delete) web application.
In this comprehensive tutorial, we will walk through how to build a basic CRUD web app from scratch using Flask and SQLAlchemy.
Overview
Here is what we will cover:
- Set up a Flask application
- Configure SQLAlchemy
- Define database models
- Set up routes and views for CRUD operations
- Create
- Read
- Update
- Delete
- Connect frontend to backend logic
By the end, you will have a fundamental understanding of building CRUD functionality with Flask and SQLAlchemy.
Prerequisites
Before starting, you should have:
- Basic understanding of Python web frameworks
- Basic understanding of SQL and databases
- Python 3 installed on your system
- Flask and SQLAlchemy installed
Here are the versions used for this tutorial:
- Python 3.7
- Flask 1.1.2
- SQLAlchemy 1.3.13
Set up a Flask Application
We will use the Flask framework to handle requests and rendering templates. Here are the steps to set up a basic Flask app:
1. Import Flask and create the app
from flask import Flask
app = Flask(__name__)
JavaScript2. Define routes
We need to add routes that map URLs to Python functions. For now we will just define a simple home page route.
@app.route("/")
def home():
return "Hello, World!"
JavaScript3. Run development server
Now we can start our development server to test it out:
$ flask run
JavaScriptYou should be able to open http://localhost:5000
and see our “Hello, World!” message.
Configure SQLAlchemy
With our basic Flask app set up, let’s configure SQLAlchemy for database access.
1. Import SQLAlchemy and create DB connection
First import sqlalchemy
and initialize a SQLAlchemy instance:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
JavaScriptThis connects SQLAlchemy to our Flask application.
2. Choose database URI
We need to specify the database URI that tells SQLAlchemy where to connect. We will use a SQLite database for this tutorial.
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydb.db'
JavaScript3. Initialize database
Now that everything is configured, we can initialize our database:
$ flask db init
JavaScriptThis will create a migrations
folder that handles database schema changes.
Define Database Models
With the groundwork in place, let’s define our database models using the SQLAlchemy declarative style:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def __repr__(self):
return '<User %r>' % self.username
JavaScriptThis creates a User
table with an primary key id
, a unique username
and email
.
We can create any models we need this way to structure our database tables.
Set up CRUD Routes and Views
Now for the meat of our application – routes and views to handle CRUD operations:
Import Statements
We will need a few extra imports:
from app import db
from models import User
JavaScriptAccepts GET and POST requests.
View
if request.method == 'POST':
username = request.form['username']
email = request.form['email']
new_user = User(username=username, email=email)
db.session.add(new_user)
db.session.commit()
return redirect(url_for('list_users'))
return render_template('createuser.html')
JavaScriptThis will get data from a form, create a new User
, save to the database, and redirect to the user list view.
We will skip over the frontend templates for brevity.
READ
To fetch and read users:
Route
@app.route('/users')
def list_users():
users = User.query.all()
return render_template('listusers.html', users=users)
JavaScriptQuery for all User
objects and pass to template.
View
Again we’ll skip the template, but it would loop through the users and display details.
We would also create routes, views, and templates to handle:
- View single user details
- Edit user (update)
- Delete user
Using similar patterns for interacting with the database.
UPDATE
To edit/update a existing user with new info:
Route
@app.route('/users/edit/<int:id>', methods=['GET', 'POST'])
def update_user(id):
JavaScriptAccepts GET and POST requests to same route, passing user id parameter.
View
user = User.query.get(id)
if request.method == 'POST':
user.username = request.form['username']
user.email = request.form['email']
db.session.commit()
return redirect(url_for('list_users'))
return render_template('updateuser.html', user=user)
JavaScriptGets existing user from id, updates fields from form data, saves to database and redirects.
Also passes user object to pre-fill the form being updated.
DELETE
Deleting a user:
Route
@app.route('/users/delete/<int:id>')
def delete_user(id):
JavaScriptTakes in user id to target for deletion.
View
user = User.query.get(id)
db.session.delete(user)
db.session.commit()
return redirect(url_for('list_users'))
JavaScriptFetches user, deletes from database, redirects back to user list view.
This covers the basics of performing CRUD using Flask and SQLAlchemy!
The last piece is connecting these backend routes, models, and databases to an actual frontend and templates for users to interact with.
Connect Frontend to Backend Logic
To build out a full CRUD application, you need:
- Templates – HTML files that display data and accept input
- Forms – WTForms that take in user input and data
- Routes – To handle requests and connect to DB logic
- Models – Database tables defined via SQLAlchemy
Here is a brief overview of how the frontend connects to the backend:
- User visits app in browser and clicks link to Create User
- Flask renders create user template with WTForm
- User fills out form fields and clicks Submit
- Request sent to create_user route
- Data passed to User model and added to DB
- Route redirects back to user list template
- Flask renders read template with all User data from DB
The same process flows through Update and Delete operations as well.
This is a simplified look at tying the whole CRUD app together.
There are many little details in developing full applications, but hopefully this gives you a primer on building core CRUD functionality with Flask and SQLAlchemy.
Summary
To recap building a CRUD app with Flask and SQLAlchemy:
- Set up Flask app and configure SQLAlchemy
- Define models and database tables
- Create routes and views for CRUD operations
- Handle requests and call database
- Interact with models to query or modify DB
- Connect backend to frontend templates and forms
Following these steps allows you to develop a simple yet complete CRUD application for managing database records.
There is a vast amount more you can do in expanding on this foundation with other Flask and SQLAlchemy features. But understanding the basics of tying these two tools together provides a hugely useful skillset for web development in Python.
Happy CRUDing with Flask!