This repository was archived by the owner on Apr 23, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup_database.py
More file actions
129 lines (112 loc) · 4.05 KB
/
setup_database.py
File metadata and controls
129 lines (112 loc) · 4.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import configparser
import hashlib
import logging
import os
from typing import Dict, Union, NoReturn
import argparse
import psycopg2
from dotenv import load_dotenv
class Configuration:
CONFIG: configparser.ConfigParser = None
CONFIGURATION_FILE = "config.ini"
@staticmethod
def set_up():
if Configuration.CONFIG is None:
Configuration.__instantiate__()
return Configuration.CONFIG
@staticmethod
def __instantiate__():
Configuration.CONFIG = configparser.ConfigParser()
Configuration.CONFIG.read(Configuration.CONFIGURATION_FILE)
@staticmethod
def get(option: str, section: str = 'DATABASE') -> Union[str, None]:
Configuration.set_up()
return Configuration.CONFIG.get(section=section, option=option, vars=os.environ)
def get_config_for_db() -> Union[Dict[str, str], None]:
dbname = Configuration.get('DB_NAME')
user = Configuration.get('DB_USER')
password = Configuration.get('DB_PASS')
host = Configuration.get('DB_HOST')
port = Configuration.get('DB_PORT')
if all([dbname, user, password, host, port]):
return {
'dbname': dbname,
'user': user,
'password': password,
'host': host,
'port': port
}
return None
def create_db(config: Dict[str, str]):
logging.debug("Connecting to the postgresql db 🐘")
try:
return psycopg2.connect(**config)
except Exception as e:
logging.error(f"Error al conectar a la base de datos: {e}")
return None
def create_tables(conn):
cursor = conn.cursor()
logging.debug("Creating refugios table.... 🕝")
create_refugios_table_query = """
CREATE TABLE IF NOT EXISTS refugios (
id_refugio VARCHAR(255) PRIMARY KEY,
password_hash VARCHAR(255) NOT NULL,
last_activity TIMESTAMP
);
"""
cursor.execute(create_refugios_table_query)
logging.debug("Creating events table.... 🕝")
create_eventos_table_query = """
CREATE TABLE IF NOT EXISTS eventos (
id SERIAL PRIMARY KEY,
timestamp TIMESTAMP NOT NULL,
id_refugio VARCHAR(255) NOT NULL,
FOREIGN KEY (id_refugio) REFERENCES refugios(id_refugio)
);
"""
cursor.execute(create_eventos_table_query)
logging.debug("Writting changes to the database... ✍")
conn.commit()
cursor.close()
logging.info("Database configuration done! 🚀")
def get_db_config() -> Union[Dict[str, str], NoReturn]:
config: Union[Dict[str, str], None] = get_config_for_db()
if config is None:
logging.info("Database configuration failing 🔴, exiting.. ")
exit(-1)
return config
def get_db(config: Dict[str, str]) -> Union[any, NoReturn]:
db = create_db(config=config)
if db is None:
logging.info("Database connection failing 🔴, exiting.. ")
exit(-1)
return db
def load_environment_vars_if_debug_mode():
parser = argparse.ArgumentParser(description='Database configuration')
parser.add_argument('--debug', action='store_true', default=False, help='Debug mode')
args = parser.parse_args()
if args.debug:
load_dotenv()
def populate_db(db):
cursor = db.cursor()
logging.debug("Adding refuges....🏠")
refuge_id = Configuration.get(option='REFUGE_ID', section='POPULATE_DB')
password = Configuration.get(option='REFUGE_PASSWORD', section='POPULATE_DB')
password_hashed = hashlib.sha256(password.encode()).hexdigest()
# Comprueba si el id_refugio ya existe
cursor.execute("SELECT id_refugio FROM refugios WHERE id_refugio = %s", (refuge_id,))
if cursor.fetchone():
print(f"Refugio con id {refuge_id} ya existe, no se insertará.")
else:
cursor.execute("INSERT INTO refugios (id_refugio, password_hash) VALUES (%s, %s)", (refuge_id, password_hashed))
db.commit()
cursor.close()
def main():
load_environment_vars_if_debug_mode()
config = get_db_config()
db = get_db(config=config)
create_tables(db)
populate_db(db)
db.close()
if __name__ == '__main__':
main()