-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlibrary.py
More file actions
39 lines (26 loc) · 1.24 KB
/
library.py
File metadata and controls
39 lines (26 loc) · 1.24 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
"""A library of functions"""
import csv
import json
from io import StringIO
from model import Employee, Company
def read_file(filename: str) -> str:
"""Reads and returns the contents of the file."""
with open(filename) as infile:
return infile.read()
def parse_csv(buffer: str) -> list[dict]:
"""Parses a string of CSV int a list of dictionaries."""
data = StringIO(buffer)
reader = csv.DictReader(data, quotechar='"')
return [row for row in reader]
def parse_json(buffer: str) -> list[dict]:
"""Parses a json blob into a list of dictionaries"""
return json.loads(buffer)
def filter_employee_records(records: list[dict]) -> list[dict]:
"""Only returns records that have a employee_id field that is populated."""
return list(filter(lambda x: bool(x.get("employee_id")), records))
def filter_company_records(records: list[dict]) -> list[dict]:
"""Only returns records that have a company_id field that is populated."""
return list(filter(lambda x: bool(x.get("company_id")), records))
def to_pydantic(records: list[dict]) -> list[Employee | Company]:
"""Convert dictionaries to the appropriate Pydantic model"""
return [Company(**r) if r.get("company_id") else Employee(**r) for r in records]