Skip to content

Commit

Permalink
Examples updates
Browse files Browse the repository at this point in the history
  • Loading branch information
vgrem committed Jul 7, 2023
1 parent a702fbf commit 9b866ef
Show file tree
Hide file tree
Showing 13 changed files with 77 additions and 97 deletions.
6 changes: 5 additions & 1 deletion examples/onedrive/sites/search.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
"""
Search across a SharePoint tenant for sites that match keywords provided.
https://learn.microsoft.com/en-us/onedrive/developer/rest-api/api/site_search?view=odsp-graph-online
"""

from examples import acquire_token_by_client_credentials
from office365.graph_client import GraphClient
from office365.onedrive.sites.site import Site
from tests.graph_case import acquire_token_by_client_credentials

client = GraphClient(acquire_token_by_client_credentials)
sites = client.sites.search("team").execute_query()
Expand Down
5 changes: 4 additions & 1 deletion examples/onedrive/termstore/export_term_store.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from examples import acquire_token_by_client_credentials
"""
Demonstrates how to retrieve a flat list of all TermSet objects
"""
from office365.graph_client import GraphClient
from tests import test_team_site_url
from tests.graph_case import acquire_token_by_client_credentials

client = GraphClient(acquire_token_by_client_credentials)
term_sets = client.sites.get_by_url(test_team_site_url).term_store.get_all_term_sets().execute_query()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
from examples import acquire_token_by_username_password
"""
Demonstrates how to work with the Excel API
https://learn.microsoft.com/en-us/graph/api/resources/excel?view=graph-rest-1.0
"""
from office365.graph_client import GraphClient
from office365.onedrive.workbooks.tables.rows.row import WorkbookTableRow
from office365.runtime.client_request_exception import ClientRequestException
from tests.graph_case import acquire_token_by_username_password


def ensure_workbook_sample(graph_client):
Expand All @@ -12,7 +18,7 @@ def ensure_workbook_sample(graph_client):
except ClientRequestException as e:
if e.response.status_code == 404:
local_path = "../../data/Financial Sample.xlsx"
target_file = graph_client.me.drive.root.resumable_upload(local_path).execute_query()
target_file = graph_client.me.drive.root.upload(local_path).execute_query()
print(f"File {target_file.web_url} has been uploaded")
return target_file.workbook
else:
Expand All @@ -22,6 +28,18 @@ def ensure_workbook_sample(graph_client):
client = GraphClient(acquire_token_by_username_password)
workbook = ensure_workbook_sample(client)

print("Creating a session...")
result = workbook.create_session().execute_query()

print("Reading a table...")
table = workbook.worksheets["Sheet1"].tables["financials"]
# read table content
rows = table.rows.get().execute_query()
for r in rows: # type: WorkbookTableRow
print(r.values)

print("Refreshing a session...")
result_new = workbook.refresh_session(result.value.id).execute_query()

print("Closing a session...")
workbook.close_session(result.value.id).execute_query()
6 changes: 3 additions & 3 deletions examples/outlook/messages/get_basic_props.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
"""

from examples import acquire_token_by_client_credentials, sample_user_principal_name
from office365.graph_client import GraphClient
from office365.outlook.mail.messages.message import Message

from tests import test_user_principal_name
from tests.graph_case import acquire_token_by_client_credentials

client = GraphClient(acquire_token_by_client_credentials)
user = client.users[sample_user_principal_name]
user = client.users[test_user_principal_name]
messages = user.messages.select(["id", "subject"]).top(10).get().execute_query()
for message in messages: # type: Message
print(message.id)
49 changes: 0 additions & 49 deletions examples/sharepoint/selfsigncert.pem

This file was deleted.

7 changes: 3 additions & 4 deletions examples/sharepoint/sites/create_comm_site_with_owner.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
"""
Creates a modern site
"""
import uuid

from office365.sharepoint.client_context import ClientContext
from tests import test_team_site_url, test_user_principal_name_alt, test_admin_credentials
from tests import test_team_site_url, test_user_principal_name_alt, test_admin_credentials, create_unique_name

client = ClientContext(test_team_site_url).with_credentials(test_admin_credentials)
owner = client.web.site_users.get_by_email(test_user_principal_name_alt)
site_alias = "commsite_{0}".format(uuid.uuid4().hex)
site_alias = create_unique_name("commsite")
print("Creating a modern site: {0} ...".format(site_alias))
site = client.create_modern_site("Comm Site", site_alias, owner).execute_query()
print("Site has been created at url: {0}".format(site.url))

Expand Down
10 changes: 8 additions & 2 deletions examples/sharepoint/sites/grant_app_access.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
"""
Controlling app access on a specific SharePoint site collection
Refer for doc:
Refer:
https://developer.microsoft.com/en-us/office/blogs/controlling-app-access-on-specific-sharepoint-site-collections/
"""
import json

from examples import acquire_token_by_client_credentials
from office365.graph_client import GraphClient
from tests import test_client_credentials, test_team_site_url
from tests.graph_case import acquire_token_by_client_credentials


def assign_site_access(site, application, roles=None, clear_existing=False):
Expand All @@ -19,11 +20,16 @@ def assign_site_access(site, application, roles=None, clear_existing=False):
:param bool clear_existing: Clear existing permissions first
"""
if clear_existing:
print("Clearing existing permissions...")
target_site.permissions.delete_all().execute_query()

if roles:
print("Granting {0} permissions for application {1}".format(roles, application.app_id))
site.permissions.add(roles, application).execute_query()

result = site.permissions.get().execute_query()
print("Current permissions: {0}".format(json.dumps(result.to_json(), indent=4)))


client = GraphClient(acquire_token_by_client_credentials)
target_site = client.sites.get_by_url(test_team_site_url)
Expand Down
28 changes: 13 additions & 15 deletions office365/onedrive/driveitems/driveItem.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,9 @@ def _construct_download_request(request):
request.method = HttpMethod.Get

def _process_download_response(response):
"""
:type response: requests.Response
"""
bytes_read = 0
for chunk in response.iter_content(chunk_size=chunk_size):
bytes_read += len(chunk)
Expand Down Expand Up @@ -312,7 +315,7 @@ def _process_response(resp):
return
return_type.set_property("__value", location)

def _create_query(parent_reference):
def _create_and_add_query(parent_reference):
"""
:param office365.onedrive.listitems.item_reference.ItemReference or None parent_reference: Reference to the
parent item the copy will be created in.
Expand All @@ -323,18 +326,16 @@ def _create_query(parent_reference):
}
self.context.before_execute(_create_request)
self.context.after_execute(_process_response)
return ServiceOperationQuery(self, "copy", None, payload, None, return_type)
qry = ServiceOperationQuery(self, "copy", None, payload, None, return_type)
self.context.add_query(qry)

if isinstance(parent, DriveItem):
def _drive_item_loaded():
parent_reference = ItemReference(drive_id=parent.parent_reference.driveId, _id=parent.id)
next_qry = _create_query(parent_reference)
self.context.add_query(next_qry)

_create_and_add_query(parent_reference)
parent.ensure_property("parentReference", _drive_item_loaded)
else:
qry = _create_query(parent)
self.context.add_query(qry)
_create_and_add_query(parent)
return return_type

def move(self, name=None, parent=None):
Expand All @@ -349,7 +350,7 @@ def move(self, name=None, parent=None):

return_type = ClientResult(self.context, str())

def _create_query(parent_reference):
def _create_and_add_query(parent_reference):
payload = {
"name": name,
"parentReference": parent_reference
Expand All @@ -359,18 +360,15 @@ def _construct_request(request):
request.method = HttpMethod.Patch

self.context.before_execute(_construct_request)
return ServiceOperationQuery(self, "move", None, payload, None, return_type)
qry = ServiceOperationQuery(self, "move", None, payload, None, return_type)
self.context.add_query(qry)

if isinstance(parent, DriveItem):
def _drive_item_loaded():
parent_reference = ItemReference(_id=parent.id)
next_qry = _create_query(parent_reference)
self.context.add_query(next_qry)

_create_and_add_query(ItemReference(_id=parent.id))
parent.ensure_property("parentReference", _drive_item_loaded)
else:
qry = _create_query(parent)
self.context.add_query(qry)
_create_and_add_query(parent)
return return_type

def rename(self, new_name):
Expand Down
2 changes: 1 addition & 1 deletion office365/onedrive/lists/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def __init__(self, context, resource_path=None):

def __getitem__(self, key):
"""
Address List by identifier or name
Gets List by it's identifier or name
:param str key: List identifier or name
:rtype: List
"""
Expand Down
8 changes: 4 additions & 4 deletions office365/onedrive/permissions/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def add(self, roles, identity=None, identity_type=None):

return_type = Permission(self.context)

known_identity_endpoints = {
known_identities = {
"application": self.context.applications,
"user": self.context.users,
"device": self.context.device_app_management,
Expand All @@ -34,10 +34,10 @@ def add(self, roles, identity=None, identity_type=None):
else:
if identity_type is None:
raise ValueError("Identity type is a mandatory when identity identifier is specified")
known_identity_endpoint = known_identity_endpoints.get(identity_type, None)
if known_identity_endpoint is None:
known_identity = known_identities.get(identity_type, None)
if known_identity is None:
raise ValueError("Unknown identity type")
identity = known_identity_endpoint[identity]
identity = known_identity[identity]

def _create():
payload = {
Expand Down
4 changes: 2 additions & 2 deletions office365/sharepoint/lists/list.py
Original file line number Diff line number Diff line change
Expand Up @@ -391,13 +391,13 @@ def add_item(self, creation_information):
qry = ServiceOperationQuery(self, "items", None, return_type, None, return_type)
self.context.add_query(qry)
else:
def _folder_loaded():
def _add_item():
creation_information.FolderUrl = self.context.base_url + self.root_folder.serverRelativeUrl
payload = {"parameters": creation_information}
next_qry = ServiceOperationQuery(self, "addItem", None, payload, None, return_type)
self.context.add_query(next_qry)

self.root_folder.ensure_property("ServerRelativeUrl", _folder_loaded)
self.root_folder.ensure_property("ServerRelativeUrl", _add_item)
return return_type

def create_wiki_page(self, page_name, page_content):
Expand Down
11 changes: 5 additions & 6 deletions office365/sharepoint/portal/sites/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,20 +29,19 @@ def create(self, title, site_url, owner=None):
"""
return_type = ClientResult(self.context, SPSiteCreationResponse())

def _create_query(owner_string=None):
def _create(owner_string=None):
request = SPSiteCreationRequest(title, site_url, owner_string)
payload = {"request": request}
return ServiceOperationQuery(self, "Create", None, payload, None, return_type)
qry = ServiceOperationQuery(self, "Create", None, payload, None, return_type)
self.context.add_query(qry)

from office365.sharepoint.principal.users.user import User
if isinstance(owner, User):
def _owner_loaded():
next_qry = _create_query(owner.user_principal_name)
self.context.add_query(next_qry)
_create(owner.user_principal_name)
owner.ensure_property("UserPrincipalName", _owner_loaded)
else:
qry = _create_query(owner)
self.context.add_query(qry)
_create(owner)
return return_type

def delete(self, site_id):
Expand Down
16 changes: 9 additions & 7 deletions office365/sharepoint/webs/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,19 +185,21 @@ def get_push_notification_subscribers_by_user(self, user):
"""
return_type = PushNotificationSubscriberCollection(self.context)

def _create_query(login_name):
return ServiceOperationQuery(self, "GetPushNotificationSubscribersByUser",
[login_name], None, None, return_type)
def _create_and_add_query(login_name):
"""
:type login_name: str
"""
qry = ServiceOperationQuery(self, "GetPushNotificationSubscribersByUser",
[login_name], None, None, return_type)
self.context.add_query(qry)

if isinstance(user, User):
def _user_loaded():
next_qry = _create_query(user.login_name)
self.context.add_query(next_qry)
_create_and_add_query(user.login_name)

user.ensure_property("LoginName", _user_loaded)
else:
qry = _create_query(user)
self.context.add_query(qry)
_create_and_add_query(user)
return return_type

@staticmethod
Expand Down

0 comments on commit 9b866ef

Please sign in to comment.