"Mastering Flask & SQLAlchemy: A Comprehensive Example"

Mastering Flask-SQLAlchemy: A Comprehensive Example

Flask-SQLAlchemy is an extension for Flask that adds support for SQLAlchemy, a popular Object-Relational Mapping (ORM) library for Python. In this guide, we'll create a simple blog application using Flask-SQLAlchemy to demonstrate its key features and best practices.

Setting Up the Project and Environment

First, ensure you have Flask and Flask-SQLAlchemy installed. If not, install them using pip:

pip install flask flask_sqlalchemy

Create a new file app.py and import the required modules:

Python Flask Tutorial 5 - Database with Flask-SQLAlchemy
Python Flask Tutorial 5 - Database with Flask-SQLAlchemy

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

Configuring the Database

Configure the database URI and enable Flask-SQLAlchemy:

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db'
db = SQLAlchemy(app)

Defining the Database Model

Create a simple Blog model with title and content fields:

class Blog(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    content = db.Column(db.Text, nullable=False)

    def __repr__(self):
        return f''

Migrations with Flask-Migrate

To manage database migrations, install Flask-Migrate:

an orange and green vase sitting on top of a white surface
an orange and green vase sitting on top of a white surface

pip install flask_migrate

Initialize Flask-Migrate and create the initial migration:

migrate = Migrate(app, db)
db.init_app(app)

@app.shell_context_processor
def make_shell_context():
    return {'db': db, 'Blog': Blog}

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

Run the following commands to create and upgrade the database:

flask db init
flask db migrate -m "Initial migration."
flask db upgrade

Creating Routes for CRUD Operations

Implement routes for creating, reading, updating, and deleting blog posts.

Laboratory flask with graduation cap and autumn leaves, symbolizing pharmaceutical research and career growth Stock Illustration
Laboratory flask with graduation cap and autumn leaves, symbolizing pharmaceutical research and career growth Stock Illustration

Create Route

Add a new route for creating a new blog post:

@app.route('/new', methods=['GET', 'POST'])
def new():
    if request.method == 'POST':
        title = request.form['title']
        content = request.form['content']
        blog = Blog(title=title, content=content)
        db.session.add(blog)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('new.html')

Read Route

Create an index route to display all blog posts:

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

Update Route

Add a route for updating an existing blog post:

@app.route('//edit', methods=['GET', 'POST'])
def edit(blog_id):
    blog = Blog.query.get_or_404(blog_id)
    if request.method == 'POST':
        blog.title = request.form['title']
        blog.content = request.form['content']
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('edit.html', blog=blog)

Delete Route

Create a route for deleting a blog post:

@app.route('//delete')
def delete(blog_id):
    blog = Blog.query.get_or_404(blog_id)
    db.session.delete(blog)
    db.session.commit()
    return redirect(url_for('index'))

Creating Templates for Views

Create HTML templates for displaying and interacting with the blog posts in the templates folder.

Index Template

Create an index.html template to display all blog posts:

<h1>Blog</h1>
<ul>
  {% for blog in blogs %}
    <li>
      <h2>{{ blog.title }}</h2>
      <p>{{ blog.content }}</p>
      <a href="{{ url_for('edit', blog_id=blog.id) }}">Edit</a>
      <a href="{{ url_for('delete', blog_id=blog.id) }}">Delete</a>
    </li>
  {% endfor %}
</ul>
<a href="{{ url_for('new') }}">New Blog</a>

New and Edit Templates

Create new.html and edit.html templates for creating and updating blog posts, respectively.

Running the Application

Run the application using the following command:

flask run

Visit http://127.0.0.1:5000/ in your browser to see the blog application in action.

Conclusion

In this guide, we've created a simple blog application using Flask-SQLAlchemy to demonstrate its key features and best practices. By following this example, you can build more complex applications using Flask and SQLAlchemy.

an illustration of a flask with fire coming out of the burner on white background
an illustration of a flask with fire coming out of the burner on white background
a beakle with liquid and a glass container with a straw in it, next to a spoon
a beakle with liquid and a glass container with a straw in it, next to a spoon
an advertisement for alchemy with two flasks and beakles on a table
an advertisement for alchemy with two flasks and beakles on a table
;dldhx
;dldhx
chemistry
chemistry
GitHub - pallets/flask: The Python micro framework for building web applications.
GitHub - pallets/flask: The Python micro framework for building web applications.
a black and white image of a flask with liquid coming out of the top
a black and white image of a flask with liquid coming out of the top
an old paper with sun, moon and vase on it in the style of doodle
an old paper with sun, moon and vase on it in the style of doodle
a black and white drawing of a flask with bubbles on the bottom, in front of a dark background
a black and white drawing of a flask with bubbles on the bottom, in front of a dark background
Python REST APIs With Flask, Connexion, and SQLAlchemy – Part 1 – Real Python
Python REST APIs With Flask, Connexion, and SQLAlchemy – Part 1 – Real Python
two glass vases sitting next to each other on top of a stand with candles
two glass vases sitting next to each other on top of a stand with candles
a blue beakle filled with liquid on top of a white background
a blue beakle filled with liquid on top of a white background
Flask Clipart PNG Images, Pink Flask Illustration, Pink, Flask, Chemistry PNG Image For Free Download
Flask Clipart PNG Images, Pink Flask Illustration, Pink, Flask, Chemistry PNG Image For Free Download
a flask filled with blue liquid
a flask filled with blue liquid
a blue glass flask with bubbles in it
a blue glass flask with bubbles in it
a black and white line drawing of a flask with liquid in it's beak
a black and white line drawing of a flask with liquid in it's beak
a pink flask with hearts floating out of it and the words science is cool
a pink flask with hearts floating out of it and the words science is cool
Conical Flask PNG Picture, Conical Flask Containing Mixed Liquid, Experiment, Flask PNG Image For Free Download
Conical Flask PNG Picture, Conical Flask Containing Mixed Liquid, Experiment, Flask PNG Image For Free Download
Gambar Peralatan Eksperimen Kartun Kelalang Kon, Kartun, Peralatan Makmal, Kelalang Kon PNG dan PSD untuk Muat turun Percuma
Gambar Peralatan Eksperimen Kartun Kelalang Kon, Kartun, Peralatan Makmal, Kelalang Kon PNG dan PSD untuk Muat turun Percuma
a glass flask filled with water on top of a white background, hand drawn
a glass flask filled with water on top of a white background, hand drawn
three flasks filled with colored liquid, beakles, and liquids png and psd
three flasks filled with colored liquid, beakles, and liquids png and psd
a flask filled with purple liquid and bubbles
a flask filled with purple liquid and bubbles
Colourful Conical Flask Sticker
Colourful Conical Flask Sticker