-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
86 lines (62 loc) · 1.9 KB
/
Copy pathmain.py
File metadata and controls
86 lines (62 loc) · 1.9 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
from fastapi import FastAPI, Query, HTTPException
from pydantic import BaseModel
from typing import Optional
import json
app = FastAPI()
class Person(BaseModel):
id: Optional[int] = None
name: str
age: int
gender: str
with open('people.json', 'r') as f:
people = json.load(f)
@app.get('/person/{p_id}', status_code = 200)
def get_persion(p_id: int):
person = [p for p in people if p['id'] == p_id]
return person[0] if len(person) > 0 else {}
@app.get("/search", status_code=200)
def search_person(age: Optional[int] = Query(None, title="Age", description="The age to filter for"),
name: Optional[str] = Query(None, title="Name", description= "The name to filter for")):
people1 = [p for p in people if p['age'] == age]
if name is None:
if age is None:
return people
else:
return people1
else:
people2 = [p for p in people if name.lower in p['name'].lower]
if age is None:
return people2
else:
combined = [p for p in people1 if p in people2]
return combined
@app.post('/addPerson', status_code = 201)
def add_person(person: Person):
p_id = max([p['id'] for p in people] + 1)
new_person = {
"id": p_id,
"name": person.name,
"age": person.age,
"gender": person.gender
}
people.append(new_person)
with open('people.json', 'w') as f:
json.dump(people, f)
return new_person
@app.put('/changePerson',status_code=204)
def chanege_person(person: Person):
new_person = {
"id": person.id,
"name": person.name,
"age": person.age,
"gender": person.gender
}
person_list = [p for p in people if['id'] == person.id]
if len(person_list) > 0:
people.remove(person_list[0])
people.append(new_person)
with open('people.json', 'w') as f:
json.dump(people,f)
return new_person
else:
return HTTPException(status_code=404, detail=f"Person with id {person.id} does not exits!")