Repository navigation
Expand file tree
/
Copy pathdelete.py
More file actions
80 lines (72 loc) · 1.98 KB
/
Copy pathdelete.py
File metadata and controls
80 lines (72 loc) · 1.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
from fastapi import FastAPI,Depends,HTTPException
from sqlalchemy import create_engine,Column,Integer,String
from sqlalchemy.orm import sessionmaker,declarative_base,Session
app=FastAPI()
database_url="sqlite:///./data.db"
engine=create_engine(
database_url,
connect_args={"check_same_thread":False}
)
sessionlocal=sessionmaker(bind=engine)
Base=declarative_base()
class Todo(Base):
__tablename__="todos"
id=Column(Integer,primary_key=True,index=True)
title=Column(String)
completed=Column(String)
Base.metadata.create_all(bind=engine)
def get_db():
db=sessionlocal()
try:
yield db
finally:
db.close()
@app.post("/todos")
def create_todo(title:str,db:Session=Depends(get_db)):
todo=Todo(title=title,completed="False")
db.add(todo)
db.commit()
db.refresh(todo)
return {
"message":"Todo Created",
"data":todo
}
#read all data
@app.get("/todos")
def get_todos(db:Session=Depends(get_db)):
todo=db.query(Todo).all()
return {
"Total":len(todo),
"Data":todo
}
#read data based on id
@app.get("/todos/{id}")
def get_todo(id=int,db:Session=Depends(get_db)):
todo=db.query(Todo).filter(Todo.id==id).first()
if not todo:
raise HTTPException(status_code=404,detail="Todo not found")
return todo
#update data
@app.put("/todos/{id}")
def update_todo(id=int,title=str,db:Session=Depends(get_db)):
todo=db.query(Todo).filter(Todo.id==id).first()
if not todo:
raise HTTPException(status_code=404,detail="Todo not found")
todo.title=title
db.commit()
db.refresh(todo)
return {
"message":"todo updated",
"data":todo
}
#delete all data
@app.delete("/todos/{id}")
def delete_todo(id=int,db:Session=Depends(get_db)):
todo=db.query(Todo).filter(Todo.id==id).first()
if not todo:
raise HTTPException(status_code=404,detail="Todo not found")
db.delete(todo)
db.commit()
return {
"message":"data deleted"
}