Implementing db querying

This commit is contained in:
2023-01-12 15:27:30 +01:00
parent 2fabf39c7b
commit 21b668d1fb
2 changed files with 101 additions and 23 deletions

39
main.py
View File

@@ -1,43 +1,36 @@
from fastapi import FastAPI
from fastapi import FastAPI, Depends
from typing import List
from sqlalchemy.orm import Session
from back.schemas import PeopleList, AverageAgeByCountry, CountByCountry, GenderRepartition
from back.db import get_db, create_people_from_list, get_average_age_by_country, \
count_people_by_country, get_gender_repartition_by_country
app = FastAPI()
@app.post("/people")
async def create_people(people_list: PeopleList) -> dict:
async def create_people(people_list: PeopleList, db: Session = Depends(get_db)) -> dict:
count = create_people_from_list(db, people_list.people)
return {
"message": "People list has been succesfully imported",
"records_created": 10
"records_created": count
}
@app.get("/average_age", response_model=List[AverageAgeByCountry])
async def read_average_age() -> List[AverageAgeByCountry]:
return [
{'country': 'FR', 'average_age': 15.0},
{'country': 'BE', 'average_age': 25.0},
{'country': 'DE', 'average_age': 23.3},
{'country': 'IT', 'average_age': 45.0},
]
async def read_average_age(db: Session = Depends(get_db)) -> List[AverageAgeByCountry]:
return [AverageAgeByCountry(**a) for a in get_average_age_by_country(db)]
@app.get("/count_by_country", response_model=List[CountByCountry])
async def read_count_by_country() -> List[CountByCountry]:
return [
{'country': 'FR', 'people_count': 2},
{'country': 'BE', 'people_count': 4},
{'country': 'DE', 'people_count': 3},
{'country': 'IT', 'people_count': 1},
]
async def read_count_by_country(db: Session = Depends(get_db)) -> List[CountByCountry]:
return [CountByCountry(**a) for a in count_people_by_country(db)]
@app.get("/gender_repartition/{country}", response_model=GenderRepartition)
async def read_count_by_gender(country: str) -> GenderRepartition:
return {
"female_proportion": 33.3,
"male_proportion": 66.6
}
async def read_count_by_gender(country: str, db: Session = Depends(get_db)) -> GenderRepartition:
return GenderRepartition(**get_gender_repartition_by_country(db, country))