-
Notifications
You must be signed in to change notification settings - Fork 0
/
auto-client.py
161 lines (139 loc) · 4.56 KB
/
auto-client.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
# Author: Jake W
from curses.ascii import isspace
from importlib.metadata import files
import ftplib
import os
import re
import csv
from datetime import date
ftp = ftplib.FTP()
def isFloat(num):
try:
float(num)
return True
except ValueError:
return False
def checkHeaders(valid):
headerTemplate = ['batch_id', 'timestamp', 'reading1', 'reading2', 'reading3', 'reading4', 'reading5', 'reading6',
'reading7', 'reading8', 'reading9', 'reading10']
if data[0] != headerTemplate:
valid = False
return valid
def checkBatchIDDuplicates(valid):
batchIDs = []
for row in range(1, len(data)):
if data[row][0] in batchIDs:
valid = False
else:
batchIDs.append(data[row][0])
return valid
def checkValues(valid):
for row in data:
for item in row:
if len(item) == 0 or item.isspace():
valid = False
else:
if isFloat(item) and not item.isdigit() and not item.isalnum():
if float(item) >= 10:
valid = False
elif(format(float(item),".3f") != item): # Check if 3dp
valid = False
return valid
def checkMalformed(valid):
for row in data:
rowItemCounter = 0 # Count items in row
for item in row:
rowItemCounter = rowItemCounter + 1
if(rowItemCounter != 12): # Not enough columns for correct format!
valid = False
return valid
def connectServer():
ip = "127.0.0.1"
port = 21
try:
msg = ftp.connect(ip,port)
print(msg)
loginServer()
except:
print("Unable to connect")
def loginServer():
user = "user"
password = "12345"
try:
msg = ftp.login(user,password)
print(msg)
downloadFile()
except Exception as e:
print("ERROR: ", e)
print("Unable to login")
def downloadFile():
canDownload = True
if canDownload == True:
filesFound = 0
formattedDate = date.today().strftime('%Y%m%d')
print("Date: "+formattedDate)
ftp.cwd('/ftpserver/ftpFiles')
if not os.path.exists('temp-downloads'):
os.mkdir('temp-downloads')
os.chdir('temp-downloads')
for filename in ftp.nlst():
if re.search("MED_DATA_"+formattedDate+"[0-9]{6}.csv", filename):
filesFound += 1
print("Downloading " + filename)
with open(filename, 'wb') as file_handle:
try:
ftp.retrbinary("RETR " + filename, file_handle.write)
except:
print("Unable to download file")
if filesFound > 0:
print("Downloaded "+str(filesFound)+" files")
print("Files from requested date downloaded")
os.chdir('..')
validateFile()
else:
print("That file doesn't exist!")
os.chdir('..')
else:
print("You must enter a date!")
def validateFile():
print("Validating files...")
directory = "temp-downloads"
if not os.path.exists('temp-downloads'):
os.mkdir('temp-downloads')
filesValidated = 0
for filename in os.listdir(directory):
valid = True
openFile = open("temp-downloads/"+filename, "rt")
global data
data = list(csv.reader(openFile))
openFile.close()
# VALIDATION
valid = checkHeaders(valid)
valid = checkBatchIDDuplicates(valid)
valid = checkValues(valid)
valid = checkMalformed(valid)
filesValidated += 1
if valid == False:
print(filename+": FILE INVALID")
os.remove("temp-downloads/"+filename)
else:
print(filename+": FILE VALID")
fileDate = date.today().strftime('%Y/%m/%d')
newpath = "validated-files/"+fileDate
if not os.path.exists(newpath):
os.makedirs(newpath)
os.replace(os.path.join("temp-downloads", filename), os.path.join(newpath, filename))
if filesValidated > 0:
print("Checked "+str(filesValidated)+" files")
else:
print("No files downloaded")
print("You must download files before validating")
def closeConnection():
try:
print("Closing connection...")
print(ftp.quit())
except:
print("Unable to disconnect")
def exit():
quit()
connectServer()