Skip to main content

Command Palette

Search for a command to run...

Activity 19: Research on Python SQLAlchemy

Updated
3 min read
Activity 19: Research on Python SQLAlchemy

SQLAlchemy is a powerful SQL toolkit and Object Relational Mapper (ORM) for Python, providing a comprehensive set of tools for interacting with databases. Here's an overview of the key concepts and features of SQLAlchemy:

1. Core Components

  • SQLAlchemy Core: This is the lower-level part of SQLAlchemy, focusing on building and executing raw SQL queries. It is ideal for complex database interactions where fine-grained control is needed.

  • SQLAlchemy ORM: The higher-level component that allows Python developers to interact with the database using Python classes. It provides an abstract way to manipulate database records using Python objects.

2. Basic Terminology

  • Engine: Connects SQLAlchemy with the database. It manages the connection pool and database dialect.

  • Session: A temporary workspace to interact with the database and handle transactions.

  • Model: A Python class that maps to a database table.

  • Mapper: Binds the Python class to the database table, facilitating ORM functionality.

  • 3. Key Features

    • ORM Functionality: SQLAlchemy can map Python classes to database tables, enabling developers to query and manipulate data using Python code instead of raw SQL.

    • Database-Agnostic: Works with a variety of databases, including SQLite, PostgreSQL, MySQL, Oracle, and more.

    • Query Flexibility: Allows both raw SQL and Pythonic query construction using the ORM syntax.

    • Schema Management: Provides tools for creating and altering database schemas.

Step 1. Check Your Environment

  1. Install Flask and Flask-SQLAlchemy: Make sure you have Flask and Flask-SQLAlchemy installed in your Python environment. You can install them using pip:

    Copy

      pip install Flask Flask-SQLAlchemy
    

Step 2: Basic Flask App with Flask-SQLAlchemy

Here's a simple example to get you started:

app.py

from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy

# Initialize the Flask app
app = Flask(__name__)

# Configure the SQLite database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# Initialize the database
db = SQLAlchemy(app)

# Define a model for the database
class Item(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), nullable=False)

    def __repr__(self):
        return f'<Item {self.name}>'

# Create database tables
with app.app_context():
    db.create_all()

@app.route('/')
def index():
    items = Item.query.all()
    return render_template('index.html', items=items)

@app.route('/add', methods=['POST'])
def add_item():
    item_name = request.form.get('name')
    if item_name:
        new_item = Item(name=item_name)
        db.session.add(new_item)
        db.session.commit()
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(debug=True)

Explanation:

  • app.py sets up a Flask web application with a simple SQLite database.

  • Item class is a model representing a table with id and name fields.

6. Check Flask Version

Finally, ensure that your Flask version is up-to-date and check the documentation for any recent changes. You can check your Flask version using:

Copy

  python -m flask --version

Running the Application:

  1. Save the files in a directory.

  2. Run the Flask app with:

     python app.py
    
  3. Go to http://127.0.0.1:5000 in your web browser to view and interact with the application.

This will get you started with a basic Flask app that supports adding and displaying items using a SQLAlchemy-powered database.

More from this blog

Joshua Nato's team blog

56 posts