Skip to content

Commit

Permalink
examples updates
Browse files Browse the repository at this point in the history
  • Loading branch information
vgrem committed Feb 17, 2024
1 parent 6a16c8f commit a1bf24e
Show file tree
Hide file tree
Showing 18 changed files with 170 additions and 72 deletions.
1 change: 1 addition & 0 deletions examples/data/report '123.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
123
Empty file.
15 changes: 10 additions & 5 deletions examples/onedrive/files/upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,17 @@
"""

from office365.graph_client import GraphClient
from tests import test_user_principal_name_alt
from tests.graph_case import acquire_token_by_client_credentials
from tests import (
test_client_id,
test_client_secret,
test_tenant,
test_user_principal_name_alt,
)

client = GraphClient(acquire_token_by_client_credentials)
client = GraphClient.with_client_secret(test_tenant, test_client_id, test_client_secret)
folder = client.users.get_by_principal_name(test_user_principal_name_alt).drive.root

local_path = "../../data/Financial Sample.xlsx"
# local_path = "../../data/Financial Sample.xlsx"
local_path = "../../data/countries.json"
file = folder.upload_file(local_path).execute_query()
print(f"File {file.web_url} has been uploaded")
print("File {0} has been uploaded".format(file.web_url))
10 changes: 6 additions & 4 deletions examples/sharepoint/files/download.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@
from tests import test_client_credentials, test_team_site_url

ctx = ClientContext(test_team_site_url).with_credentials(test_client_credentials)
file_url = "Shared Documents/big_buck_bunny.mp4"
# file_url = "Shared Documents/!2022/Financial Sample.xlsx"
# file_url = "Shared Documents/Sample.pdf"
# file_url = "Shared Documents/big_buck_bunny.mp4"
# file_url = "Shared Documents/Financial Sample.xlsx"
file_url = "Shared Documents/report '123.csv"
download_path = os.path.join(tempfile.mkdtemp(), os.path.basename(file_url))
with open(download_path, "wb") as local_file:
file = (
ctx.web.get_file_by_server_relative_url(file_url)
ctx.web.get_file_by_server_relative_path(file_url)
.download(local_file)
.execute_query()
)
print("[Ok] file has been downloaded into: {0}".format(download_path))
print("[Ok] file has been downloaded into: {0}".format(download_path))
22 changes: 22 additions & 0 deletions examples/sharepoint/files/download_deprecated.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""
Demonstrates how to download a file from SharePoint site
Note: this method is considered a deprecated approach nowadays!
Refer download.py which demonstrates how to download a file
"""
import os
import tempfile

from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File
from tests import test_client_credentials, test_team_site_url

ctx = ClientContext(test_team_site_url).with_credentials(test_client_credentials)
file_url = "Shared Documents/Sample.pdf"
# file_url = "Shared Documents/report '123.csv"
download_path = os.path.join(tempfile.mkdtemp(), os.path.basename(file_url))
with open(download_path, "wb") as local_file:
file = ctx.web.get_file_by_server_relative_url(file_url).get().execute_query()
resp = File.open_binary(ctx, file.properties["ServerRelativeUrl"])
resp.raise_for_status()
local_file.write(resp.content)
print("[Ok] file has been downloaded into: {0}".format(download_path))
11 changes: 4 additions & 7 deletions examples/sharepoint/files/upload.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""
Demonstrates how to upload a small files (up to 4MB in size)
"""
import os

from office365.sharepoint.client_context import ClientContext
from tests import test_team_site_url, test_user_credentials
Expand All @@ -10,10 +9,8 @@

list_title = "Documents"
folder = ctx.web.lists.get_by_title(list_title).root_folder
path = "../../data/Financial Sample.csv"
# with open(path, "rb") as f:
# file = folder.files.upload(f).execute_query()
with open(path, "r") as content_file:
file_content = content_file.read().encode("utf-8-sig")
file = folder.upload_file(os.path.basename(path), file_content).execute_query()
# path = "../../data/Financial Sample.csv"
path = "../../data/report '123.csv"
with open(path, "rb") as f:
file = folder.files.upload(f).execute_query()
print("File has been uploaded into: {0}".format(file.serverRelativeUrl))
17 changes: 17 additions & 0 deletions examples/sharepoint/files/upload_csv.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
"""
Demonstrates how to upload a CSV file to a SharePoint site
"""
import os

from office365.sharepoint.client_context import ClientContext
from tests import test_team_site_url, test_user_credentials

ctx = ClientContext(test_team_site_url).with_credentials(test_user_credentials)

list_title = "Documents"
folder = ctx.web.lists.get_by_title(list_title).root_folder
path = "../../data/Financial Sample.csv"
with open(path, "r") as content_file:
file_content = content_file.read().encode("utf-8-sig")
file = folder.upload_file(os.path.basename(path), file_content).execute_query()
print("File has been uploaded into: {0}".format(file.serverRelativeUrl))
10 changes: 5 additions & 5 deletions examples/sharepoint/listitems/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
"""

from office365.sharepoint.client_context import ClientContext
from tests import test_client_credentials, test_team_site_url
from tests import test_client_credentials, test_site_url

ctx = ClientContext(test_team_site_url).with_credentials(test_client_credentials)
ctx = ClientContext(test_site_url).with_credentials(test_client_credentials)
result = (
ctx.web.lists.get_by_title("Site Pages")
.items.filter("ID eq 135 AND RequestType eq 'Standard'")
.get()
ctx.web.lists.get_by_title("Documents")
.items.get()
.filter("ID lt 100")
.execute_query()
)
for item in result:
Expand Down
18 changes: 18 additions & 0 deletions examples/sharepoint/listitems/filter_by_filename.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"""
Demonstrates how to apply filtering to list collection
In the provided example only the user defined lists are getting returned
"""

from office365.sharepoint.client_context import ClientContext
from tests import test_client_credentials, test_site_url, test_team_site_url

ctx = ClientContext(test_site_url).with_credentials(test_client_credentials)
result = (
ctx.web.lists.get_by_title("Documents")
.items.get()
.filter("FileLeafRef eq 'report.csv'")
.execute_query()
)
for item in result:
print(item.properties)
14 changes: 14 additions & 0 deletions examples/sharepoint/listitems/get_deleted.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
"""
Demonstrates how to retrieve deleted items (of File type)
"""
from office365.sharepoint.changes.query import ChangeQuery
from office365.sharepoint.client_context import ClientContext
from tests import test_client_credentials, test_team_site_url

ctx = ClientContext(test_team_site_url).with_credentials(test_client_credentials)
# result = ctx.web.default_document_library().get_changes(ChangeQuery(list_=False, item=True)).execute_query()
result = (
ctx.web.recycle_bin.get().execute_query()
) # filter("ItemType eq 1").execute_query()
for item in result:
print(item.properties)
2 changes: 1 addition & 1 deletion examples/sharepoint/lists/clear.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@ def print_progress(items_count):

ctx = ClientContext(test_team_site_url).with_credentials(test_client_credentials)
target_list = ctx.web.lists.get_by_title("Contacts_Large")
target_list.clear().get().execute_batch()
target_list.clear().get().execute_query()
print("List items count: {0}".format(target_list.item_count))
14 changes: 14 additions & 0 deletions examples/sharepoint/lists/read_all.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.listitems.collection import ListItemCollection
from tests import test_client_credentials, test_team_site_url


def print_progress(items):
# type: (ListItemCollection) -> None
print("Items read: {0}".format(len(items)))


ctx = ClientContext(test_team_site_url).with_credentials(test_client_credentials)
large_list = ctx.web.lists.get_by_title("Contacts_Large")
all_items = large_list.items.get_all(5000, print_progress).execute_query()
print("Total items count: {0}".format(len(all_items)))
33 changes: 0 additions & 33 deletions examples/sharepoint/lists/read_large.py

This file was deleted.

2 changes: 1 addition & 1 deletion examples/sharepoint/lists/read_paged.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def print_progress(items):
ctx = ClientContext(test_team_site_url).with_credentials(test_client_credentials)
large_list = ctx.web.lists.get_by_title("Contacts_Large")
paged_items = (
large_list.items.paged(5000, page_loaded=print_progress).get().execute_query()
large_list.items.paged(1000, page_loaded=print_progress).get().execute_query()
)
for index, item in enumerate(paged_items): # type: int, ListItem
pass
Expand Down
22 changes: 18 additions & 4 deletions office365/graph_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,17 +72,31 @@
from office365.teams.template import TeamsTemplate
from office365.teams.viva.employee_experience import EmployeeExperience

environments_endpoints = {
"GCCH": {
"graph_url": "https://graph.microsoft.com",
"entra_url": "https://login.microsoftonline.com",
},
"GCC High": {
"graph_url": "https://graph.microsoft.us",
"entra_url": "https://login.microsoftonline.us",
},
"DoD": {
"graph_url": "https://dod-graph.microsoft.us",
"entra_url": "https://login.chinacloudapi.cn",
},
}


class GraphClient(ClientRuntimeContext):
"""Graph Service client"""

def __init__(self, acquire_token_callback, version="v1.0"):
# type: (Callable[[], dict], str) -> None
def __init__(self, acquire_token_callback, version="v1.0", environment="GCCH"):
# type: (Callable[[], dict], str, str) -> None
super(GraphClient, self).__init__()
self._pending_request = None
self._resource = "https://graph.microsoft.com"
self._version = version
self._authority_host_url = "https://login.microsoftonline.com"
self._environment_endpoints = environments_endpoints.get(environment, None)
self._acquire_token_callback = acquire_token_callback

@staticmethod
Expand Down
17 changes: 7 additions & 10 deletions office365/sharepoint/changes/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,12 @@ def __init__(self, context, resource_path=None):
super(ChangeCollection, self).__init__(context, Change, resource_path)

def set_property(self, key, value, persist_changes=False):
self.resolve_change_type(value)
self._resolve_change_type(value)
super(ChangeCollection, self).set_property(key, value)

def resolve_change_type(self, properties):
"""
Resolves a change type
:type properties: dict
"""
def _resolve_change_type(self, properties):
# type: (dict) -> None
"""Resolves a change type"""
from office365.sharepoint.changes.alert import ChangeAlert
from office365.sharepoint.changes.content_type import ChangeContentType
from office365.sharepoint.changes.field import ChangeField
Expand All @@ -27,10 +24,10 @@ def resolve_change_type(self, properties):
from office365.sharepoint.changes.user import ChangeUser
from office365.sharepoint.changes.web import ChangeWeb

if "ListId" in properties and "WebId" in properties:
self._item_type = ChangeList
elif "ItemId" in properties and "ListId" in properties:
if "ItemId" in properties and "ListId" in properties:
self._item_type = ChangeItem
elif "ListId" in properties and "WebId" in properties:
self._item_type = ChangeList
elif "WebId" in properties:
self._item_type = ChangeWeb
elif "UserId" in properties:
Expand Down
29 changes: 29 additions & 0 deletions office365/sharepoint/changes/item.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,29 @@ def content_type_id(self):
"""Specifies an identifier for the content type"""
return self.properties.get("ContentTypeId", ContentTypeId())

@property
def file_type(self):
# type: () -> Optional[str]
"""Returns the list item’s file type."""
return self.properties.get("FileType", None)

@property
def item_id(self):
# type: () -> Optional[int]
"""Identifies the changed item."""
return self.properties.get("ItemId", None)

@property
def is_recycle_bin_operation(self):
# type: () -> Optional[bool]
return self.properties.get("IsRecycleBinOperation", None)

@property
def server_relative_url(self):
# type: () -> Optional[str]
"""Specifies the server-relative URL of the item."""
return self.properties.get("ServerRelativeUrl", None)

@property
def shared_by_user(self):
"""Return the sharedBy User Information in sharing action for change log."""
Expand All @@ -32,6 +55,12 @@ def shared_with_users(self):
"SharedWithUsers", ClientValueCollection(SharedWithUser)
)

@property
def unique_id(self):
# type: () -> Optional[str]
"""The Document identifier of the item."""
return self.properties.get("UniqueId", None)

def get_property(self, name, default_value=None):
if default_value is None:
property_mapping = {
Expand Down
5 changes: 3 additions & 2 deletions office365/sharepoint/lists/list.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def clear(self):
def _clear(items):
[item.delete_object() for item in items]

self.items.get().after_execute(_clear)
self.items.get().after_execute(_clear, execute_first=True)
return self

def create_document_and_get_edit_link(
Expand Down Expand Up @@ -622,10 +622,11 @@ def get_view(self, view_id):
)

def get_changes(self, query=None):
# type: (ChangeQuery) -> ChangeCollection
"""Returns the collection of changes from the change log that have occurred within the list,
based on the specified query.
:param office365.sharepoint.changeQuery.ChangeQuery query: Specifies which changes to return
:param ChangeQuery query: Specifies which changes to return
"""
if query is None:
query = ChangeQuery(list_=True)
Expand Down

0 comments on commit a1bf24e

Please sign in to comment.