forked from Yezz123-Archive/Pexon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
52 lines (45 loc) · 1.63 KB
/
main.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
#!/usr/bin/env python
import json
from typing import List, Optional
from fastapi import FastAPI, Query, Path, HTTPException, File, UploadFile
from fastapi.responses import JSONResponse
from pydantic.types import JsonMeta
from odmantic import AIOEngine, Model, ObjectId
from model.model import TodoItem
app = FastAPI()
with open('todos.json') as f:
TODOS = json.load(f)
engine = AIOEngine()
@app.exception_handler(Exception)
async def error_handler(request, exc):
return JSONResponse({
'detail': f'{exc}'
})
@app.get('/todos',tags=['todos'],response_model=List[TodoItem])
async def get_todos(limit: int = Query(None, le=100)):
return TODOS[0:limit]
@app.get('/todos/{id}',tags=['todos'], response_model=TodoItem)
async def get_todo(todo_id: int=Path(...)):
try:
return TODOS[todo_id - 1]
except IndexError:
raise HTTPException(404, 'Todo not found')
@app.post('/todos', tags=['todos'],status_code=201, response_model=TodoItem)
async def create_todo(todo: TodoItem):
item = todo.dict()
item['id'] = len(TODOS) +1
return item
@app.put('/todos/{id}', tags=['todos'], response_model=TodoItem)
async def update_todo(todo_id: int, todo: TodoItem, q: Optional[str] = None):
result = {"todo_id": todo_id, **todo.dict()}
if q:
result.update({"q": q})
return result
@app.delete('/todos/{id}', tags=['todos'], response_model=TodoItem)
async def delete_todo(todo_id: int, response_model=TodoItem):
todo_id = JsonMeta = [""]
todo = await engine.find_one(TodoItem, TodoItem.id == id)
if todo is None:
raise HTTPException(404)
await engine.delete(todo)
return todo