You are currently viewing Build a production-ready user management microservice with Flask and SQLAlchemy: A Step-by-Step Guide

Build a production-ready user management microservice with Flask and SQLAlchemy: A Step-by-Step Guide

  • Post author:
  • Post category:Python

Part 1: Setting up the project

In this first part of the tutorial series, we’ll set up the foundation for our user management microservice. By the end of this tutorial, you’ll have a basic Flask application with SQLAlchemy configured, ready for adding features like user registration, authentication, and more.

What you’ll learn in Part 1

  • How to set up a Python project with Flask and SQLAlchemy.
  • How to structure your project for scalability.
  • How to configure a SQLite database for development.
  • How to run your Flask application locally.

Prerequisites

Before we begin, ensure you have the following installed:

  • Python 3.7+: Download and install Python from python.org.
  • pip: Python’s package manager (comes pre-installed with Python).
  • Basic knowledge of Python: Familiarity with Python syntax and concepts will be helpful.

Step 1: Create a project directory

Start by creating a directory for your project:

mkdir user-management-microservice
cd user-management-microservice

Step 2: Set up a virtual environment

A virtual environment isolates your project dependencies from the global Python installation. Create and activate a virtual environment:

On macOS/Linux:

python -m venv venv
source venv/bin/activate

On Windows:

python -m venv venv
venv\Scripts\activate

Once activated, your terminal prompt will show the virtual environment name (venv).

Step 3: Install required packages

Install the necessary Python packages using pip:

pip install Flask SQLAlchemy Flask-SQLAlchemy

Here’s what each package does:

  • Flask: A lightweight web framework for building APIs.
  • SQLAlchemy: An ORM (Object-Relational Mapping) tool for database interactions.
  • Flask-SQLAlchemy: Integrates SQLAlchemy with Flask.

Step 4: Create the project structure

Organize your project with the following structure:

user-management-microservice/
├── app/
│   ├── __init__.py
│   ├── models.py
│   ├── routes.py
├── config.py
├── run.py
├── requirements.txt

File descriptions

  1. app/__init__.py: Initializes the Flask app and SQLAlchemy.
  2. app/models.py: Defines the database models (e.g., User).
  3. app/routes.py: Contains the API routes (e.g., /api/users).
  4. config.py: Stores configuration settings (e.g., database URL).
  5. run.py: Entry point to run the application.
  6. requirements.txt: Lists the project dependencies.

Step 5: Write the configuration file

Create a config.py file to store your application’s configuration:

import os

class Config:
    SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL', 'sqlite:///app.db')  # Use SQLite by default
    SQLALCHEMY_TRACK_MODIFICATIONS = False  # Disable modification tracking

This code defines a Config class that manages database settings for a Flask application. It imports the os module to access environment variables and sets SQLALCHEMY_DATABASE_URI to the value of the DATABASE_URL environment variable, defaulting to an SQLite database file (app.db) if the variable is not set. Additionally, it disables SQLAlchemy’s modification tracking by setting SQLALCHEMY_TRACK_MODIFICATIONS to False, which improves performance by reducing unnecessary overhead.

Step 6: Add a basic route

In app/routes.py, add the following code:

from flask import Blueprint, jsonify

bp = Blueprint('api', __name__, url_prefix='/api')

@bp.route('/test', methods=['GET'])
def test():
    return jsonify({"message": "Welcome to the user management microservice"})

This code creates an API blueprint for a Flask application and defines a test route. It imports Blueprint and jsonify from Flask, then initializes a blueprint named api with a URL prefix of /api. The test function handles GET requests at /api/test and returns a JSON response containing a welcome message.

Step 7: Initialize the Flask application

In app/__init__.py, initialize the Flask app and SQLAlchemy:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import Config

db = SQLAlchemy()

def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)

    db.init_app(app)

    with app.app_context():
        from . import routes
        app.register_blueprint(routes.bp)

        db.create_all()

    return app

This code sets up a Flask application with SQLAlchemy for database management. It imports the necessary modules and initializes an SQLAlchemy instance (db). The create_app function creates a Flask app, loads configuration settings from the Config class, and initializes the database with the app. Inside the application context, it imports routes from the current package, registers them as a blueprint, and creates any missing database tables. Finally, the function returns the configured Flask application.

Step 8: Define the database model

In app/models.py, define the User model:

from . import db

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)
    password_hash = db.Column(db.String(128), nullable=False)

    def __repr__(self):
        return f'<User {self.username}>'

This code defines a User model for a Flask application using SQLAlchemy. It imports the database instance (db) and creates the User class, which inherits from db.Model. The class defines four columns: id as the primary key, username as a unique and required string of up to 80 characters, email as a unique and required string of up to 120 characters, and password_hash as a required string of up to 128 characters. The __repr__ method returns a string representation of the user, displaying the username.

Step 9: Create the entry point

In run.py, create the entry point to run the application:

from app import create_app

app = create_app()

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

This code initializes and runs a Flask application. It imports the create_app function from the app module and calls it to create an instance of the Flask application. If the script runs directly (not imported as a module), it starts the Flask development server with debugging enabled.

Step 10: Run the application

Start the application by running:

python run.py

You should see output similar to:

* Running on http://127.0.0.1:5000

You now have a solid foundation for building a production-ready microservice. In the next part, we’ll dive into implementing user management features.

Full Code for Part 1

You can find the complete code for this tutorial in the GitHub repository.

What’s next?

In Part 2, we’ll implement user registration and add endpoints for creating, fetching, updating, and deleting users. Stay tuned!

 

Facebook Comments