zaheer140 commited on
Commit
9c5bb5d
·
verified ·
1 Parent(s): 77af8a3

Update database/db_utils.py

Browse files
Files changed (1) hide show
  1. database/db_utils.py +10 -9
database/db_utils.py CHANGED
@@ -4,23 +4,24 @@ from psycopg2.extras import RealDictCursor
4
  import logging
5
  from dotenv import load_dotenv
6
 
7
- # Load environment variables from .env file
 
8
  load_dotenv()
9
 
10
  logger = logging.getLogger(__name__)
11
 
 
12
  POSTGRES_URI = os.getenv("POSTGRES_URI", "")
13
 
14
  def get_db_connection():
15
  """
16
- Establishes a connection to the PostgreSQL database using the URI from environment variables.
17
- Returns:
18
- psycopg2.connection or None: Reusable DB connection object.
19
  """
20
  if not POSTGRES_URI:
21
- logger.error("POSTGRES_URI is not set in the environment variables.")
22
  return None
23
  try:
 
24
  conn = psycopg2.connect(POSTGRES_URI, cursor_factory=RealDictCursor)
25
  return conn
26
  except Exception as e:
@@ -34,16 +35,16 @@ def execute_query(query, params=None):
34
  conn = get_db_connection()
35
  if not conn:
36
  return []
37
-
38
  try:
39
  with conn.cursor() as cur:
40
  cur.execute(query, params)
41
- if cur.description: # If it's a SELECT query
42
  return cur.fetchall()
43
- conn.commit()
44
  return []
45
  except Exception as e:
46
  logger.error(f"Query execution failed: {e}")
47
  return []
48
  finally:
49
- conn.close()
 
4
  import logging
5
  from dotenv import load_dotenv
6
 
7
+ # Local development ke liye load_dotenv() rahega
8
+ # Hugging Face par ye automatically Secrets se environment variable utha lega
9
  load_dotenv()
10
 
11
  logger = logging.getLogger(__name__)
12
 
13
+ # Hugging Face Settings -> Secrets mein 'POSTGRES_URI' naam se link save karein
14
  POSTGRES_URI = os.getenv("POSTGRES_URI", "")
15
 
16
  def get_db_connection():
17
  """
18
+ Establishes a connection to the PostgreSQL database using the URI.
 
 
19
  """
20
  if not POSTGRES_URI:
21
+ logger.error("POSTGRES_URI is not set. Please add it to Hugging Face Secrets.")
22
  return None
23
  try:
24
+ # Hugging Face se connection ke liye kabhi kabhi sslmode='require' zaroori hota hai
25
  conn = psycopg2.connect(POSTGRES_URI, cursor_factory=RealDictCursor)
26
  return conn
27
  except Exception as e:
 
35
  conn = get_db_connection()
36
  if not conn:
37
  return []
38
+
39
  try:
40
  with conn.cursor() as cur:
41
  cur.execute(query, params)
42
+ if cur.description: # SELECT query ke liye
43
  return cur.fetchall()
44
+ conn.commit() # INSERT/UPDATE ke liye
45
  return []
46
  except Exception as e:
47
  logger.error(f"Query execution failed: {e}")
48
  return []
49
  finally:
50
+ conn.close()