Skip to content

Commit

Permalink
type hints enhancements for lists, webs namespaces, #749: a few fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
vgrem committed Oct 11, 2023
1 parent 2a00994 commit e33710e
Show file tree
Hide file tree
Showing 22 changed files with 66 additions and 106 deletions.
14 changes: 3 additions & 11 deletions examples/onedrive/columns/create_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,10 @@
from tests import create_unique_name
from tests.graph_case import acquire_token_by_username_password


def clean_up(columns):
"""
:type columns: list[office365.onedrive.columns.definition.ColumnDefinition]
"""
[column.delete_object().execute_query() for column in columns]


client = GraphClient(acquire_token_by_username_password)
lib = client.sites.root.lists["Docs"]
column_name = create_unique_name("TextColumn")
text_column = lib.columns.add_text(column_name).execute_query()
print(text_column.display_name)
column = lib.columns.add_text(column_name).execute_query()
print(column.display_name)

clean_up([text_column])
column.delete_object().execute_query()
2 changes: 1 addition & 1 deletion examples/onedrive/columns/list_site.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@

client = GraphClient(acquire_token_by_username_password)
columns = client.sites.root.columns.get().execute_query()
for column in columns: # type: ColumnDefinition
for column in columns:
print(column.name)
3 changes: 1 addition & 2 deletions examples/onedrive/excel/read_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
"""
from examples.onedrive import upload_excel_sample
from office365.graph_client import GraphClient
from office365.onedrive.workbooks.tables.rows.row import WorkbookTableRow
from tests.graph_case import acquire_token_by_username_password

client = GraphClient(acquire_token_by_username_password)
Expand All @@ -17,5 +16,5 @@

# read table content
rows = table.rows.get().execute_query()
for r in rows: # type: WorkbookTableRow
for r in rows:
print(r.values)
34 changes: 0 additions & 34 deletions examples/sharepoint/fields/create.py

This file was deleted.

12 changes: 12 additions & 0 deletions examples/sharepoint/fields/create_date.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
"""
Demonstrates how to crete a site field of type DateTime
"""

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

client = ClientContext(test_team_site_url).with_credentials(test_client_credentials)
field_name = create_unique_name("DateColumn")
field = client.web.fields.add_datetime(field_name).execute_query()
print("Field {0} has been created".format(field.internal_name))
field.delete_object().execute_query() # clean up
2 changes: 1 addition & 1 deletion examples/sharepoint/tenant/get_all_sites.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""
Retrieves sites in tenant
"""

from office365.sharepoint.client_context import ClientContext
Expand Down
3 changes: 1 addition & 2 deletions examples/sharepoint/tenant/get_home_sites.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.sites.home_sites_details import HomeSitesDetails
from tests import test_admin_credentials, test_admin_site_url

admin_client = ClientContext(test_admin_site_url).with_credentials(
test_admin_credentials
)
result = admin_client.tenant.get_home_sites().execute_query()
for details in result.value: # type: HomeSitesDetails
for details in result.value:
print(" {0}".format(details.Url))
3 changes: 1 addition & 2 deletions examples/sharepoint/tenant/get_my_sites.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from office365.runtime.client_request_exception import ClientRequestException
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.tenant.administration.sites.properties import SiteProperties
from office365.sharepoint.tenant.administration.tenant import Tenant
from tests import test_admin_credentials, test_admin_site_url, test_user_principal_name

Expand All @@ -24,7 +23,7 @@ def try_get_user_permissions(site_url, user_name):
raise ValueError(e.response.text)


for siteProps in result: # type: SiteProperties
for siteProps in result:
print("Current site url: {0}".format(siteProps.url))
if try_get_user_permissions(siteProps.url, test_user_principal_name) is True:
print(
Expand Down
9 changes: 6 additions & 3 deletions examples/sharepoint/users/export_site_users.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import json
"""
Retrieves site users
"""

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)
users = ctx.web.site_users.select(["LoginName"]).get().execute_query()
print(json.dumps(users.to_json(), indent=4))
users = ctx.web.site_users.select(["LoginName"]).get().top(100).execute_query()
for user in users:
print(user.login_name)
30 changes: 11 additions & 19 deletions examples/sharepoint/webs/clear_web.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,19 @@
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.lists.list import List
from tests import test_client_credentials, test_site_url, test_team_site_url
from tests import test_client_credentials, test_site_url


def print_progress(num_deleted):
print("{0} deleted.".format(num_deleted))


def delete_custom_lists(web):
"""
:type web: office365.sharepoint.webs.web.Web
"""
result = (
web.lists.get()
.select(["IsSystemList", "Title", "Id"])
.filter("IsSystemList eq false")
.execute_query()
)
print("{0} lists found".format(len(result)))
for lst in result: # type: List
lst.delete_object()
web.context.execute_batch(success_callback=print_progress)


ctx = ClientContext(test_site_url).with_credentials(test_client_credentials)
delete_custom_lists(ctx.web)
result = (
ctx.web.lists.get()
.select(["IsSystemList", "Title", "Id"])
.filter("IsSystemList eq false")
.execute_query()
)
print("{0} lists found".format(len(result)))
for lst in result:
lst.delete_object()
ctx.web.context.execute_batch(success_callback=print_progress)
4 changes: 2 additions & 2 deletions examples/sharepoint/webs/get_activities.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
"""
Gets web activities
"""
from office365.sharepoint.activities.entity import SPActivityEntity
from office365.sharepoint.client_context import ClientContext
from tests import test_client_credentials, test_site_url

client = ClientContext(test_site_url).with_credentials(test_client_credentials)
activities = client.web.activities.get().execute_query()
for activity in activities: # type: SPActivityEntity
for activity in activities:
print(activity.action.facet_type)
3 changes: 1 addition & 2 deletions examples/sharepoint/webs/get_all.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.webs.web import Web
from tests import test_client_credentials, test_site_url

client = ClientContext(test_site_url).with_credentials(test_client_credentials)

webs = client.web.get_all_webs().execute_query()
for web in webs: # type: Web
for web in webs:
print(web.url)
3 changes: 1 addition & 2 deletions examples/sharepoint/webs/get_lists.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.lists.list import List
from tests import test_client_credentials, test_site_url

client = ClientContext(test_site_url).with_credentials(test_client_credentials)
lists = client.web.get_lists().execute_query()
for lst in lists: # type: List
for lst in lists:
print(lst.title)
2 changes: 2 additions & 0 deletions office365/base_item.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from datetime import datetime
from typing import Optional

from office365.directory.permissions.identity_set import IdentitySet
from office365.entity import Entity
Expand Down Expand Up @@ -61,6 +62,7 @@ def last_modified_datetime(self):

@property
def name(self):
# type: () -> Optional[str]
"""Gets the name of the item."""
return self.properties.get("name", None)

Expand Down
2 changes: 1 addition & 1 deletion office365/booking/business/business.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def get_staff_availability(
"""
return_type = ClientResult(
self.context, ClientValueCollection(StaffAvailabilityItem)
)
) # type: ClientResult[ClientValueCollection[StaffAvailabilityItem]]
payload = {
"staffIds": staff_ids,
"startDateTime": start_datetime,
Expand Down
2 changes: 1 addition & 1 deletion office365/onedrive/columns/definition_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from office365.runtime.queries.create_entity import CreateEntityQuery


class ColumnDefinitionCollection(EntityCollection):
class ColumnDefinitionCollection(EntityCollection[ColumnDefinition]):
def __init__(self, context, resource_path, parent):
super(ColumnDefinitionCollection, self).__init__(
context, ColumnDefinition, resource_path, parent
Expand Down
26 changes: 12 additions & 14 deletions office365/onedrive/driveitems/driveItem.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import os
from datetime import datetime
from typing import IO, TYPE_CHECKING, Callable, Optional, TypeVar
from typing import IO, Callable, Optional, TypeVar

from typing_extensions import Self

Expand All @@ -19,6 +19,9 @@
from office365.onedrive.driveitems.remote_item import RemoteItem
from office365.onedrive.driveitems.special_folder import SpecialFolder
from office365.onedrive.driveitems.thumbnail_set import ThumbnailSet
from office365.onedrive.driveitems.uploadable_properties import (
DriveItemUploadableProperties,
)
from office365.onedrive.drives.recipient import DriveRecipient
from office365.onedrive.files.file import File
from office365.onedrive.files.system_info import FileSystemInfo
Expand Down Expand Up @@ -49,11 +52,6 @@
from office365.runtime.queries.upload_session import UploadSessionQuery
from office365.subscriptions.collection import SubscriptionCollection

if TYPE_CHECKING:
from office365.onedrive.driveitems.drive_item_uploadable_properties import (
DriveItemUploadableProperties,
)

P_T = TypeVar("P_T")


Expand Down Expand Up @@ -90,16 +88,16 @@ def create_link(
message=None,
retain_inherited_permissions=None,
):
# type: (str, Optional[str], Optional[datetime.datetime], Optional[str], Optional[str], Optional[bool]) -> Permission
# type: (str, Optional[str], Optional[datetime], Optional[str], Optional[str], Optional[bool]) -> Permission
"""
The createLink action will create a new sharing link if the specified link type doesn't already exist
for the calling application. If a sharing link of the specified type already exists for the app,
the existing sharing link will be returned.
:param str link_type: The type of sharing link to create. Either view, edit, or embed.
:param str scope: The scope of link to create. Either anonymous or organization.
:param str or datetime.datetime expiration_datetime: A String with format of yyyy-MM-ddTHH:mm:ssZ of DateTime indicates
the expiration time of the permission.
:param str or datetime.datetime expiration_datetime: A String with format of yyyy-MM-ddTHH:mm:ssZ of DateTime
indicate the expiration time of the permission.
:param str password: The password of the sharing link that is set by the creator. Optional
and OneDrive Personal only.
:param str message:
Expand All @@ -124,7 +122,7 @@ def create_link(
return return_type

def extract_sensitivity_labels(self):
# type: () -> ClientValueCollection[SensitivityLabelAssignment]
# type: () -> ClientResult[ExtractSensitivityLabelsResult]
"""
Extract one or more sensitivity labels assigned to a drive item and update the metadata of a drive
item with the latest details of the assigned label. In case of failure to extract the sensitivity labels
Expand Down Expand Up @@ -181,7 +179,7 @@ def checkin(self, comment, checkin_as=None):
return self

def resumable_upload(self, source_path, chunk_size=2000000, chunk_uploaded=None):
# type: (str, int, str) -> DriveItem
# type: (str, int, Optional[Callable[[int], None]]) -> DriveItem
"""
Create an upload session to allow your app to upload files up to the maximum file size.
An upload session allows your app to upload ranges of the file in sequential API requests,
Expand Down Expand Up @@ -257,7 +255,7 @@ def upload_file(self, path_or_file):
return self.upload(name, content)

def get_content(self, format_name=None):
# type: (Optional[str]) -> ClientResult
# type: (Optional[str]) -> ClientResult[bytes]
"""
Download the contents of the primary stream (file) of a DriveItem.
Only driveItems with the file property can be downloaded.
Expand Down Expand Up @@ -473,7 +471,7 @@ def invite(
password=None,
retain_inherited_permissions=None,
):
# type: (list[str], str, Optional[bool], Optional[bool], Optional[list[str]], Optional[datetime.datetime], Optional[str], Optional[bool]) -> PermissionCollection
# type: (list[str], str, Optional[bool], Optional[bool], Optional[list[str]], Optional[datetime], Optional[str], Optional[bool]) -> PermissionCollection
"""
Sends a sharing invitation for a driveItem. A sharing invitation provides permissions to the recipients
and optionally sends them an email with a sharing link.
Expand Down Expand Up @@ -571,7 +569,7 @@ def restore(self, parent_reference=None, name=None):
return return_type

def preview(self, page, zoom=None):
# type: (str or int, int or None) -> ItemPreviewInfo
# type: (str or int, int or None) -> ClientResult[ItemPreviewInfo]
"""
This action allows you to obtain a short-lived embeddable URL for an item in order
to render a temporary preview.
Expand Down
2 changes: 1 addition & 1 deletion office365/sharepoint/lists/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from office365.sharepoint.lists.list import List


class ListCollection(EntityCollection):
class ListCollection(EntityCollection[List]):
"""Specifies a collection of lists."""

def __init__(self, context, resource_path=None):
Expand Down
6 changes: 3 additions & 3 deletions office365/sharepoint/sites/site.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import datetime
from typing import Optional

from office365.runtime.client_result import ClientResult
from office365.runtime.client_value_collection import ClientValueCollection
Expand Down Expand Up @@ -605,10 +606,9 @@ def required_designer_version(self):

@property
def url(self):
# type: () -> Optional[str]
"""
Specifies the full URL of the site (2), including host name, port number and path.
:rtype: str
Specifies the full URL of the site (2), including host name, port number and path
"""
return self.properties.get("Url", None)

Expand Down
2 changes: 1 addition & 1 deletion office365/sharepoint/tenant/administration/tenant.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ def get_home_site_url(self):
def get_home_sites(self):
return_type = ClientResult(
self.context, ClientValueCollection(HomeSitesDetails)
)
) # type: ClientResult[ClientValueCollection[HomeSitesDetails]]
qry = ServiceOperationQuery(self, "GetHomeSites", None, None, None, return_type)
self.context.add_query(qry)
return return_type
Expand Down
2 changes: 1 addition & 1 deletion office365/sharepoint/webs/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from office365.sharepoint.webs.web import Web


class WebCollection(EntityCollection):
class WebCollection(EntityCollection[Web]):
"""Web collection"""

def __init__(self, context, resource_path=None, parent_web=None):
Expand Down

0 comments on commit e33710e

Please sign in to comment.