rogulski.it

My name is Piotr, a passionate pythonista and this is my blog!

SSL connection setup using PostgreSQL and SQLAlchemy

Posted at — Oct 13, 2021
  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!