DEV Community

Marco Upia
Marco Upia

Posted on

Starting with Flask and SQLAlchemy: A Beginner's Guide

Are you just getting started with Python and interested in creating web projects? Well, have I got the perfect solution for you! Let me introduce you to Flask and SQLAlchemy - a dynamic duo that makes web development in Python super easy, even for beginners like you!

Flask: The Friendly Web Framework
Flask is a web application development framework that simplifies the process of creating web applications, much like a good friend who always has your back. It's a lightweight and easy-to-understand framework that follows the "micro-framework" principle. This means that it provides you with only the necessary tools to get started without overwhelming you with unnecessary features.

Setting Up Your Flask App
To create a Flask app, you need to install Flask first. To do this, open your terminal and type:

pip install Flask
Enter fullscreen mode Exit fullscreen mode

Now, let's build a simple "Hello, Flask!" app:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_flask():
    return 'Hello, Flask!'
Enter fullscreen mode Exit fullscreen mode

Here, we've created a minimal Flask app. The @app.route('/') decorator tells Flask that when someone visits the root URL ('/'), it should execute the hello_flask function, which simply returns 'Hello, Flask!'.

Run your app with:

python your_app_name.py
Enter fullscreen mode Exit fullscreen mode

Open your browser and navigate to http://localhost:5000. Congratulations! You have just created your first Flask app.

SQLAlchemy: The Pythonic Database Toolkit
Let's discuss SQLAlchemy. If Flask is the buddy who assists you in constructing the framework, then SQLAlchemy is the expert who handles your database. It streamlines database interactions and provides a Pythonic interface, making it feel like you're working with Python, not intricate SQL queries.

Setting Up Your Database
First, install SQLAlchemy:

pip install Flask-SQLAlchemy
Enter fullscreen mode Exit fullscreen mode

Now, let's integrate SQLAlchemy into our Flask app. We'll use an SQLite database for starter:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'  # Using SQLite database
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)

# Run this in your terminal to create the database
# python
# >>> from your_app_name import db
# >>> db.create_all()
Enter fullscreen mode Exit fullscreen mode

In this example, we've created a simple User model with an id and a username. SQLAlchemy helps us define our database structure using Python classes.

Connecting Flask and SQLAlchemy
Now, let's update our Flask app to use SQLAlchemy:

from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy

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

@app.route('/')
def home():
    users = User.query.all()
    return render_template('home.html', users=users)

if __name__ == '__main__':
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

This Flask app uses SQLAlchemy to query all users from the database and passes them to a template (we'll create a simple 'home.html' file). The render_template function allows us to display dynamic content in our HTML.

Conclusion
Great job! You've taken your first steps into the world of Flask and SQLAlchemy. As you continue to explore, you'll discover the true potential of these tools in building dynamic and scalable web applications. Keep in mind that the best way to learn is by doing, so don't hesitate to experiment and work on your own projects.

Top comments (0)