🔍 Code Extractor

class Office365Tenant

Maturity: 47

Represents a SharePoint Online tenant and provides administrative operations for managing tenant-level settings, CDN configurations, external users, themes, and user profile properties.

File:
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/tenant/management/office365_tenant.py
Lines:
23 - 298
Complexity:
complex

Purpose

This class serves as the primary interface for SharePoint Online tenant administration. It enables administrators to manage Content Delivery Network (CDN) settings, control external user access, configure tenant themes, manage sharing permissions, revoke user sessions, and perform bulk user profile property imports. It inherits from Entity and uses a static resource path for tenant management operations.

Source Code

class Office365Tenant(Entity):
    """Represents a SharePoint Online tenant."""

    def __init__(self, context):
        static_path = ResourcePath(
            "Microsoft.Online.SharePoint.TenantManagement.Office365Tenant"
        )
        super(Office365Tenant, self).__init__(context, static_path)

    @property
    def allow_editing(self):
        return self.properties.get("AllowEditing", None)

    @property
    def ai_builder_site_info_list(self):
        return self.properties.get(
            "AIBuilderSiteInfoList", ClientValueCollection(SiteInfoForSitePicker)
        )

    def add_tenant_cdn_origin(self, cdn_type, origin_url):
        """
        Configures a new origin to public or private CDN, on either Tenant level or on a single Site level.
        Effectively, a tenant admin points out to a document library, or a folder in the document library
        and requests that content in that library should be retrievable by using a CDN.

        You must have the SharePoint Admin role or Global Administrator role and be a site collection administrator
        to run the operation.

        :param int cdn_type: Specifies the CDN type. The valid values are: public or private.
        :param str origin_url: Specifies a path to the doc library to be configured. It can be provided in two ways:
            relative path, or a mask.
        """
        payload = {
            "cdnType": cdn_type,
            "originUrl": origin_url,
        }
        qry = ServiceOperationQuery(self, "AddTenantCdnOrigin", None, payload)
        self.context.add_query(qry)
        return self

    def disable_sharing_for_non_owners_of_site(self, site_url):
        """
        :param str site_url:
        """
        payload = {"siteUrl": site_url}
        qry = ServiceOperationQuery(
            self, "DisableSharingForNonOwnersOfSite", None, payload
        )
        self.context.add_query(qry)
        return self

    def get_tenant_cdn_enabled(self, cdn_type):
        """
        Returns whether Public content delivery network (CDN) or Private CDN is enabled on the tenant level.

        You must have the SharePoint Admin role or Global Administrator role and be a site collection administrator
        to run the operation.

        :param int cdn_type: Specifies the CDN type. The valid values are: public or private.
        """
        payload = {
            "cdnType": cdn_type,
        }
        return_type = ClientResult(self.context)
        qry = ServiceOperationQuery(
            self, "GetTenantCdnEnabled", None, payload, None, return_type
        )
        self.context.add_query(qry)
        return return_type

    def set_tenant_cdn_enabled(self, cdn_type, is_enabled):
        """
        Enables or disables Public content delivery network (CDN) or Private CDN on the tenant level.

        You must have the SharePoint Admin role or Global Administrator role and be a site collection administrator
        to run the operation.

        :param int cdn_type: Specifies the CDN type. The valid values are: public or private.
        :param bool is_enabled: Specifies if the CDN is enabled.
        """
        payload = {"cdnType": cdn_type, "isEnabled": is_enabled}
        qry = ServiceOperationQuery(self, "SetTenantCdnEnabled", None, payload)
        self.context.add_query(qry)
        return self

    def remove_tenant_cdn_origin(self, cdn_type, origin_url):
        """
        Removes a new origin from the Public or Private content delivery network (CDN).

        You must have the SharePoint Admin role or Global Administrator role and be a site collection administrator
        to run the operation.

        :param int cdn_type: Specifies the CDN type. The valid values are: public or private.
        :param str origin_url: Specifies a path to the doc library to be configured. It can be provided in two ways:
            relative path, or a mask.
        """
        payload = {
            "cdnType": cdn_type,
            "originUrl": origin_url,
        }
        qry = ServiceOperationQuery(self, "RemoveTenantCdnOrigin", None, payload)
        self.context.add_query(qry)
        return self

    def get_tenant_cdn_policies(self, cdn_type):
        """
        Get the public or private Policies applied on your SharePoint Online Tenant.

        Requires Tenant administrator permissions.


        :param int cdn_type: Specifies the CDN type. The valid values are: public or private.
        """
        payload = {
            "cdnType": cdn_type,
        }
        return_type = ClientResult(self.context, ClientValueCollection(str))
        qry = ServiceOperationQuery(
            self, "GetTenantCdnPolicies", None, payload, None, return_type
        )
        self.context.add_query(qry)
        return return_type

    def set_tenant_cdn_policy(self, cdn_type, policy, policy_value):
        """
        Sets the content delivery network (CDN) policies at the tenant level.

        Requires Tenant administrator permissions.

        :param int cdn_type: Specifies the CDN type. The valid values are: public or private.
        :param int policy: The PolicyType specifies the type of policy to set.
               Valid values:
                  IncludeFileExtensions
                  ExcludeRestrictedSiteClassifications
                  ExcludeIfNoScriptDisabled
        :param str policy_value: A String representing the value of the policy type defined by the PolicyType parameter.
        """
        payload = {"cdnType": cdn_type, "policy": policy, "policyValue": policy_value}
        qry = ServiceOperationQuery(self, "SetTenantCdnPolicy", None, payload)
        self.context.add_query(qry)
        return self

    def revoke_all_user_sessions(self, user):
        """
        Provides IT administrators the ability to invalidate a particular users' O365 sessions across all their devices.

        :param str or User user: Specifies a user name or user object
              (for example, user1@contoso.com) or User object
        """
        return_type = SPOUserSessionRevocationResult(self.context)

        def _revoke_all_user_sessions(login_name):
            """
            :type login_name: str
            """
            qry = ServiceOperationQuery(
                self, "RevokeAllUserSessions", [login_name], None, None, return_type
            )
            self.context.add_query(qry)

        if isinstance(user, User):

            def _user_loaded():
                _revoke_all_user_sessions(user.login_name)

            user.ensure_property("LoginName", _user_loaded)
        else:
            _revoke_all_user_sessions(user)
        return return_type

    def get_external_users(self, position=0, page_size=50, _filter=None, sort_order=0):
        """
        Returns external users in the tenant.

        :param int position: Use to specify the zero-based index of the position in the sorted collection of the
                             first result to be returned.
        :param int page_size: Specifies the maximum number of users to be returned in the collection.
                              The value must be less than or equal to 50.
        :param str _filter: Limits the results to only those users whose first name, last name, or email address
                            begins with the text in the string using a case-insensitive comparison.
        :param int sort_order: Specifies the sort results in Ascending or Descending order on the User.Email property
                               should occur.
        """
        return_type = GetExternalUsersResults(self.context)
        payload = {
            "position": position,
            "pageSize": page_size,
            "filter": _filter,
            "sortOrder": sort_order,
        }
        qry = ServiceOperationQuery(
            self, "GetExternalUsers", None, payload, None, return_type
        )
        self.context.add_query(qry)
        return return_type

    def remove_external_users(self, unique_ids=None):
        """
        Removes a collection of external users from the tenancy's folder.

        :param list[str] unique_ids: Specifies an ID that can be used to identify an external user based on
                                     their Windows Live ID.
        """
        payload = {
            "uniqueIds": unique_ids,
        }
        return_type = RemoveExternalUsersResults(self.context)
        qry = ServiceOperationQuery(
            self, "RemoveExternalUsers", None, payload, None, return_type
        )
        self.context.add_query(qry)
        return return_type

    def get_all_tenant_themes(self):
        """
        Get all themes from tenant
        """
        return_type = ClientObjectCollection(self.context, ThemeProperties)
        qry = ServiceOperationQuery(
            self, "GetAllTenantThemes", None, None, None, return_type
        )
        self.context.add_query(qry)
        return return_type

    def add_tenant_theme(self, name, theme_json):
        """
        Adds a new theme to a tenant.

        :param str name:
        :param str theme_json:
        """
        return_type = ClientResult(self.context)
        payload = {
            "name": name,
            "themeJson": theme_json,
        }
        qry = ServiceOperationQuery(
            self, "AddTenantTheme", None, payload, None, return_type
        )
        self.context.add_query(qry)
        return return_type

    def delete_tenant_theme(self, name):
        """
        Removes a theme from tenant
        :type name: str
        """
        payload = {
            "name": name,
        }
        qry = ServiceOperationQuery(self, "DeleteTenantTheme", None, payload)
        self.context.add_query(qry)
        return self

    def queue_import_profile_properties(
        self, id_type, source_data_id_property, property_map, source_uri
    ):
        """Bulk import custom user profile properties

        :param int id_type: The type of id to use when looking up the user profile.
        :param str source_data_id_property: The name of the ID property in the source data.
        :param dict property_map: A map from the source property name to the user profile service property name.
        :param str source_uri: The URI of the source data file to import.
        """
        return_type = ClientResult(self.context)
        payload = {
            "idType": id_type,
            "sourceDataIdProperty": source_data_id_property,
            "propertyMap": property_map,
            "sourceUri": source_uri,
        }
        qry = ServiceOperationQuery(
            self, "QueueImportProfileProperties", None, payload, None, return_type
        )
        self.context.add_query(qry)
        return return_type

Parameters

Name Type Default Kind
bases Entity -

Parameter Details

context: A client context object that provides the connection and authentication details for communicating with the SharePoint Online tenant. This context is used to execute queries and operations against the tenant.

Return Value

Instantiation returns an Office365Tenant object that represents the SharePoint Online tenant. Most methods return 'self' for method chaining, or return specialized result objects (ClientResult, GetExternalUsersResults, RemoveExternalUsersResults, SPOUserSessionRevocationResult, ClientObjectCollection) that contain the operation results after query execution.

Class Interface

Methods

__init__(self, context)

Purpose: Initializes the Office365Tenant object with a client context and sets up the static resource path for tenant management operations

Parameters:

  • context: Client context object for SharePoint communication

Returns: None (constructor)

@property allow_editing(self) property

Purpose: Gets the AllowEditing property value from the tenant properties

Returns: Boolean or None indicating if editing is allowed

@property ai_builder_site_info_list(self) property

Purpose: Gets the AI Builder site information list from tenant properties

Returns: ClientValueCollection of SiteInfoForSitePicker objects

add_tenant_cdn_origin(self, cdn_type: int, origin_url: str) -> Office365Tenant

Purpose: Configures a new origin for public or private CDN at tenant or site level by pointing to a document library or folder

Parameters:

  • cdn_type: Integer specifying CDN type (0 for public, 1 for private)
  • origin_url: String path to the document library, can be relative path or mask

Returns: Self for method chaining

disable_sharing_for_non_owners_of_site(self, site_url: str) -> Office365Tenant

Purpose: Disables sharing capabilities for non-owners of a specific site

Parameters:

  • site_url: String URL of the site to restrict sharing

Returns: Self for method chaining

get_tenant_cdn_enabled(self, cdn_type: int) -> ClientResult

Purpose: Checks whether Public or Private CDN is enabled at the tenant level

Parameters:

  • cdn_type: Integer specifying CDN type (0 for public, 1 for private)

Returns: ClientResult object containing boolean value indicating if CDN is enabled

set_tenant_cdn_enabled(self, cdn_type: int, is_enabled: bool) -> Office365Tenant

Purpose: Enables or disables Public or Private CDN at the tenant level

Parameters:

  • cdn_type: Integer specifying CDN type (0 for public, 1 for private)
  • is_enabled: Boolean indicating whether to enable or disable the CDN

Returns: Self for method chaining

remove_tenant_cdn_origin(self, cdn_type: int, origin_url: str) -> Office365Tenant

Purpose: Removes an origin from the Public or Private CDN configuration

Parameters:

  • cdn_type: Integer specifying CDN type (0 for public, 1 for private)
  • origin_url: String path to the document library to remove, can be relative path or mask

Returns: Self for method chaining

get_tenant_cdn_policies(self, cdn_type: int) -> ClientResult

Purpose: Retrieves the public or private CDN policies applied on the SharePoint Online tenant

Parameters:

  • cdn_type: Integer specifying CDN type (0 for public, 1 for private)

Returns: ClientResult object containing ClientValueCollection of strings representing policies

set_tenant_cdn_policy(self, cdn_type: int, policy: int, policy_value: str) -> Office365Tenant

Purpose: Sets CDN policies at the tenant level for file extensions, site classifications, or script settings

Parameters:

  • cdn_type: Integer specifying CDN type (0 for public, 1 for private)
  • policy: Integer PolicyType (IncludeFileExtensions, ExcludeRestrictedSiteClassifications, ExcludeIfNoScriptDisabled)
  • policy_value: String representing the value for the specified policy type

Returns: Self for method chaining

revoke_all_user_sessions(self, user: str | User) -> SPOUserSessionRevocationResult

Purpose: Invalidates all O365 sessions for a specific user across all their devices

Parameters:

  • user: String username (e.g., user1@contoso.com) or User object

Returns: SPOUserSessionRevocationResult object containing the revocation operation result

get_external_users(self, position: int = 0, page_size: int = 50, _filter: str = None, sort_order: int = 0) -> GetExternalUsersResults

Purpose: Retrieves a paginated list of external users in the tenant with optional filtering and sorting

Parameters:

  • position: Integer zero-based index for pagination start position
  • page_size: Integer maximum number of users to return (max 50)
  • _filter: String to filter users by first name, last name, or email (case-insensitive)
  • sort_order: Integer specifying ascending or descending sort on User.Email

Returns: GetExternalUsersResults object containing the collection of external users

remove_external_users(self, unique_ids: list[str] = None) -> RemoveExternalUsersResults

Purpose: Removes a collection of external users from the tenant based on their unique IDs

Parameters:

  • unique_ids: List of strings containing Windows Live IDs identifying external users

Returns: RemoveExternalUsersResults object containing the removal operation results

get_all_tenant_themes(self) -> ClientObjectCollection

Purpose: Retrieves all custom themes configured at the tenant level

Returns: ClientObjectCollection of ThemeProperties objects

add_tenant_theme(self, name: str, theme_json: str) -> ClientResult

Purpose: Adds a new custom theme to the tenant with specified name and theme configuration

Parameters:

  • name: String name for the new theme
  • theme_json: String JSON representation of the theme properties

Returns: ClientResult object containing the operation result

delete_tenant_theme(self, name: str) -> Office365Tenant

Purpose: Removes a custom theme from the tenant by name

Parameters:

  • name: String name of the theme to delete

Returns: Self for method chaining

queue_import_profile_properties(self, id_type: int, source_data_id_property: str, property_map: dict, source_uri: str) -> ClientResult

Purpose: Queues a bulk import operation for custom user profile properties from an external data source

Parameters:

  • id_type: Integer type of ID to use for user profile lookup
  • source_data_id_property: String name of the ID property in the source data
  • property_map: Dictionary mapping source property names to user profile service property names
  • source_uri: String URI of the source data file to import

Returns: ClientResult object containing the import job identifier

Attributes

Name Type Description Scope
context ClientContext The client context used for executing queries against SharePoint Online instance
properties dict Dictionary containing tenant properties loaded from SharePoint (inherited from Entity) instance

Dependencies

  • office365

Required Imports

from office365.runtime.client_object_collection import ClientObjectCollection
from office365.runtime.client_result import ClientResult
from office365.runtime.client_value_collection import ClientValueCollection
from office365.runtime.paths.resource_path import ResourcePath
from office365.runtime.queries.service_operation import ServiceOperationQuery
from office365.sharepoint.entity import Entity
from office365.sharepoint.principal.users.user import User
from office365.sharepoint.tenant.administration.siteinfo_for_site_picker import SiteInfoForSitePicker
from office365.sharepoint.tenant.administration.theme_properties import ThemeProperties
from office365.sharepoint.tenant.management.externalusers.results.get import GetExternalUsersResults
from office365.sharepoint.tenant.management.externalusers.results.remove import RemoveExternalUsersResults
from office365.sharepoint.tenant.management.externalusers.results.session_revocation import SPOUserSessionRevocationResult

Usage Example

from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.user_credential import UserCredential

# Authenticate and get tenant context
tenant_url = 'https://contoso-admin.sharepoint.com'
credentials = UserCredential('admin@contoso.com', 'password')
ctx = ClientContext(tenant_url).with_credentials(credentials)

# Create tenant object
tenant = ctx.site.root_web.tenant_app_catalog.tenant

# Enable public CDN
tenant.set_tenant_cdn_enabled(cdn_type=0, is_enabled=True)
ctx.execute_query()

# Add CDN origin
tenant.add_tenant_cdn_origin(cdn_type=0, origin_url='*/CDN')
ctx.execute_query()

# Check if CDN is enabled
result = tenant.get_tenant_cdn_enabled(cdn_type=0)
ctx.execute_query()
print(f'CDN Enabled: {result.value}')

# Get external users
external_users = tenant.get_external_users(position=0, page_size=10)
ctx.execute_query()
for user in external_users.external_user_collection:
    print(user.display_name)

# Revoke user sessions
revoke_result = tenant.revoke_all_user_sessions('user@external.com')
ctx.execute_query()
print(f'Sessions revoked: {revoke_result.value}')

Best Practices

  • Always call ctx.execute_query() after adding operations to actually execute them against SharePoint
  • Ensure the authenticated user has SharePoint Admin or Global Administrator role before calling administrative methods
  • Use method chaining when performing multiple operations, then execute once for efficiency
  • Handle return types appropriately - some methods return ClientResult objects that need .value property access after execution
  • For CDN operations, cdn_type parameter uses integers: 0 for public CDN, 1 for private CDN
  • When revoking user sessions, you can pass either a User object or a string login name
  • External user operations require proper permissions and may have rate limits
  • Theme JSON must be properly formatted according to SharePoint theme schema
  • Profile property imports are queued and processed asynchronously
  • Always check property availability using ensure_property() when working with lazy-loaded properties

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class TenantAdminSettingsService 78.1% similar

    A service class for managing SharePoint Online tenant administration settings, providing access to tenant-level configuration and sharing status.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/tenant/administration/settings_service.py
  • class TenantCdnApi 77.3% similar

    TenantCdnApi is a SharePoint entity class that provides access to the Tenant CDN (Content Delivery Network) API for managing CDN settings at the tenant level.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/tenant/cdn_api.py
  • class TenantAdminEndpoints 76.0% similar

    A SharePoint entity class representing tenant administration endpoints, providing access to Office 365 admin center endpoint information.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/tenant/administration/endpoints.py
  • class TenantCdnUrl 71.7% similar

    A client value class representing a SharePoint Tenant CDN URL entity, providing type identification for Microsoft SharePoint Tenant CDN URL objects.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/tenant/cdn_url.py
  • class Tenant 71.5% similar

    Represents a SharePoint tenant.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/tenant/administration/tenant.py
← Back to Browse