rairo commited on
Commit
7d1d875
·
verified ·
1 Parent(s): cb606cf

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +21 -9
main.py CHANGED
@@ -57,13 +57,14 @@ CORS(app)
57
  _CONN = None
58
 
59
  def _connect():
60
- """(Re)connect to TiDB with TLS + autocommit; DictCursor for JSON friendliness."""
61
  global _CONN
62
  try:
63
  if _CONN:
64
  _CONN.close()
65
  except Exception:
66
  pass
 
67
  _CONN = pymysql.connect(
68
  host=TIDB_HOST,
69
  port=TIDB_PORT,
@@ -73,21 +74,32 @@ def _connect():
73
  ssl={"ca": certifi.where()},
74
  ssl_verify_cert=True,
75
  ssl_verify_identity=True,
76
- autocommit=True, # ensure object rows are durable before child rows (FKs)
77
  charset="utf8mb4",
78
  cursorclass=pymysql.cursors.DictCursor,
 
 
 
 
79
  )
80
 
81
  def _ensure_conn():
82
  global _CONN
83
- if _CONN is None:
84
- _connect()
85
- else:
86
  try:
87
- _CONN.ping(reconnect=True)
88
- except Exception:
89
- _connect()
90
- return _CONN
 
 
 
 
 
 
 
 
91
 
92
  @contextmanager
93
  def cursor():
 
57
  _CONN = None
58
 
59
  def _connect():
60
+ """Enhanced connection with better error handling"""
61
  global _CONN
62
  try:
63
  if _CONN:
64
  _CONN.close()
65
  except Exception:
66
  pass
67
+
68
  _CONN = pymysql.connect(
69
  host=TIDB_HOST,
70
  port=TIDB_PORT,
 
74
  ssl={"ca": certifi.where()},
75
  ssl_verify_cert=True,
76
  ssl_verify_identity=True,
77
+ autocommit=True,
78
  charset="utf8mb4",
79
  cursorclass=pymysql.cursors.DictCursor,
80
+ # Add these timeouts:
81
+ connect_timeout=10,
82
+ read_timeout=30,
83
+ write_timeout=30,
84
  )
85
 
86
  def _ensure_conn():
87
  global _CONN
88
+ max_retries = 3
89
+ for attempt in range(max_retries):
 
90
  try:
91
+ if _CONN is None:
92
+ _connect()
93
+ else:
94
+ _CONN.ping(reconnect=False) # Test without auto-reconnect first
95
+ return _CONN
96
+ except Exception as e:
97
+ log.warning(f"Connection attempt {attempt + 1} failed: {e}")
98
+ _CONN = None
99
+ if attempt < max_retries - 1:
100
+ time.sleep(0.5 * (attempt + 1)) # Backoff
101
+ else:
102
+ raise
103
 
104
  @contextmanager
105
  def cursor():