← All writing

Configure PostgreSQL SSL with SQLAlchemy and AWS RDS

Configure an SSL connection to PostgreSQL with SQLAlchemy, including AWS RDS certificates, a Python SSL context, and async engine connection settings.

  1. Add ssl=true to your DATABASE_URL

  2. Download certificate that is required for secure connection with RDS e.g. AWS docs

  3. Add required arguments while creating a session

    import ssl
    
    from sqlalchemy.ext.asyncio import (
        AsyncSession, 
        create_async_engine
    )
    from sqlalchemy.orm import sessionmaker
    
    RDS_CERT_PATH = "path/to/your/cert/file"
    DATABASE_URL = "postgresql://x:y@z:5432/psql?ssl=true"
    
    ssl_context = ssl.create_default_context(cafile=RDS_CERT_PATH)
    ssl_context.verify_mode = ssl.CERT_REQUIRED
    
    connect_args = {"ssl": ssl_context}
    
    engine = create_async_engine(
       DATABASE_URL,
       connect_args=connect_args,
    )
    async_session = sessionmaker(
        engine, 
        class_=AsyncSession 
    )
  4. This setup should make the work done, enjoy!

← More writing