Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

1. added possibility to download file with context manager #240

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
32 changes: 32 additions & 0 deletions examples/sharepoint/files/download_file_from_url_app_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# example that downloads file test.pdf from document library with name "Software".
# Current example uses App authentication. See examples "connect_with_app.py"
# For detailed info read official Microsoft article: Granting access using SharePoint App-Only

import os
import tempfile
import time

from office365.sharepoint.files.file import File
from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.authentication_context import AuthenticationContext

site_url = "https://company.sharepoint.com/sites/my-team/"
app_principal = {
'client_id': 'client ID',
'client_secret': 'client Secret',
}

context_auth = AuthenticationContext(url=site_url)
context_auth.acquire_token_for_app(client_id=app_principal['client_id'], client_secret=app_principal['client_secret'])

abs_file_url = site_url + "Software/test.pdf"
ctx = ClientContext(site_url, context_auth)
file_name = os.path.basename(abs_file_url)

with tempfile.TemporaryDirectory() as local_path:
with open(os.path.join(local_path, file_name), 'wb') as local_file:
file = File.from_url(abs_file_url).with_context(ctx).download(local_file).execute_query()
print("'{0}' file has been downloaded into {1}".format(file.serverRelativeUrl, local_file.name))

# give some time before delete file :)
time.sleep(100)
11 changes: 11 additions & 0 deletions office365/sharepoint/base_entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ def with_credentials(self, credentials):
self.context.with_credentials(credentials)
return self

def with_context(self, ctx):
self.context = ctx
return self

def execute_query(self):
self.context.execute_query()
return self
Expand All @@ -39,6 +43,13 @@ def context(self):
"""
return self._context

@context.setter
def context(self, ctx):
"""
:rtype: office365.sharepoint.client_context.ClientContext
"""
self._context = ctx

@property
def entity_type_name(self):
if self._entity_type_name is None:
Expand Down