|
| 1 | +import os |
| 2 | +import json |
| 3 | +import boto3 |
| 4 | + |
| 5 | +from sqlalchemy import create_engine |
| 6 | +from sqlalchemy.orm import sessionmaker |
| 7 | +from sqlalchemy.sql import text |
| 8 | + |
| 9 | +from botocore.exceptions import ClientError |
| 10 | + |
| 11 | + |
| 12 | +class Config: |
| 13 | + def __init__(self): |
| 14 | + self.secrets_manager = boto3.client('secretsmanager') |
| 15 | + |
| 16 | + def get_secret_from_aws(self, secret_name): |
| 17 | + try: |
| 18 | + response = self.secrets_manager.get_secret_value(SecretId=secret_name) |
| 19 | + if 'SecretString' in response: |
| 20 | + return json.loads(response['SecretString']) |
| 21 | + return None |
| 22 | + except (ClientError,): |
| 23 | + return None |
| 24 | + |
| 25 | + def get_config_value(self, key, default_value, secret_name=None): |
| 26 | + if secret_name: |
| 27 | + aws_secret = self.get_secret_from_aws(secret_name) |
| 28 | + if aws_secret and key in aws_secret: |
| 29 | + return aws_secret |
| 30 | + if key in os.environ: |
| 31 | + return os.environ[key] |
| 32 | + return default_value |
| 33 | + |
| 34 | + def get_db_config(self): |
| 35 | + return { |
| 36 | + "name": self.get_config_value("DB_NAME", "postgres", "python_interview_dbname"), |
| 37 | + "user": self.get_config_value("DB_USER", "postgres", "python_interview_user"), |
| 38 | + "password": self.get_config_value("DB_PASSWORD", "password", "python_interview_password"), |
| 39 | + "host": self.get_config_value("DB_HOST", "localhost", "python_interview_host"), |
| 40 | + "port": self.get_config_value("DB_PORT", "5432", "python_interview_port") |
| 41 | + } |
| 42 | + |
| 43 | + def get_conn_string(self): |
| 44 | + db_config = self.get_db_config() |
| 45 | + return "postgresql://{user}:{password}@{host}:{port}/{name}".format( |
| 46 | + name=db_config['name'], |
| 47 | + user=db_config['user'], |
| 48 | + password=db_config['password'], |
| 49 | + host=db_config['host'], |
| 50 | + port=db_config['port'] |
| 51 | + ) |
| 52 | + |
| 53 | + |
| 54 | +class DatabaseConnection: |
| 55 | + def __init__(self, conn_string): |
| 56 | + self.engine = create_engine(conn_string) |
| 57 | + self.session = sessionmaker(bind=self.engine) |
| 58 | + |
| 59 | + def get_session(self): |
| 60 | + new_session = self.session() |
| 61 | + return new_session |
| 62 | + |
| 63 | + |
| 64 | +def dedupe_data(session, table_name): |
| 65 | + records = session.execute(text(f"SELECT * FROM {table_name}")).fetchall() |
| 66 | + |
| 67 | + duplicates = [] |
| 68 | + outliers = [] |
| 69 | + for record in records: |
| 70 | + print(record) |
| 71 | + # Insert your anomaly detection logic here |
| 72 | + |
| 73 | + |
| 74 | +if __name__ == "__main__": |
| 75 | + config = Config() |
| 76 | + conn_string = config.get_conn_string() |
| 77 | + db = DatabaseConnection(conn_string) |
| 78 | + session = db.get_session() |
| 79 | + |
| 80 | + dedupe_data(session, "crypto_transactions") |
0 commit comments