-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
61 lines (52 loc) · 1.59 KB
/
main.py
File metadata and controls
61 lines (52 loc) · 1.59 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
from fastapi import FastAPI
from pymongo import MongoClient
from dotenv import load_dotenv
import os
load_dotenv()
app = FastAPI()
connect = MongoClient(os.getenv('MONGODB_URL'))
db = connect['db']
table = db['db_table']
#insert data into mongodb
@app.put("/insert/{id}")
async def insert(id: int,item_title: str):
try:
table.insert_one(
{
'_id': id,
'item_title': item_title,
}
)
return {"message": "item inserted"}
except Exception as e:
return {"message": "item not inserted"}
#update data into mongodb
@app.put("/update/{id}")
async def update(id: int, new_item_title: str):
try:
data: dict = table.find_one_and_update({'_id': id}, {'$set': {'item_title': new_item_title}})
if data:
return {"message": "item updated"}
return {"message": "item not found"}
except Exception as e:
return {"error": str(e)}
#delete data from mongodb
@app.delete("/delete/{id}")
async def delete(id: int):
try:
data: dict = table.find_one_and_delete({'_id': id})
if data:
return {"message": "item deleted"}
return {"message": "item not found"}
except Exception as e:
return {"error": str(e)}
#get data from mongodb
@app.get("/get/{id}")
async def get(id: int):
try:
data: dict = table.find_one({'_id': id})
if data:
return {"id": data['_id'], "item_title": data['item_title']}
return {"message": "item not found"}
except Exception as e:
return {"error": str(e)}