Do not store secrets in plaintext in code


Python Clean Code Tip:

Avoid storing things like secret keys, passwords, connection strings, and API keys inside your code. Instead, use a secrets management solution like AWS Secrets Manager or Vault.

# bad


class ProductionConfig:
    DEBUG = False
    TESTING = False
    APP_ENVIRONMENT = "production"
    SQLALCHEMY_DATABASE_URI = (
        "postgresql://my_user:strong_password@my_server:5432/my_db"
    )


# better

import boto3


class ProductionConfig:
    DEBUG = False
    TESTING = False
    APP_ENVIRONMENT = "production"
    _SQLALCHEMY_DATABASE_URI = None

    @property
    def SQLALCHEMY_DATABASE_URI(self):
        if self._SQLALCHEMY_DATABASE_URI is None:
            self._SQLALCHEMY_DATABASE_URI = boto3.client(
                "secretsmanager"
            ).get_secret_value(SecretId=f"db-connection-string-{self.APP_ENVIRONMENT}")[
                "SecretString"
            ]

        return self._SQLALCHEMY_DATABASE_URI

If a secrets management tool is overkill for your project, store secrets in environment variables. Never store them in plaintext in your code.