-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpractice1.py
103 lines (95 loc) · 2.72 KB
/
practice1.py
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
from fastapi import FastAPI, HTTPException
import psycopg2
from pydantic import BaseModel
def db_connect():
conn = psycopg2.connect(
host="localhost",
dbname="postgres",
user="postgres",
password="ganesh",
port=5432
)
return conn
class Test(BaseModel):
test: str
app = FastAPI()
@app.get("/test")
def test():
return {"message": "Test"}
@app.post("/create")
def create(test: Test):
conn = db_connect()
try:
with conn.cursor() as cur:
print("Database connected")
cur.execute(
"""
CREATE TABLE IF NOT EXISTS test (
id SERIAL PRIMARY KEY,
test VARCHAR(255)
)
"""
)
cur.execute(
"""
INSERT INTO test (test)
VALUES (%s)
RETURNING id
""",
(test.test,)
)
test_id = cur.fetchone()[0]
conn.commit()
return {**test.dict(), "id": test_id}
except Exception as e:
conn.rollback()
raise HTTPException(status_code=500, detail=f"Database error: {e}")
finally:
conn.close()
@app.put("/update/{id}")
def update(updated_test: Test, id: int):
conn = db_connect()
try:
with conn.cursor() as cur:
cur.execute(
"""
UPDATE test
SET test = %s
WHERE id = %s
RETURNING id, test
""",
(updated_test.test, id) # Pass parameters as a tuple
)
updated_row = cur.fetchone()
if updated_row is None:
raise HTTPException(status_code=404, detail="Test not found")
conn.commit()
return {"id": updated_row[0], "test": updated_row[1]}
except Exception as e:
conn.rollback()
raise HTTPException(status_code=500, detail=f"Database error: {e}")
finally:
conn.close()
@app.delete("/delete/{id}")
def delete(id:int):
conn = db_connect()
try:
with conn.cursor() as cur:
cur.execute(
"""
DELETE FROM test
WHERE id = %s
RETURNING id
""",
(id,)
)
deleted_row = cur.fetchone()
if deleted_row is None:
raise HTTPException(status_code=404,detail="Not found")
conn.commit()
return {"message" : f"Test with {id} deleted"}
except Exception as e:
conn.rollback()
raise HTTPException(status_code=500,detail=f"Error {e}")
finally:
conn.close()