|
| 1 | +""" |
| 2 | +Downloads files modified in the last 24 hours from the specified ftp server.""" |
| 3 | + |
| 4 | +# standard |
| 5 | +import datetime |
| 6 | +import functools |
| 7 | +from os import path |
| 8 | + |
| 9 | +# third party |
| 10 | +import paramiko |
| 11 | + |
| 12 | + |
| 13 | +def print_callback(filename, bytes_so_far, bytes_total): |
| 14 | + """Log file transfer progress""" |
| 15 | + rough_percent_transferred = int(100 * (bytes_so_far / bytes_total)) |
| 16 | + if (rough_percent_transferred % 25) == 0: |
| 17 | + print(f'{filename} transfer: {rough_percent_transferred}%') |
| 18 | + |
| 19 | + |
| 20 | +def get_files_from_dir(sftp, out_path): |
| 21 | + """Download files from sftp server that have been uploaded in last day |
| 22 | + Args: |
| 23 | + sftp: SFTP Session from Paramiko client |
| 24 | + out_path: Path to local directory into which to download the files |
| 25 | + """ |
| 26 | + |
| 27 | + current_time = datetime.datetime.now() |
| 28 | + |
| 29 | + # go through files in recieving dir |
| 30 | + filepaths_to_download = {} |
| 31 | + for fileattr in sftp.listdir_attr(): |
| 32 | + file_time = datetime.datetime.fromtimestamp(fileattr.st_mtime) |
| 33 | + filename = fileattr.filename |
| 34 | + if current_time - file_time < datetime.timedelta(days=1) and \ |
| 35 | + not path.exists(path.join(out_path, filename)): |
| 36 | + filepaths_to_download[filename] = path.join(out_path, filename) |
| 37 | + |
| 38 | + # make sure we don't download more than 2 files per day |
| 39 | + assert len(filepaths_to_download) <= 2, "more files dropped than expected" |
| 40 | + |
| 41 | + # download! |
| 42 | + for infile, outfile in filepaths_to_download.items(): |
| 43 | + callback_for_filename = functools.partial(print_callback, infile) |
| 44 | + sftp.get(infile, outfile, callback=callback_for_filename) |
| 45 | + |
| 46 | + |
| 47 | +def download(out_path, ftp_conn): |
| 48 | + """Downloads files necessary to create CHC signal from ftp server. |
| 49 | + Args: |
| 50 | + out_path: Path to local directory into which to download the files |
| 51 | + ftp_conn: Dict containing login credentials to ftp server |
| 52 | + """ |
| 53 | + |
| 54 | + # open client |
| 55 | + try: |
| 56 | + client = paramiko.SSHClient() |
| 57 | + client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) |
| 58 | + |
| 59 | + client.connect(ftp_conn["host"], username=ftp_conn["user"], |
| 60 | + password=ftp_conn["pass"][1:] + ftp_conn["pass"][0], |
| 61 | + port=ftp_conn["port"], |
| 62 | + allow_agent=False, look_for_keys=False) |
| 63 | + sftp = client.open_sftp() |
| 64 | + |
| 65 | + sftp.chdir('/dailycounts/All_Outpatients_By_County') |
| 66 | + get_files_from_dir(sftp, out_path) |
| 67 | + |
| 68 | + sftp.chdir('/dailycounts/Covid_Outpatients_By_County') |
| 69 | + get_files_from_dir(sftp, out_path) |
| 70 | + |
| 71 | + finally: |
| 72 | + if client: |
| 73 | + client.close() |
0 commit comments