-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
179 lines (134 loc) · 5.06 KB
/
main.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import os
import time
import sys
import logging
import json
import random
import requests
# *********************************************** #
# LOGGING
# *********************************************** #
log_level = str.upper(os.environ.get('LOG_LEVEL', 'DEBUG'))
log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
logging.basicConfig(stream = sys.stdout, level = log_level, format = log_format)
# Set the log to use GMT time zone
logging.Formatter.converter = time.gmtime
# Add milliseconds
logging.Formatter.default_msec_format = '%s.%03d'
log = logging.getLogger(__name__)
# *********************************************** #
# SETUP
# *********************************************** #
session = requests.Session()
url = os.environ.get("PLN_API_URL")
session.headers.update({
"Content-Type": "application/json",
"Authorization": f"PLANONKEY accesskey={os.environ.get('PLN_API_KEY')}"
})
# *********************************************** #
# CONFIGURATION
# *********************************************** #
max_pages = 15
max_results = 5000
time_sleep = 120
seed = "dartmouth"
# *********************************************** #
# CACHE
# *********************************************** #
################# IDENTITIES #################
identities = []
for page in range(1, max_pages):
# TODO: cache additional identies, left off at page 7
response = requests.get(url=f"https://randomuser.me/api?seed={seed}&results={max_results}&page={page}")
# Throttling
log.info(f"Sleeping for {time_sleep} seconds")
time.sleep(time_sleep)
if response.ok:
identities = identities + response.json()['results']
with open(file='cache/identities.json', mode='w') as file:
file.write(json.dumps(identities))
################# DEPARTMENTS #################
departments = session.post(url=f"{url}/read/Department", json={}).json()['records']
with open(file='cache/departments.json', mode='w') as file:
file.write(json.dumps(departments))
################# DEPARTMENTS #################
positions = session.post(url=f"{url}/read/PersonPosition", json={}).json()['records']
with open(file='cache/positions.json', mode='w') as file:
file.write(json.dumps(positions))
# *********************************************** #
# MAIN
# *********************************************** #
### LOAD CACHE
with open(file='cache/identities.json', mode='r') as file:
identities = json.load(file)
with open(file='cache/departments.json', mode='r') as file:
departments = json.load(file)
with open(file='cache/positions.json', mode='r') as file:
positions = json.load(file)
### LOAD IDENTITIES
failed = []
request_statistics = []
records = []
start_time = time.time()
for identity in identities:
log.info(f"Creating instance of Person object {identity['name']['last']}, {identity['name']['first']}")
### CREATE BO
body = {
"values": {
"FirstName": identity['name']['first'],
"Initials": f"{identity['name']['first'][0]}{identity['name']['last'][0]}",
"LastName": identity['name']['last'],
"RefBOStateUserDefined": 1079,
"PersonPositionRef": random.choice(positions)['Syscode'],
"DepartmentRef": random.choice(departments)['Syscode']
}
}
try:
request_start_time = time.time()
response = session.post(url=f"{url}/execute/UsrEmployee/BomAdd", json=body)
request_end_time = time.time()
request_statistics.append({
"start": request_start_time,
"end": request_end_time,
"response_code": response.status_code
})
response.raise_for_status()
records = records + response.json()['records']
except Exception as e:
log.error(repr(e))
failed.append({
'body': body,
'error': repr(e)
})
end_time = time.time()
total_duration = (end_time - start_time) / 60
# *********************************************** #
# STATISTICS
# *********************************************** #
log.info("# ======================= STATISTICS ======================= #")
log.info(f"TOTAL DURATION (seconds): {total_duration}")
log.info(f"TOTAL SOURCE RECORDS: {len(identities)}")
log.info(f"TOTAL PLANON RECORDS: {len(records)}")
# *********************************************** #
# CLEANUP
# *********************************************** #
chunk_size = 1000
syscodes = [record['Syscode'] for record in records]
chunked_records = [syscodes[i:i + chunk_size] for i in range(0, len(syscodes))]
'''{
"filter": {
"Syscode": {"ge": 1},
"Syscode": {"le": 100}
}
}'''
for chunk in chunked_records:
body = f'''{{
"filter": {{
"Syscode": {{"ge": {chunk[0]}}},
"Syscode": {{"le": {chunk[-1]}}}
}}
}}'''
# b'{"uuid":"334ead57-11a1-4e0f-a6bf-f010a075d055","message":"Execute on multiple BO\'s not implemented"}'
# response = session.post(url=f"{url}/execute/UsrEmployee/BomDelete", data=body)
response = session.post(url=f"{url}/read/UsrEmployee", data=body)
len(response.json()['records']) == chunk_size