Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
168 lines (150 loc) · 4.98 KB
/
Copy pathserver.py
File metadata and controls
168 lines (150 loc) · 4.98 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, HTMLResponse
from pydantic import BaseModel
import pyodbc
from fastapi.middleware.cors import CORSMiddleware
import os
app = FastAPI()
# CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ✅ FIX: Kiểm tra thư mục static tồn tại
if not os.path.exists("static"):
os.makedirs("static")
# Serve static files
app.mount("/static", StaticFiles(directory="static"), name="static")
# Kết nối SQL Server
conn_str = (
"DRIVER={ODBC Driver 17 for SQL Server};"
"SERVER=HYHONCUTE;"
"DATABASE=RescueDB;"
"Trusted_Connection=yes;"
"TrustServerCertificate=yes;"
)
def get_conn():
try:
return pyodbc.connect(conn_str)
except Exception as e:
print(f"❌ Lỗi kết nối DB: {e}")
raise
# Models
class RescueReport(BaseModel):
name: str
phone: str
message: str
lat: float
lng: float
address: str = ""
# Root -> Form gửi cứu hộ
@app.get("/")
def read_root():
return FileResponse("static/index.html")
# ✅ FIX: Bản đồ với error handling
@app.get("/map")
def read_map():
try:
if not os.path.exists("static/map.html"):
return HTMLResponse(
content="<h1>❌ File map.html không tồn tại!</h1><p>Vui lòng tạo file static/map.html</p>",
status_code=404
)
return FileResponse("static/map.html")
except Exception as e:
return HTMLResponse(content=f"<h1>❌ Lỗi: {str(e)}</h1>", status_code=500)
# API test kết nối
@app.get("/api/test")
def test():
return {"status": "ok", "message": "Server đang chạy!"}
# API test DB
@app.get("/api/test-db")
def test_db():
try:
conn = get_conn()
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM RescueRequests")
count = cursor.fetchone()[0]
conn.close()
return {"status": "success", "message": f"Kết nối DB thành công! Có {count} yêu cầu cứu hộ."}
except Exception as e:
return {"status": "error", "message": str(e)}
# API nhận yêu cầu cứu hộ
@app.post("/api/report")
def report(data: RescueReport):
try:
conn = get_conn()
cursor = conn.cursor()
cursor.execute("""
INSERT INTO RescueRequests (Name, Phone, Message, Latitude, Longitude, Address, CreatedAt)
VALUES (?, ?, ?, ?, ?, ?, GETDATE())
""", (data.name, data.phone, data.message, data.lat, data.lng, data.address))
conn.commit()
conn.close()
return {"status": "success", "message": "Đã gửi yêu cầu cứu hộ!"}
except Exception as e:
return {"status": "error", "message": str(e)}
# ✅ FIX: API lấy danh sách cứu hộ với error handling
@app.get("/api/locations")
def locations():
try:
conn = get_conn()
cursor = conn.cursor()
cursor.execute("""
SELECT Id, Name, Phone, Message, Latitude, Longitude,
ISNULL(Address, N'Không rõ') as Address,
ISNULL(Status, 'Pending') as Status,
FORMAT(CreatedAt, 'dd/MM/yyyy HH:mm:ss') as CreatedAt
FROM RescueRequests
WHERE Status != 'Rescued' OR Status IS NULL
ORDER BY CreatedAt DESC
""")
columns = [column[0] for column in cursor.description]
results = []
for row in cursor.fetchall():
row_dict = {}
for i, column in enumerate(columns):
value = row[i]
# Convert float to proper format
if isinstance(value, float):
row_dict[column] = value
else:
row_dict[column] = value
results.append(row_dict)
conn.close()
return {"status": "success", "data": results, "count": len(results)}
except Exception as e:
print(f"❌ Lỗi API locations: {e}")
return {"status": "error", "message": str(e), "data": []}
# API đánh dấu đã cứu
@app.post("/api/mark-rescued/{id}")
def mark_rescued(id: int):
try:
conn = get_conn()
cursor = conn.cursor()
cursor.execute("""
UPDATE RescueRequests
SET Status = 'Rescued', RescuedAt = GETDATE()
WHERE Id = ?
""", (id,))
conn.commit()
conn.close()
return {"status": "success"}
except Exception as e:
return {"status": "error", "message": str(e)}
# API xóa yêu cầu
@app.delete("/api/delete/{id}")
def delete_request(id: int):
try:
conn = get_conn()
cursor = conn.cursor()
cursor.execute("DELETE FROM RescueRequests WHERE Id = ?", (id,))
conn.commit()
conn.close()
return {"status": "success"}
except Exception as e:
return {"status": "error", "message": str(e)}