File size: 2,381 Bytes
662a446
 
 
 
 
b916cdf
 
662a446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from typing import Optional
from fastapi import FastAPI, APIRouter, Query
from testpkg.finit import api_router, app
from testpkg.schemas import MyDataModel, MyDataSearchResults, CreateMyDataModelEntity
from testpkg.MyDataList import myDataList


@api_router.get("/datas/getall", status_code=200)
def get_all() -> dict:   
    return {"data": myDataList}

# @api_router.get("/add_rows", status_code=200)
# def add_rows(rowstr:str) -> dict:   
#     return {"data": arr}


# Updated using to use a response_model
# https://fastapi.tiangolo.com/tutorial/response-model/
@api_router.get("/datas/get/{data_id}", status_code=200)
def get_data(*, data_id: int) -> dict:
    """
    Fetch a single data by ID
    """

    result = [x for x in myDataList if x["id"] == data_id]
    if result:
        return result[0]


# Updated using the FastAPI parameter validation `Query` class
# # https://fastapi.tiangolo.com/tutorial/query-params-str-validations/
@api_router.get("/datas/search", status_code=200)
def search_data(*, keyword: Optional[str] = Query(None,min_length=3), max_results: Optional[int] = 3) -> dict:
    """
    Search for datas based on text keyword
    """
    if not keyword:
        # we use Python list slicing to limit results
        # based on the max_results query parameter
        return {"results": myDataList[:max_results]}

    results = filter(lambda x: keyword.lower() in x["text"].lower(), myDataList)
    return {"results": list(results)[:max_results]}


# New addition, using Pydantic model `RecipeCreate` to define
# the POST request body
@api_router.post("/datas/create", status_code=201, response_model=MyDataModel)
def create_data(*, my_data: CreateMyDataModelEntity) -> MyDataModel:
    """
    Create a new data (in memory only)
    """
    new_entry_id = len(myDataList) + 1
    entry = MyDataModel(
        id=new_entry_id,
        text=my_data.text,
        description=my_data.description
    )
    myDataList.append(entry.model_dump())

    return entry


# Updated using to use a response_model
# https://fastapi.tiangolo.com/tutorial/response-model/
@api_router.get("/datas/delete/{data_id}", status_code=200)
def delete_data(*, data_id: int) -> dict:
    """
    Fetch a single data by ID
    """

    result = [x for x in myDataList if x["id"] == data_id]
    if result:
        myDataList.remove(result[0])

    return {"datas":myDataList}