weaverk
weaverk

Reputation: 113

how to download a file using python-sharepoint library

I am using this library https://github.com/ox-it/python-sharepoint to connect to a SharePoint list. I can authenticate, access the list fields, including the full URL to the file I want, and it seems this library does have is_file() and open() methods however, I do not understand how to call these. Any advice is appreciated!

from sharepoint import SharePointSite, basic_auth_opener 

opener = basic_auth_opener(server_url, "domain/username", "password")
site = SharePointSite(server_url, opener)

sp_list = site.lists['ListName']
for row in sp_list.rows:
       print row.id, row.Title, row.Author['name'], row.Created, row.EncodedAbsUrl
       #download file
       #row.open() ??

To quote from ReadMe file:

Support for document libraries is limited, but SharePointListRow objects do support a is_file() method and an open() method for accessing file data.

Upvotes: 5

Views: 19745

Answers (1)

unconditional
unconditional

Reputation: 7646

Basically you call these methods on the list row (which is of type SharePointListRow). The open() method is actually the method of urllib2's opener, which you usually use like so:

import urllib2
opener = urllib2.build_opener()
response = opener.open('http://www.example.com/')
print ('READ CONTENTS:', response.read())
print ('URL          :', response.geturl())
# ....

So you should be able to use it like this (I don't have any Sharepoint site to check this though):

from sharepoint import SharePointSite, basic_auth_opener 

opener = basic_auth_opener(server_url, "domain/username", "password")
site = SharePointSite(server_url, opener)

sp_list = site.lists['ListName']
for row in sp_list.rows():                # <<<
   print row.id, row.Title, row.Author['name'], row.Created, row.EncodedAbsUrl
   # download file here 

   print ( "This row: ", row.name() )     # <<<
   if row.is_file():                      # <<<
      response = row.open()               # <<<
      file_data = response.read()         # <<<

      # process the file data, e.g. write to disk

Upvotes: 3

Related Questions