Using Flask‑SQLAlchemy for Database Operations in Python Web Development
This tutorial explains how to install Flask‑SQLAlchemy, configure a Flask app to connect to MySQL, define ORM models, perform queries, handle pagination, update records, and execute join queries, providing code examples and best‑practice tips for backend development.
Background: In web development, databases are essential and SQLAlchemy is the most popular ORM for Python; Flask‑SQLAlchemy simplifies its integration with Flask.
Installation: Use pip install flask-sqlalchemy to add the package.
Configuration: Add database URI and other settings in the Flask app, e.g., app.config['SQLALCHEMY_DATABASE_URI']='mysql+pymysql://user:pwd@host:port/flask_test?charset=utf8&autocommit=true' and app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True , then initialize with db = SQLAlchemy(app) . More options are listed at the official config page.
Model definition: Each table corresponds to a class inheriting from db.Model ; define columns with Column types and optionally a __repr__ method.
Data retrieval: Query the database directly and render results in HTML templates; pagination can be handled on the front‑end with DataTables or on the back‑end using limit and offset methods.
Updating data: After editing or creating records, commit changes with db.session.commit() . An example shows using an id check to distinguish insert versus update.
Join queries: Flask‑SQLAlchemy supports joins via the join method; an example demonstrates joining three tables to select specific fields: news = db.session.query(Table1.param1, Table1.params2).join(Table2, Table2.params1==Table1.params1).join(Table3, Table3.params1==Table1.params1).first() .
The tutorial ends with a note that more Flask features will be shared later.
360 Quality & Efficiency
360 Quality & Efficiency focuses on seamlessly integrating quality and efficiency in R&D, sharing 360’s internal best practices with industry peers to foster collaboration among Chinese enterprises and drive greater efficiency value.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.