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 | def getMongoDB(**context):
token = context.get("ti").xcom_pull(key="token")
response = requests.get(
url=f"{dRoW_api_end_url}/api/module/nd201907/document-data?from=1665845580212&documentId=5ffd229d55bd1f019c188ca3",
headers={
"x-access-token": f"Bearer {token}",
"ICWPxAccessKey": "nd@201907ICWP_[1AG:4UdI){n=b~"
}
)
#print('got_data')
RISC_Data = json.loads(response.text)
Mapping= {"F2. 監理代表 Checked by SupD on Date" : "f2_checked_by_supd_on_date",
"A1a 巡查日期 Inspection Date" : "a01a_inspection_date",
"D4 Submission Date" : "d4_submission_date",
"A2 每日/每週? Daily or Weekly?": "a2_daily_or_weekly"
}
#print('start transform')
host = 'drowdatewarehouse.crlwwhgepgi7.ap-east-1.rds.amazonaws.com'
# User name of the database server
dbUserName = 'dRowAdmin'
# Password for the database user
dbUserPassword = 'drowsuper'
# Name of the database
database = 'drowDateWareHouse'
# Character set
charSet = "utf8mb4"
port = "5432"
# #cursor Type
# cusrsorType = pymysql.cursors.DictCursor
#create_engine('mysql+mysqldb://root:password@localhost:3306/mydbname', echo = False)
conn_string = ('postgres://' +
dbUserName + ':' +
dbUserPassword +
'@' + host + ':' + port +
'/' + database)
# df = context.get("ti").xcom_pull(key="InsertData")
# print(df)
# conn_string = 'postgres://user:password@host/data1'
db = create_engine(conn_string)
conn = db.connect()
#print('db connected')
with conn as conn:
df = pd.DataFrame()
for x in RISC_Data:
#print(x)
df_nested_list = json_normalize(x['data'])
#print('process 1')
df2 = df_nested_list.reindex(columns=Mapping.keys())
df2["report_name"] = df2["A1a 巡查日期 Inspection Date"].astype(str).str[:10] + df2["A2 每日/每週? Daily or Weekly?"]
if df2['F2. 監理代表 Checked by SupD on Date'].isnull().bool():
df2['report_complete_or_incomplete'] = 'incomplete'
else:
df2['report_complete_or_incomplete'] = 'complete'
if not df2['F2. 監理代表 Checked by SupD on Date'].isnull().bool() and not df2['D4 Submission Date'].isnull().bool() and (df2["F2. 監理代表 Checked by SupD on Date"].astype('datetime64[ns]') < df2["D4 Submission Date"].astype('datetime64[ns]')).bool():
df2['nc_report'] = True
else:
df2['nc_report'] = False
if (not df2['F2. 監理代表 Checked by SupD on Date'].isnull().bool() and not df2['A1a 巡查日期 Inspection Date'].isnull().bool()):
df2['complete_time_in_days'] = (((df2['F2. 監理代表 Checked by SupD on Date'].astype('datetime64[ns]') -
df2['A1a 巡查日期 Inspection Date'].astype('datetime64[ns]'))/ np.timedelta64(1, 'h'))/24).round(2)
if df2['complete_time_in_days'].isnull().bool() or df2['complete_time_in_days'].lt(0).bool():
df2['complete_time_in_days'] = 0
else:
df2['complete_time_in_days'] = 0
# if(not df2["C02 - Survey Checked on Date Time"].isnull().bool() and not df2["A10 - Request Submission Date Time"].isnull().bool() and ((df2["C02 - Survey Checked on Date Time"].astype('datetime64[ns]') < df2["A10 - Request Submission Date Time"].astype('datetime64[ns]')).bool())):
# print((df2["C02 - Survey Checked on Date Time"].astype('datetime64[ns]') < df2["A10 - Request Submission Date Time"].astype('datetime64[ns]')))
# else:
# print((df2["C02 - Survey Checked on Date Time"].astype('datetime64[ns]') < df2["A10 - Request Submission Date Time"].astype('datetime64[ns]')))
# if (not df2["C02 - Survey Checked on Date Time"].isnull().bool() and (not df2["A10 - Request Submission Date Time"].isnull().bool()) and (df2["C02 - Survey Checked on Date Time"].astype('datetime64[ns]') < df2["A10 - Request Submission Date Time"].astype('datetime64[ns]')).bool()):
# df2['nc_report'] = True
# else:
# df2['nc_report'] = False
# if (not df2["C02 - Survey Checked on Date Time"].isnull().bool() and not df2["A10 - Request Submission Date Time"].isnull().bool() and (((df2["C02 - Survey Checked on Date Time"].astype('datetime64[ns]') - df2["A10 - Request Submission Date Time"].astype('datetime64[ns]'))) < pd.Timedelta(24, unit='h')).bool()):
# df2['urgent_report'] = True
# else:
# df2['urgent_report'] = False
# if (not df2['E01 - Received on behalf of Contractor on Date Time'].isnull().bool() and not df2['A10 - Request Submission Date Time'].isnull().bool()):
# df2['elapsed_time'] = (((df2['E01 - Received on behalf of Contractor on Date Time'].astype('datetime64[ns]') -
# df2['A10 - Request Submission Date Time'].astype('datetime64[ns]'))/ np.timedelta64(1, 'h'))/24).round(2)
# if df2['elapsed_time'].isnull().bool() or df2['elapsed_time'].lt(0).bool():
# df2['elapsed_time'] = 0
# else:
# df2['elapsed_time'] = 0
# if (not df2["C02 - Survey Checked on Date Time"].isnull().bool() and not df2["D01 - Countersigned on Date Time"].isnull().bool() and (((df2["D01 - Countersigned on Date Time"].astype('datetime64[ns]') - df2["C02 - Survey Checked on Date Time"].astype('datetime64[ns]')))>= pd.Timedelta(24, unit='h')).bool()):
# df2['overdue_report'] = True
# else:
# df2['overdue_report'] = False
# if (not df2["C02 - Survey Checked on Date Time"].isnull().bool() and not df2["C12 Time Pass to Senior or Contractor"].isnull().bool() and (((df2["C12 Time Pass to Senior or Contractor"].astype('datetime64[ns]') - df2["C02 - Survey Checked on Date Time"].astype('datetime64[ns]')))>= pd.Timedelta(24, unit='h')).bool()):
# df2['delayed_approval_report'] = True
# else:
# df2['delayed_approval_report'] = False
# if ((df2['A01a - Request No. Revision']=="-A").bool()):
# df2['fail_in_first_inspection'] = True
# else:
# df2['fail_in_first_inspection'] = False
# if (not df2["C12 Time Pass to Senior or Contractor"].isnull().bool() and not df2["C02 - Survey Checked on Date Time"].isnull().bool() and not df2["E01 - Received on behalf of Contractor on Date Time"].isnull().bool()):
# df2['complete_incomplete_outstanding_report'] = 'complete'
# elif ((df2["C12 Time Pass to Senior or Contractor"].isnull().bool() or df2["E01 - Received on behalf of Contractor on Date Time"].isnull().bool()) and not df2["C02 - Survey Checked on Date Time"].isnull().bool()):
# df2['complete_incomplete_outstanding_report'] = 'in-complete'
# elif ((not df2["C12 Time Pass to Senior or Contractor"].isnull().bool() or df2["E01 - Received on behalf of Contractor on Date Time"].isnull().bool()) and df2["C02 - Survey Checked on Date Time"].isnull().bool()):
# df2['complete_incomplete_outstanding_report'] = 'outstanding'
# else:
# df2['complete_incomplete_outstanding_report'] = 'outstanding'
#print('process 2')
df2.rename(columns=Mapping, inplace=True)
# df2.to_sql('table_temp', engine, if_exists='replace')
# context["ti"].xcom_push(key="InsertData", value=df2)
#print('loading into DB')
# our dataframe
# data = {'Name': ['Tom', 'dick', 'harry'],
# 'Age': [22, 21, 24]}
# # Create DataFrame
# df = pd.DataFrame(data)
# conn = psycopg2.connect(conn_string
# )
# conn.autocommit = True
# cursor = conn.cursor()
df = df.append(df2)
df['a01a_inspection_date']=df['a01a_inspection_date'].apply(pd.to_datetime)
df['d4_submission_date']=df['d4_submission_date'].apply(pd.to_datetime)
df['f2_checked_by_supd_on_date']=df['f2_checked_by_supd_on_date'].apply(pd.to_datetime)
df.to_sql('nd201907_cleansing', con=conn, if_exists='replace', index= False)
|