pyCurl - delete all files in WebDAV directory

74 Views Asked by At

I want to delete all files in a WebDav directory with pyCurl. I was able to delete one specific file with the following code:

def filedelete(url, filename, upload_user, upload_pw):
    c = pycurl.Curl()
    url = url + filename
    c.setopt(pycurl.URL, url)
    c.setopt(pycurl.CUSTOMREQUEST, "DELETE")
    c.setopt(pycurl.SSL_VERIFYPEER, 0)
    c.setopt(pycurl.SSL_VERIFYHOST, 0)
    c.setopt(pycurl.USERPWD, upload_user + ":" + upload_pw)

    c.perform()
    c.close()

For my understanding it is not possible to use wildcards in curl. So the only solution for this task is to read a list of all files in this directory and delete every file. How can I read the list of files and is it possible to send a list of filenames/urls with one command to reduce the load on the server?

Thanks in advance!

1

There are 1 best solutions below

0
nico On BEST ANSWER

I was able to create a solution by myself with the following functions. Perhaps it is not the most elegant solution but it is working for me.

The function filedelete deletes all files on the WebDav Url url. For this the function calls first the function listfiles. This function creates an array of all files and folders on the url. After that each file is deleted individually in the function filedelete.

def filedelete(url, upload_user, upload_pw):
    parsed_uri = urlparse(url)
    host = '{uri.scheme}://{uri.netloc}'.format(uri=parsed_uri)
    print(host)

    c = pycurl.Curl()

    # Get all files in directory
    files = listfiles(url, upload_user, upload_pw)

    print(files)

    # Delete all files in directory
    for url in files:
        url = host + url
        c.setopt(pycurl.URL, url)
        c.setopt(pycurl.CUSTOMREQUEST, "DELETE")
        c.setopt(pycurl.SSL_VERIFYPEER, 0)
        c.setopt(pycurl.SSL_VERIFYHOST, 0)
        c.setopt(pycurl.USERPWD, upload_user + ":" + upload_pw)
        c.perform()
    
    c.close()
    
    return True

def listfiles(url, upload_user, upload_pw):
    buffer = BytesIO()
    c = pycurl.Curl()
    c.setopt(pycurl.URL, url)
    c.setopt(pycurl.CUSTOMREQUEST, "PROPFIND")
    c.setopt(c.WRITEDATA, buffer)
    c.setopt(pycurl.SSL_VERIFYPEER, 0)
    c.setopt(pycurl.SSL_VERIFYHOST, 0)
    c.setopt(pycurl.USERPWD, upload_user + ":" + upload_pw)
    c.perform()
    c.close()

    body = buffer.getvalue().decode('iso-8859-1')
    
    # create element tree object
    tree = ET.ElementTree(ET.fromstring(body))
    root = tree.getroot()
    
    files = []
    for items in root.findall('./{DAV:}response/{DAV:}href'):
        files.append(items.text)

    files.pop(0)
    files.reverse()

    return files