generated from MLH-Fellowship/orientation-project-python
-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathhelpers.py
79 lines (70 loc) · 2.72 KB
/
helpers.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
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
"""
Helper functions for the Flask application
"""
import json
import phonenumbers
from models import Experience, Education, Skill, UserInformation
def validate_fields(field_names, request_data):
"""
Checks that the required fields are in the request data
"""
return [
field
for field in field_names
if field not in request_data or request_data[field] in [None, "", "null"]
]
def validate_phone_number(phone_number):
"""
Checks that the phone number is valid and properly internationalized
"""
try:
if phone_number and phone_number.startswith("+"):
parsed_number = phonenumbers.parse(phone_number, None)
return phonenumbers.is_valid_number(parsed_number)
return False
except phonenumbers.phonenumberutil.NumberParseException:
return False
def load_data(filename):
"""
Using dataclasses to serialize and deserialize JSON data.
this forms a "layer" between the data and the application.
Saving and loading data from a JSON file
"""
try:
with open(filename, 'r', encoding="utf-8") as file:
data = json.load(file)
return {
"experience": [Experience(**exp) for exp in data.get('experience', [])],
"education": [Education(**edu) for edu in data.get('education', [])],
"skill": [Skill(**skl) for skl in data.get('skill', [])],
"user_information": [UserInformation(**info) for info in data.get('user_information', [])]
}
except FileNotFoundError:
print(f"File {filename} not found.")
return {"experience": [], "education": [], "skill": [], "user_information": []}
except json.JSONDecodeError:
print("Error decoding JSON.")
return {"experience": [], "education": [], "skill": [], "user_information": []}
def save_data(filename, data):
"""
This function writes the data to a JSON file.
First it converts the data to a dictionary, then writes it to the file.
"""
try:
with open(filename, 'w', encoding="utf-8") as file:
json_data = {
"experience": [exp.__dict__ for exp in data['experience']],
"education": [edu.__dict__ for edu in data['education']],
"skill": [skl.__dict__ for skl in data['skill']],
"user_information": [info.__dict__ for info in data['user_information']]
}
json.dump(json_data, file, indent=4)
except IOError as e:
print(f"An error occurred while writing to {filename}: {e}")
def generate_id(data, model):
"""
Generate a new ID for a model
"""
if data[model]:
return max(item.id for item in data[model] if item.id is not None) + 1
return 1