DEV Community

Hassan Shahzad
Hassan Shahzad

Posted on

A Step-by-Step Guide to Publishing a Python Package for Secure Microservice Database Migration with Alembic

If you’re building microservices, managing databases can quickly become a nightmare. Each microservice often has its own database, and keeping schemas in sync across multiple environments can lead to downtime, errors, and security risks.

That’s why I created a Python database migration tool packaged with Alembic and setuptools. It not only automates schema changes but also adds an extra layer of security with encrypted database connections and token-based authentication.

In this guide, I’ll walk you through how to publish your own secure Python migration package for microservices on GitHub.

Why Database Migration Matters in Microservices

When each service controls its own schema, you need a reliable database migration tool for microservices. Without it, you risk:

  • Schema mismatches between environments
  • Costly production errors
  • Time wasted on manual SQL scripts

By using Alembic, we can ensure migrations are automated, version-controlled, and repeatable across services.

Step 1: Set Up the Project

Start by creating your project folder:

mkdir microservice-db-migrator
cd microservice-db-migrator
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
Enter fullscreen mode Exit fullscreen mode

Basic structure:

microservice-db-migrator/
│── alembic/         # Alembic environment
│── migrations/      # Generated migration scripts
│── migrator/        # Your custom Python package
│   └── __init__.py
│── setup.py
│── README.md
Enter fullscreen mode Exit fullscreen mode

This follows best practices for a Python setuptools packaging tutorial.

Step 2: Install Alembic and Dependencies

pip install alembic sqlalchemy cryptography
Enter fullscreen mode Exit fullscreen mode

Initialize Alembic:

alembic init alembic
Enter fullscreen mode Exit fullscreen mode

Now you have the base configuration for schema migrations.

Step 3: Secure Database Connection (Encryption + Tokens)

Hardcoding credentials is risky. Instead, we’ll create a secure database connection in Python with token-based decryption.

In migrator/db_connection.py:

from cryptography.fernet import Fernet

class SecureDBConnector:
    def __init__(self, token: str):
        self.token = token
        self.key = Fernet(token)

    def decrypt_connection(self, encrypted_url: str) -> str:
        return self.key.decrypt(encrypted_url.encode()).decode()
Enter fullscreen mode Exit fullscreen mode

Only services with a valid token can access the actual database URL — perfect for secure Python migrations.

Step 4: Configure setup.py with setuptools

To make the tool reusable, package it with setuptools.

from setuptools import setup, find_packages

setup(
    name="microservice-db-migrator",
    version="0.1.0",
    packages=find_packages(),
    install_requires=[
        "alembic",
        "sqlalchemy",
        "cryptography",
    ],
    entry_points={
        "console_scripts": [
            "db-migrate=migrator.cli:main",
        ],
    },
)
Enter fullscreen mode Exit fullscreen mode

This creates a command-line tool db-migrate that integrates with Alembic migrations.

Step 5: Build a Simple CLI for Migrations

In migrator/cli.py:

import subprocess
from migrator.db_connection import SecureDBConnector

def main():
    token = input("Enter your token: ")
    encrypted_url = "ENCRYPTED_DB_URL"

    connector = SecureDBConnector(token)
    db_url = connector.decrypt_connection(encrypted_url)

    subprocess.run(["alembic", "upgrade", "head"])
Enter fullscreen mode Exit fullscreen mode

This ensures database migrations in microservices are simple, secure, and token-protected.

Step 6: Publish to GitHub

Push your code to GitHub, tag a release, and now others can install your migration package:

pip install git+https://github.com/yourusername/microservice-db-migrator.git
Enter fullscreen mode Exit fullscreen mode

This makes your Python database migration package reusable across all your services.

Why This Approach Works

By combining Alembic migrations, setuptools packaging, and encrypted database credentials, this tool provides:

  • Security – No plain-text credentials in configs
  • Automation – Alembic tracks schema versions
  • Reusability – One package for all microservices
  • Scalability – Easy to extend for future services

Conclusion

Publishing this package taught me a lot about Python packaging with setuptools, secure database connections in microservices, and how to leverage Alembic for migrations.

If you want a reliable, Python database migration guide, this approach ensures your services remain secure, consistent, and production-ready.

Top comments (0)