Flask-SQLAlchemy Setup 🚀

beginner
16 min

Flask-SQLAlchemy Setup 🚀

Welcome to our Flask-SQLAlchemy Setup tutorial! In this comprehensive guide, we'll walk you through the process of setting up a web application using Flask, a micro-web framework for Python, and SQLAlchemy, a powerful SQL toolkit and Object-Relational Mapping (ORM) system. By the end of this tutorial, you'll have a solid understanding of how to create a database-driven Flask app. 💡 Pro Tip: This tutorial is suitable for both beginners and intermediates.

What is Flask? 🎯

Flask is a lightweight web framework for Python that allows you to create web applications quickly and easily. It's a great choice for small to medium-sized projects and is perfect for learning the basics of web development.

What is SQLAlchemy? 🎯

SQLAlchemy is a SQL toolkit and Object-Relational Mapping (ORM) system for Python. It provides a high-level, database-agnostic API for interacting with databases, making it easy to create, read, update, and delete data.

Setting Up the Environment 📝

Before we dive into the Flask-SQLAlchemy setup, let's make sure you have the necessary tools installed:

  1. Python: You can download the latest version from Python.org.

  2. pip: Python's package manager, which comes bundled with Python.

  3. virtualenv: A tool to create isolated Python environments. You can install it using pip:

    pip install virtualenv

Creating a New Project 📝

Let's create a new Flask project called my_flask_app.

bash
mkdir my_flask_app cd my_flask_app virtualenv venv source venv/bin/activate pip install flask flask_sqlalchemy

Now, let's create our first Flask app. Create a new file called app.py and add the following code:

python
from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return 'Hello, World!' if __name__ == '__main__': app.run(debug=True)

You can run the app by executing python app.py. Visit http://localhost:5000 in your web browser to see the output. ✅

Setting Up SQLAlchemy 📝

Now, let's set up SQLAlchemy and create a simple database model. Update your app.py to include the following code:

python
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) 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) if __name__ == '__main__': db.create_all() app.run(debug=True)

In this code, we've set up SQLAlchemy and created a simple User model with three columns: id, username, and email. We've also told SQLAlchemy to create the table when the app starts.

Querying the Database 📝

Now let's add a route to create, read, update, and delete data from the database. Update your app.py to include the following code:

python
# ... previous code ... @app.route('/add_user', methods=['POST']) def add_user(): user = User(username='new_user', email='new_user@example.com') db.session.add(user) db.session.commit() return 'User added!' @app.route('/users') def list_users(): users = User.query.all() return str(users) # ... previous code ...

With these additions, our app now has two routes:

  1. /add_user: Adds a new user to the database.
  2. /users: Retrieves and displays all users from the database.
Quick Quiz
Question 1 of 1

Which Flask route adds a new user to the database?

Quick Quiz
Question 1 of 1

Which Flask route retrieves and displays all users from the database?

Conclusion 📝

You now have a basic understanding of how to set up a Flask-SQLAlchemy application and interact with a database. In future tutorials, we'll dive deeper into Flask, SQLAlchemy, and database interactions. Keep learning, and happy coding! 🎯