|
| 1 | +import os |
| 2 | +import tempfile |
| 3 | + |
| 4 | +from office365.runtime.http.request_options import RequestOptions |
| 5 | +from settings import settings |
| 6 | + |
| 7 | +from office365.runtime.auth.client_credential import ClientCredential |
| 8 | +from office365.sharepoint.client_context import ClientContext |
| 9 | + |
| 10 | + |
| 11 | +def download_file(context, download_url, file_object, chunk_downloaded=None, chunk_size=1024 * 1024): |
| 12 | + """ |
| 13 | +
|
| 14 | + :type context: office365.sharepoint.client_context.ClientContext |
| 15 | + :type download_url: str |
| 16 | + :type file_object: typing.IO |
| 17 | + :type chunk_downloaded: (int)->None or None |
| 18 | + :type chunk_size: int |
| 19 | + """ |
| 20 | + |
| 21 | + request = RequestOptions( |
| 22 | + r"{0}web/getFileByServerRelativeUrl('{1}')/\$value".format(ctx.service_root_url(), download_url)) |
| 23 | + request.stream = True |
| 24 | + response = context.execute_request_direct(request) |
| 25 | + response.raise_for_status() |
| 26 | + bytes_read = 0 |
| 27 | + for chunk in response.iter_content(chunk_size=chunk_size): |
| 28 | + bytes_read += len(chunk) |
| 29 | + if callable(chunk_downloaded): |
| 30 | + chunk_downloaded(bytes_read) |
| 31 | + file_object.write(chunk) |
| 32 | + |
| 33 | + |
| 34 | +def print_download_progress(offset): |
| 35 | + print("Downloaded '{0}' bytes...".format(offset)) |
| 36 | + |
| 37 | + |
| 38 | +site_url = settings.get('url') + "/sites/team" |
| 39 | +credentials = ClientCredential(settings.get('client_credentials').get('client_id'), |
| 40 | + settings.get('client_credentials').get('client_secret')) |
| 41 | +ctx = ClientContext(site_url).with_credentials(credentials) |
| 42 | + |
| 43 | +file_url = f'/sites/team/Shared Documents/big_buck_bunny.mp4' |
| 44 | +local_file_name = os.path.join(tempfile.mkdtemp(), os.path.basename(file_url)) |
| 45 | +with open(local_file_name, "wb") as local_file: |
| 46 | + download_file(ctx, file_url, local_file, print_download_progress) |
| 47 | +print("[Ok] file has been downloaded: {0}".format(local_file_name)) |
0 commit comments