'Import CSV files from remote servers'

def import_remote_csv(self, url, prefix, resource, stylesheet):

    extension = url.split('.')[(-1)]
    if (extension not in ('csv', 'zip')):
        current.log.error(('error    importing    remote    file    %s:    invalid    extension' % url))
        return
    cwd = os.getcwd()
    TEMP = os.path.join(cwd, 'temp')
    if (not os.path.exists(TEMP)):
        import tempfile
        TEMP = tempfile.gettempdir()
    tempPath = os.path.join(TEMP, 'remote_csv')
    if (not os.path.exists(tempPath)):
        try:
            os.mkdir(tempPath)
        except OSError:
            current.log.error(('Unable    to    create    temp    folder    %s!' % tempPath))
            return
    filename = url.split('/')[(-1)]
    if (extension == 'zip'):
        filename = filename.replace('.zip', '.csv')
    if os.path.exists(os.path.join(tempPath, filename)):
        current.log.warning(('Using    cached    copy    of    %s' % filename))
    else:
        os.chdir(tempPath)
        try:
            _file = fetch(url)
        except urllib2.URLError as exception:
            current.log.error(exception)
            os.chdir(cwd)
            return
        if (extension == 'zip'):
            import zipfile
            try:
                myfile = zipfile.ZipFile(StringIO(_file))
            except zipfile.BadZipfile as exception:
                current.log.error(exception)
                os.chdir(cwd)
                return
            files = myfile.infolist()
            for f in files:
                filename = f.filename
                extension = filename.split('.')[(-1)]
                if (extension == 'csv'):
                    _file = myfile.read(filename)
                    _f = open(filename, 'w')
                    _f.write(_file)
                    _f.close()
                    break
            myfile.close()
        else:
            f = open(filename, 'w')
            f.write(_file)
            f.close()
        os.chdir(cwd)
    task = [1, prefix, resource, os.path.join(tempPath, filename), os.path.join(current.request.folder, 'static', 'formats', 's3csv', prefix, stylesheet), None]
    self.execute_import_task(task)
