-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
190 lines (167 loc) · 6.28 KB
/
main.py
File metadata and controls
190 lines (167 loc) · 6.28 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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import psycopg2
from psycopg2.extras import RealDictCursor
from typing import Optional
import os
import logging
app = FastAPI()
DB_CONFIG = {
'host': os.getenv('POSTGRES_HOST'),
'dbname': os.getenv('POSTGRES_DB'),
'user': os.getenv('POSTGRES_USER'),
'password': os.getenv('POSTGRES_PASSWORD'),
'port': int(os.getenv('POSTGRES_PORT', 5432))
}
class ItemModel(BaseModel):
train_date: str
platform: int
start_point: str
end_point: str
arrival_time: str
departure_time: str
class PostgresQuery:
def __init__(self, config):
self.conn = psycopg2.connect(**config)
def execute_query(self, query, params=None, fetch=True):
with self.conn.cursor(cursor_factory=RealDictCursor) as cursor:
cursor.execute(query, params)
if fetch:
return cursor.fetchall()
else:
return cursor.rowcount
def commit(self):
self.conn.commit()
def close(self):
self.conn.close()
@app.get("/")
async def root():
return {"message": "Please use /trains, /trains/id/{id}, /trains/platform/{platform}, or /trains/end_point/{end_point}."}
@app.get("/trains")
async def get_trains():
try:
query = PostgresQuery(DB_CONFIG)
q = "SELECT * FROM trains"
result = query.execute_query(q)
query.close()
return result
except Exception as e:
raise HTTPException(status_code=500, detail=str(e), headers={"X-Error": "An error occurred while fetching the trains."})
@app.get("/trains/id/{id}")
async def get_train_by_id(id: int):
query = None
try:
query = PostgresQuery(DB_CONFIG)
q = "SELECT * FROM trains WHERE id = %(id)s"
params = {"id": id}
result = query.execute_query(q, params)
if not result:
raise HTTPException(status_code=404, detail="Train not found")
return result
except HTTPException:
raise
except Exception as e:
raise HTTPException(
status_code=500,
detail=str(e),
headers={"X-Error": "An error occurred while fetching the train."}
)
finally:
if query:
query.close()
@app.get("/trains/platform/{platform}")
async def get_train_by_platform(platform: str):
try:
query = PostgresQuery(DB_CONFIG)
q = "SELECT * FROM trains WHERE platform = %(platform)s"
params = {"platform": platform}
result = query.execute_query(q, params)
query.close()
return result
except Exception as e:
raise HTTPException(status_code=500, detail=str(e), headers={"X-Error": "An error occurred while fetching the train."})
@app.get("/trains/end_point/{end_point}")
async def get_train_by_end_point(end_point: str):
try:
query = PostgresQuery(DB_CONFIG)
q = "SELECT * FROM trains WHERE end_point = %(end_point)s"
params = {"end_point": end_point}
result = query.execute_query(q, params)
query.close()
return result
except Exception as e:
raise HTTPException(status_code=500, detail=str(e), headers={"X-Error": "An error occurred while fetching the train."})
@app.post("/trains")
async def create_train(train: ItemModel):
try:
query = PostgresQuery(DB_CONFIG)
q = """
INSERT INTO trains
(train_date, platform, start_point, end_point, arrival_time, departure_time)
VALUES (%(train_date)s, %(platform)s, %(start_point)s, %(end_point)s, %(arrival_time)s, %(departure_time)s)
RETURNING *
"""
params = train.model_dump()
result = query.execute_query(q, params)
query.commit()
query.close()
return {"message": "Train created successfully", "train": result[0]}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e), headers={"X-Error": "An error occurred while creating the train."})
@app.put("/trains/id/{id}")
async def update_train(id: int, train: ItemModel):
try:
query = PostgresQuery(DB_CONFIG)
# Check if train exists
check_q = "SELECT id FROM trains WHERE id = %(id)s"
check_result = query.execute_query(check_q, {"id": id})
if not check_result:
raise HTTPException(status_code=404, detail="Train not found")
q = """
UPDATE trains
SET train_date = %(train_date)s, platform = %(platform)s, start_point = %(start_point)s,
end_point = %(end_point)s, arrival_time = %(arrival_time)s, departure_time = %(departure_time)s
WHERE id = %(id)s
RETURNING *
"""
params = {**train.model_dump(), "id": id}
result = query.execute_query(q, params)
query.commit()
query.close()
return {"message": "Train updated successfully", "train": result[0]}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e), headers={"X-Error": "An error occurred while updating the train."})
@app.delete("/trains/id/{id}")
async def delete_train(id: int):
query = None
try:
query = PostgresQuery(DB_CONFIG)
param = {"id": id}
# Check if the train exists
check_q = "SELECT * FROM trains WHERE id = %(id)s"
check_result = query.execute_query(check_q, param)
if not check_result:
raise HTTPException(status_code=404, detail="Train not found")
# Perform the delete operation
q = "DELETE FROM trains WHERE id = %(id)s"
delete_result = query.execute_query(q, param, fetch=False)
query.commit()
if delete_result == 0:
raise HTTPException(status_code=404, detail="Train not found")
return {
"message": "Train deleted successfully",
"deleted_train": check_result[0], # Returning the deleted train's data
"rows_affected": delete_result # Number of rows affected
}
except HTTPException:
raise
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"An error occurred while deleting the train: {str(e)}"
)
finally:
if query:
query.close()