Skip to content

Commit 8dc6780

Browse files
vvgrem@gmail.comvvgrem@gmail.com
authored andcommitted
SharePoint example: download file in chunks (#277)
1 parent ef216aa commit 8dc6780

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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))

office365/sharepoint/userprofiles/profileLoader.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def get_profile_loader(context):
2121
return result
2222

2323
def get_user_profile(self):
24-
result = UserProfile(self.context)
24+
result = UserProfile(self.context, ResourcePath("GetUserProfile", self.resource_path))
2525
qry = ServiceOperationQuery(self, "GetUserProfile", None, None, None, result)
2626
self.context.add_query(qry)
2727
return result

0 commit comments

Comments
 (0)