-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupload_payments.py
73 lines (51 loc) · 2.25 KB
/
upload_payments.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
import psycopg2
import datetime
import os
import csv
from ftp_dowload import dowload_new_payments
def update_fact_payments():
write_conn = psycopg2.connect(dbname='dwh', user='dwh_krasnoyarsk',
password='dwh_krasnoyarsk_uBPaXNSx', host='de-edu-db.chronosavant.ru')
write_cursor = write_conn.cursor()
#Загрузка новых файлов
dowload_new_payments()
directory = 'payments/'
files = os.listdir(directory)
wrong_lines = []
write_cursor.execute("SELECT MAX(transaction_id) FROM fact_payments")
res = write_cursor.fetchall()
if res != [(None,)]:
transaction_id = res[-1][0] + 1
else:
transaction_id = 0
# print(files)
for file in files:
with open('payments/'+file, newline='') as f:
spamreader = csv.reader(f)
for row in spamreader:
try:
#выборка данных
data = row[0].split('\t')
card_num = int(data[1])
transaction_amt = float(data[2])
transaction_dt = datetime.datetime.strptime(data[0], '%d.%m.%Y %H:%M:%S')
# print((transaction_id, card_num, transaction_amt, transaction_dt))
#запись данных
write_cursor.execute('INSERT INTO fact_payments VALUES(%s, %s, %s, %s);',
(transaction_id, card_num, transaction_amt, transaction_dt))
write_conn.commit()
transaction_id += 1
except Exception as e:
wrong_lines.append((transaction_id, card_num, transaction_amt, transaction_dt))
os.remove('payments/'+file)
#возможно стоити перенести в другое место и добавить проверку на ошибки
if files != []:
with open('last_payment.txt', 'w') as f:
f.write(files[-1])
write_cursor.close()
write_conn.close()
if wrong_lines != []:
print('Problems with files:' + '\n'.join(wrong_lines))
return wrong_lines
if __name__ == '__main__':
update_fact_payments()