pysftp разбивает огромный файл, влияя на производительность - PullRequest
0 голосов
/ 07 августа 2020

Я пытаюсь разбить огромный файл, находящийся в каталоге SFTP-сервера, на 3 меньших файла равного размера с помощью приведенного ниже кода (используя pysftp). Код работает нормально, но проблема в том, что он занимает много времени и влияет на производительность, чтобы разделить файл размером 25 МБ, требуется почти 25 секунд.

Не могли бы вы сообщить мне, как я могу настроить код для повышения производительности, поскольку я новичок в разработке Python. Я выполняю код ниже в структуре FaaS (Oracle Cloud Infrastructure - Functions).

def filesplit(*args):
    try:
        logging.getLogger().info("------------ Started filesplit function execution ------------")
        sftphostname = args[1]
        sftpusername = args[0]
        sftpport = int(args[2])
        sftpenv = args[3]
        source_filesize = int(args[4])
        source_filename = args[5]
        source_filedir = args[6]
        target_filedir = args[7]
        threshold_splitsize = int(args[8])
        responselist = []
        responsedict = {}

        if source_filesize < threshold_splitsize:
            responselist.append({'fileName' : source_filename})
        else:
            sftpkeypath = sftpenv + '_sftp_private_key.pem'
            file1_content = []
            file2_content = []
            file3_content = []
            loc_counter = 0
            match_header_footer = ['EDI_DC40','ATYPE3000', 'BTYPE3000']
            match_line_records = ['CTYPE3000', 'DTYPE3000', 'ETYPE3000',
                                  'FTYPE3000']
            print(source_filedir+source_filename)
            with pysftp.Connection(host=sftphostname, username=sftpusername, port=sftpport, private_key=sftpkeypath) as sftp:
                with sftp.open(source_filedir+source_filename, bufsize=32768) as file:
                    for line in file:
                        linestring = line.strip()
                        if any(linestring.startswith(headerfooter) for headerfooter in match_header_footer):
                            file1_content.append(linestring + '\n')
                            file2_content.append(linestring + '\n')
                            file3_content.append(linestring + '\n')
                        elif linestring.startswith('Y_TYPE3000'):
                            loc_counter += 1
                        if any(linestring.startswith(linerecord) for linerecord in match_line_records):
                            if loc_counter % 3 == 0:
                                file1_content.append(linestring + '\n')
                                continue
                            if loc_counter % 3 == 1:
                                file2_content.append(linestring + '\n')
                                continue
                            file3_content.append(linestring + '\n')
                if loc_counter > 0:
                    target_file1 = '1_' + source_filename
                    target_file2 = '2_' + source_filename
                    target_file3 = '3_' + source_filename
                    sftp.putfo(StringIO(''.join(file1_content)), target_filedir + target_file1)
                    responselist.append({'fileName' : target_file1})
                    sftp.putfo(StringIO(''.join(file2_content)), target_filedir + target_file2)
                    responselist.append({'fileName' : target_file2})
                    sftp.putfo(StringIO(''.join(file3_content)), target_filedir + target_file3)
                    responselist.append({'fileName' : target_file3})
        return responselist
        logging.getLogger().info("------------ Finished filesplit function execution------------")
    except (custexcep.GenericError) as ex:
        raise custexcep.GenericError(ex.get_errorcode(), ex.get_message())
    except (Exception) as ex:
        #logging.getLogger().exception(ex)
        raise custexcep.GenericError("GEN-100 : Unhandled Exception" , tracebk.format_exc())
...