-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
165 lines (127 loc) · 4.57 KB
/
Copy pathmain.py
File metadata and controls
165 lines (127 loc) · 4.57 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
from email import message
from fastapi import FastAPI, Request, HTTPException, Response
from pydantic import BaseModel,field_validator
import sqlite3
import os
from dotenv import load_dotenv
import psycopg
app = FastAPI()
################################################################################
#DATABASE
load_dotenv()
DATABASE_URL = os.getenv("DATABASE_URL")
def get_db_connection():
return psycopg.connect(DATABASE_URL)
def init_db():
with get_db_connection() as con:
with con.cursor() as cur:
cur.execute("CREATE TABLE IF NOT EXISTS tasks(id SERIAL PRIMARY KEY, title TEXT, done BOOLEAN)")
cur.execute("SELECT COUNT(*) FROM tasks")
COUNT = cur.fetchone()[0]
if COUNT ==0:
cur.executemany("INSERT INTO tasks(title, done) VALUES(%s, %s)", [
("Task 0", True),
("Task 1", True),
("Task 2", False)
])
con.commit()
#####################################################################################
@app.on_event("startup")
def on_startup():
init_db()
#####################################################################################
@app.get("/test")
async def test():
return {}
###############################################################################
@app.get("/", summary="API information")
async def root():
return {"name": "Task API", "version": "1.0", "endpoints": ["/tasks"] }
@app.get("/health",summary="Check API health")
async def health():
return {"status": "ok"}
###############################################################################
###############################################################################
@app.get("/tasks", summary="Get all tasks")
async def get_tasks():
with get_db_connection() as con:
with con.cursor() as cur:
cur.execute("SELECT * FROM tasks")
taskx = cur.fetchall()
return taskx
@app.get("/tasks/{id}", summary="Get task by ID")
async def get_task_by_id(id: int):
with get_db_connection() as con:
with con.cursor() as cur:
id_valued = cur.execute("SELECT * FROM tasks WHERE id = %s", (id,))
task = id_valued.fetchone()
if task:
return task
return {"error": f"Task {id} not found"}
###############################################################################
class Task(BaseModel):
title: str
@field_validator("title")
def title_not_empty(cls, value):
if value.strip() == "":
raise ValueError("Title cannot be empty")
return value
@app.post("/tasks", status_code=201)
async def create_task(task: Task):
with get_db_connection() as con:
with con.cursor() as cur:
cur.execute(
"INSERT INTO tasks(title, done) VALUES(%s, %s)",
(task.title, False)
)
con.commit()
return task
###############################################################################
from pydantic import BaseModel, field_validator
class UpdateTask(BaseModel):
title: str
done: bool
@field_validator("title")
def title_not_empty(cls, value):
if value.strip() == "":
raise ValueError("Title cannot be empty")
return value
@app.put("/tasks/{id}", summary="Update a task")
async def update_task(id: int, req: UpdateTask):
with get_db_connection() as con:
with con.cursor() as cur:
cur.execute(
"SELECT * FROM tasks WHERE id = %s",
(id,)
)
task = cur.fetchone()
if task is None:
raise HTTPException(
status_code=404,
detail=f"Task {id} not found"
)
cur.execute(
"""
UPDATE tasks
SET title = %s, done = %s
WHERE id = %s
""",
(req.title, req.done, id)
)
con.commit()
return {
"id": id,
"title": req.title,
"done": req.done
}
@app.delete("/tasks/{id}", status_code=204, summary="Delete a task")
async def delete_task(id: int):
with get_db_connection() as con:
with con.cursor() as cur:
cur.execute("DELETE FROM tasks WHERE id = %s", (id,))
if cur.rowcount > 0:
return Response(status_code=204)
raise HTTPException(
status_code=404,
detail=f"Task {id} not found"
)