File size: 2,577 Bytes
325b400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from sqlalchemy import create_engine, URL, text
from sqlalchemy.orm import sessionmaker, DeclarativeBase
from sqlalchemy.exc import OperationalError
from dotenv import load_dotenv
import os
load_dotenv()
import os, sys
import os
from dotenv import load_dotenv

# Load biến môi trường từ file .env

current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.abspath(os.path.join(current_dir, '..', '..')) 
from dotenv import load_dotenv, find_dotenv

# Tự động tìm file .env gần nhất trong cây thư mục cha
load_dotenv(find_dotenv(), override=True)

MYSQL_USER_NAME = os.getenv('DB_USER')
MYSQL_PASSWORD = os.getenv('DB_PASSWORD')
MYSQL_PORT = os.getenv('DB_PORT')
MYSQL_DATABASE = os.getenv('DB_NAME')
MYSQL_HOST = os.getenv('DB_HOST')
MYSQL_PORT = int(MYSQL_PORT) if MYSQL_PORT else 3306 

import os
from urllib.parse import quote

password = os.getenv("DB_PASSWORD") 
DB_PASSWORD = quote(password)

Base = DeclarativeBase()

# def get_db_engine():
#     """ Tạo kết nối đến MySQL """
#     dsn = URL.create(
#         drivername="mysql+pymysql",
#         username=MYSQL_USER_NAME,
#         # password=MYSQL_PASSWORD,
#         host=MYSQL_HOST,
#         port=MYSQL_PORT,
#         database=MYSQL_DATABASE
#     )
#     return create_engine(dsn)

# Connect server MYSQL
def get_db_engine():
    dsn = URL.create(
        drivername="mysql+pymysql",
        username=MYSQL_USER_NAME,
        password=MYSQL_PASSWORD,
        host=MYSQL_HOST,
        port=MYSQL_PORT,
        database=MYSQL_DATABASE
    )
    connect_args = {
            "ssl_verify_cert": True,
            "ssl_verify_identity": True,
            "ssl_ca": 'ca.pem',
        }
    return create_engine(
        dsn,
        connect_args=connect_args,
    )


# echo=True để debug SQL logs

# # Khởi tạo engine
# engine = get_db_engine()

# # Tạo session factory
# SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# def test_connection():
#     """ Kiểm tra kết nối MySQL """
#     try:
#         with engine.connect() as connection:
#             result = connection.execute(text("SELECT 1"))  # Dùng text() để tránh lỗi ObjectNotExecutableError
#             print("✅ Kết nối MySQL thành công!", result.scalar())  # result.scalar() lấy giá trị đầu tiên
#     except OperationalError as e:
#         print("❌ Kết nối MySQL thất bại!", str(e))

# # Chạy test kết nối
# test_connection()