Repository navigation
Expand file tree
/
Copy pathfetch_where.py
More file actions
192 lines (148 loc) · 5.65 KB
/
Copy pathfetch_where.py
File metadata and controls
192 lines (148 loc) · 5.65 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
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
180
181
182
183
184
185
186
187
188
189
190
191
192
"""Recursively call the Infor CSD FetchWhere API and dump the results to a CSV.
Usage:
python fetch_where.py [--config config/config.ini]
"""
import argparse
import configparser
import csv
import json
import os
import sys
from datetime import datetime
import requests
def load_config(config_path):
parser = configparser.ConfigParser()
parser.optionxform = str # preserve case of keys (payload field names)
if not parser.read(config_path):
raise FileNotFoundError(f"Config file not found: {config_path}")
config_dir = os.path.dirname(os.path.abspath(config_path))
ionapi_file = parser.get("ionapi", "file")
if not os.path.isabs(ionapi_file):
ionapi_file = os.path.join(config_dir, ionapi_file)
fw = parser["fetchwhere"]
fetchwhere = {
"CompanyNumber": fw.getint("CompanyNumber"),
"Operator": fw.get("Operator", fallback=""),
"TableName": fw.get("TableName"),
"WhereClause": fw.get("WhereClause", fallback=""),
"BatchSize": fw.getint("BatchSize"),
}
output_dir = parser.get("output", "directory")
if not os.path.isabs(output_dir):
output_dir = os.path.join(config_dir, output_dir)
return ionapi_file, fetchwhere, output_dir
def load_ionapi(ionapi_path):
with open(ionapi_path, "r", encoding="utf-8") as f:
return json.load(f)
def get_access_token(ionapi):
token_url = ionapi["pu"] + ionapi["ot"]
data = {
"grant_type": "password",
"username": ionapi["saak"],
"password": ionapi["sask"],
"client_id": ionapi["ci"],
"client_secret": ionapi["cs"],
}
scopes = ionapi.get("sc") or []
if scopes:
data["scope"] = " ".join(scopes)
resp = requests.post(token_url, data=data)
resp.raise_for_status()
return resp.json()["access_token"]
def build_fetchwhere_url(ionapi):
return (
ionapi["iu"].rstrip("/")
+ "/"
+ ionapi["ti"]
+ "/SX/rest/serviceinterface/proxy/FetchWhere"
)
def extract_records_and_restart_id(response_json):
"""FetchWhere wraps the result rows under a key whose name depends on the
table being queried, so find the first list-valued key rather than
assuming a fixed name. RestartRowID is always its own top-level key."""
restart_id = ""
records = []
for key, value in response_json.items():
if key.lower() == "restartrowid":
restart_id = value or ""
elif isinstance(value, list) and records == []:
records = value
return records, restart_id
def fetch_all_rows(session, url, fetchwhere, get_token):
rows = []
restart_id = ""
seen_restart_ids = set()
token = get_token()
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
page = 1
while True:
payload = dict(fetchwhere)
payload["RestartRowID"] = restart_id
resp = session.post(url, headers=headers, json=payload)
if resp.status_code == 401:
token = get_token()
headers["Authorization"] = f"Bearer {token}"
resp = session.post(url, headers=headers, json=payload)
resp.raise_for_status()
records, new_restart_id = extract_records_and_restart_id(resp.json())
rows.extend(records)
print(f" page {page}: fetched {len(records)} rows (total {len(rows)})")
if not records or not new_restart_id or new_restart_id in seen_restart_ids:
break
seen_restart_ids.add(new_restart_id)
restart_id = new_restart_id
page += 1
return rows
def write_csv(rows, output_dir, tenant, table_name):
os.makedirs(output_dir, exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"{tenant}_{table_name}_{timestamp}.csv"
path = os.path.join(output_dir, filename)
fieldnames = []
seen = set()
for row in rows:
for key in row.keys():
if key not in seen:
seen.add(key)
fieldnames.append(key)
with open(path, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
return path
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--config",
default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "config", "config.ini"),
help="Path to config.ini (default: config/config.ini)",
)
args = parser.parse_args()
ionapi_path, fetchwhere, output_dir = load_config(args.config)
ionapi = load_ionapi(ionapi_path)
url = build_fetchwhere_url(ionapi)
table_name = fetchwhere["TableName"]
print(f"Fetching table '{table_name}' from {url}")
print(f" CompanyNumber={fetchwhere['CompanyNumber']} Operator={fetchwhere['Operator']!r} "
f"WhereClause={fetchwhere['WhereClause']!r} BatchSize={fetchwhere['BatchSize']}")
session = requests.Session()
token_holder = {"token": None}
def get_token():
token_holder["token"] = get_access_token(ionapi)
return token_holder["token"]
rows = fetch_all_rows(session, url, fetchwhere, get_token)
if not rows:
print("No rows returned; no CSV written.")
return
path = write_csv(rows, output_dir, ionapi["ti"], table_name)
print(f"Wrote {len(rows)} rows to {path}")
if __name__ == "__main__":
try:
main()
except requests.HTTPError as e:
body = e.response.text if e.response is not None else ""
print(f"HTTP error: {e}\n{body}", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)