Spaces:
Running
Running
Create database.py
Browse files- database.py +47 -0
database.py
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import psycopg2
|
2 |
+
from decouple import config
|
3 |
+
from urllib.parse import urlparse
|
4 |
+
import re
|
5 |
+
import sys
|
6 |
+
import shutil
|
7 |
+
import threading
|
8 |
+
import time
|
9 |
+
import os
|
10 |
+
import time
|
11 |
+
from datetime import datetime, timedelta, datetime
|
12 |
+
from colorama import Fore, Style, Back, init
|
13 |
+
init(autoreset=True)
|
14 |
+
|
15 |
+
def db_connection():
|
16 |
+
"""Establishes a connection to the database with SSL and keepalives."""
|
17 |
+
# Parse DATABASE_URL
|
18 |
+
url = urlparse(config("DATABASE_URL"))
|
19 |
+
|
20 |
+
# Extract connection details from the DATABASE_URL
|
21 |
+
host = url.hostname
|
22 |
+
port = url.port
|
23 |
+
user = url.username
|
24 |
+
password = url.password
|
25 |
+
database = url.path[1:]
|
26 |
+
|
27 |
+
try:
|
28 |
+
# Connect using individual parameters
|
29 |
+
conn = psycopg2.connect(
|
30 |
+
host=host,
|
31 |
+
port=port,
|
32 |
+
user=user,
|
33 |
+
password=password,
|
34 |
+
dbname=database,
|
35 |
+
sslmode="require", # Use SSL
|
36 |
+
keepalives=1, # Enable keepalives
|
37 |
+
keepalives_idle=300, # Set idle time before keepalives (in seconds)
|
38 |
+
keepalives_interval=60, # Interval for keepalives (in seconds)
|
39 |
+
keepalives_count=5 # Number of keepalive retries before disconnecting
|
40 |
+
)
|
41 |
+
|
42 |
+
return conn
|
43 |
+
except psycopg2.OperationalError as db_error:
|
44 |
+
return
|
45 |
+
except Exception as e:
|
46 |
+
print(f"Database connection error: {e}"), 500
|
47 |
+
return conn
|