Flask SQLAlchemy Tutorial for Database
0 812
Introduction to Flask-SQLAlchemy
Flask-SQLAlchemy is a popular extension that integrates SQLAlchemy with Flask applications. It simplifies database operations by providing an ORM (Object Relational Mapper) which allows you to interact with your database using Python classes and objects instead of raw SQL queries.
Installing Flask-SQLAlchemy
Before connecting your Flask app to a database, you need to install the Flask-SQLAlchemy package. You can do this using pip:
pip install Flask-SQLAlchemy
Setting Up Your Flask App with a Database
After installation, you can configure your Flask app to connect to a database by specifying the database URI in the app configuration. This URI tells SQLAlchemy which database to connect to and how.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' # Using SQLite for simplicity
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
Defining Models
With Flask-SQLAlchemy, you define your database structure by creating models. A model is a Python class that maps to a table in your database.
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 f'<User {self.username}>'
Creating the Database
After defining your models, you need to create the actual tables in the database. This can be done by running:
with app.app_context():
db.create_all()
This will create all tables based on your model definitions.
Adding and Querying Data
You can add new entries to your database by creating instances of your models and committing them using the session.
with app.app_context():
new_user = User(username='johndoe', email='john@example.com')
db.session.add(new_user)
db.session.commit()
user = User.query.filter_by(username='johndoe').first()
print(user.email) # Output: john@example.com
Summary
Flask-SQLAlchemy offers a seamless way to connect your Flask application to a database. By defining models as Python classes and using SQLAlchemy's ORM features, you can easily create, read, update, and delete database records with minimal effort.
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:



Comments
Waiting for your comments