import time
from datacloud.key_manager.key_helpers import get_key


def connect_and_login(partner, keys=None):
    from ftplib import FTP_TLS
    keys = keys or get_key('partners_ftp')
    partner_keys = keys[partner]
    server = partner_keys['ftp']
    count = 5
    ftp = None
    while count > 0:
        try:
            ftp = FTP_TLS(server)
            break
        except Exception:
            time.sleep(3)
            count -= 1
    if ftp is None:
        ftp = FTP_TLS(server)
    ftp.login(partner_keys['login'], partner_keys['password'])
    return ftp
