LapStore commited on
Commit
a78f512
·
1 Parent(s): 85c15a5

diving into adding connection to database ,simple test

Browse files
Files changed (1) hide show
  1. app.py +40 -39
app.py CHANGED
@@ -2,9 +2,7 @@ from fastapi import FastAPI, HTTPException
2
  from typing import List, Union
3
  import requests
4
  import ast
5
-
6
- from sqlalchemy import create_engine, text
7
- from sqlalchemy.orm import sessionmaker, Session
8
 
9
  # -------------------------
10
  # App Initialization
@@ -12,23 +10,25 @@ from sqlalchemy.orm import sessionmaker, Session
12
  app = FastAPI()
13
 
14
  # -------------------------
15
- # Database Setup (SQLAlchemy + PyMySQL)
16
  # -------------------------
17
- DB_URL = (
18
- "mysql+pymysql://avnadmin:AVNS_aT0RGFafs6_34WFegSF"
19
- "@mysql-19285eb2-tahaelshrif1-7999.h.aivencloud.com:11520/trafficManagerSignals"
20
- "?charset=utf8mb4"
21
- )
22
-
23
- engine = create_engine(DB_URL, pool_size=10, max_overflow=20, pool_pre_ping=True)
24
- SessionLocal = sessionmaker(bind=engine)
25
 
26
  def get_db():
27
- db = SessionLocal()
28
- try:
29
- yield db
30
- finally:
31
- db.close()
 
 
 
 
 
 
 
 
 
32
 
33
  # -------------------------
34
  # Utilities
@@ -59,8 +59,6 @@ def get_traffic_in_container(coordinates):
59
  def read_root():
60
  return {"message": "Hello from FastAPI on Hugging Face Spaces!"}
61
 
62
- import requests
63
-
64
  @app.get("/test-internet")
65
  def test_internet():
66
  try:
@@ -68,13 +66,15 @@ def test_internet():
68
  return {"status": "ok", "your_ip": r.json()}
69
  except Exception as e:
70
  return {"status": "error", "detail": str(e)}
71
-
72
  @app.get("/test-db")
73
  def test_db():
74
  try:
75
- db = next(get_db())
76
-
77
- result = db.execute(text("SELECT 1")).fetchone()
 
 
78
  return {"status": "connected", "result": result}
79
  except Exception as e:
80
  return {"status": "error", "detail": str(e)}
@@ -95,22 +95,23 @@ def receive_coordinates(coords: Union[str, List[float]]):
95
  # -------------------------
96
  # Signal Database Check
97
  # -------------------------
98
- def check_signals(coords, db: Session = next(get_db())):
99
- """
100
- Check if lat/lon exists in traffic_signals DB table.
101
- Returns list of tl_id_sumo.
102
- """
103
  found_signals = []
104
- for lat, lon in coords:
105
- result = db.execute(
106
- text("""
107
- SELECT tl_id_sumo FROM traffic_signals
108
- WHERE lat = :lat AND lon = :lon
109
- """),
110
- {"lat": lat, "lon": lon}
111
- ).fetchone()
112
-
113
- if result:
114
- found_signals.append(result.tl_id_sumo)
 
 
 
 
115
 
116
  return found_signals
 
2
  from typing import List, Union
3
  import requests
4
  import ast
5
+ import pymysql
 
 
6
 
7
  # -------------------------
8
  # App Initialization
 
10
  app = FastAPI()
11
 
12
  # -------------------------
13
+ # Database Setup (Pure PyMySQL)
14
  # -------------------------
15
+ timeout = 20
 
 
 
 
 
 
 
16
 
17
  def get_db():
18
+ connection = pymysql.connect(
19
+ charset="utf8mb4",
20
+ connect_timeout=timeout,
21
+ cursorclass=pymysql.cursors.DictCursor,
22
+ db="trafficManagerSignals",
23
+ host="mysql-19285eb2-tahaelshrif1-7999.h.aivencloud.com",
24
+ password="AVNS_aT0RGFafs6_34WFegSF",
25
+ read_timeout=timeout,
26
+ port=11520,
27
+ user="avnadmin",
28
+ write_timeout=timeout,
29
+ ssl={"ssl": True},
30
+ )
31
+ return connection
32
 
33
  # -------------------------
34
  # Utilities
 
59
  def read_root():
60
  return {"message": "Hello from FastAPI on Hugging Face Spaces!"}
61
 
 
 
62
  @app.get("/test-internet")
63
  def test_internet():
64
  try:
 
66
  return {"status": "ok", "your_ip": r.json()}
67
  except Exception as e:
68
  return {"status": "error", "detail": str(e)}
69
+
70
  @app.get("/test-db")
71
  def test_db():
72
  try:
73
+ connection = get_db()
74
+ with connection.cursor() as cursor:
75
+ cursor.execute("SELECT 1")
76
+ result = cursor.fetchone()
77
+ connection.close()
78
  return {"status": "connected", "result": result}
79
  except Exception as e:
80
  return {"status": "error", "detail": str(e)}
 
95
  # -------------------------
96
  # Signal Database Check
97
  # -------------------------
98
+ def check_signals(coords):
99
+ connection = get_db()
 
 
 
100
  found_signals = []
101
+ try:
102
+ with connection.cursor() as cursor:
103
+ for lat, lon in coords:
104
+ cursor.execute(
105
+ """
106
+ SELECT tl_id_sumo FROM traffic_signals
107
+ WHERE lat = %s AND lon = %s
108
+ """,
109
+ (lat, lon)
110
+ )
111
+ result = cursor.fetchone()
112
+ if result:
113
+ found_signals.append(result['tl_id_sumo'])
114
+ finally:
115
+ connection.close()
116
 
117
  return found_signals