如何使用 Python SDK 和 Site.Selected 权限通过 Sites API 获取我的 SharePoint 网站

问题描述 投票:0回答:2

上下文:我需要一些帮助来了解如何管理 SharePoint 网站的存储库。

假设我的网站 URL 为“https://mycompanyname.sharepoint.com/sites/mysitename”

我首先要“访问”该站点以获得其ID,以便稍后获取该站点下的驱动器并管理存储库。

问题:我想在这里解决的问题是获取站点以便访问其元数据及其 ID。

权限:我相信我拥有应用程序级别的 Sites.Selected 权限。我可以尝试请求 Sites.Read.All,但这需要时间。有没有办法以最少的许可以某种方式完成工作?

到目前为止我尝试过,但没有成功:

import os
import jwt
from typing import Optional, Literal
from azure.identity.aio import ClientSecretCredential
from msgraph import GraphServiceClient
from msgraph.generated.models.drive_item import DriveItem
from msgraph.generated.models.folder import Folder
from msgraph.generated.drives.item.items.item.content.content_request_builder import ContentRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
from msgraph.generated.models.o_data_errors.o_data_error import ODataError
from src.config.loader import CONFIG
import aiofiles
from src.utils.logger import get_logger

logger = get_logger(CONFIG.logging.name, CONFIG.logging.level)

class GraphClientSingleton():
    _client = None
    _credentials = None

    @classmethod
    def get_client(cls):
        if cls._client is None:
            # cls._authority = 'login.microsoftonline.com'
            cls._credentials = ClientSecretCredential(
                tenant_id = CONFIG.msgraph.tenant_id_sharepoint,
                client_id = CONFIG.msgraph.client_id_sharepoint,
                client_secret = CONFIG.msgraph.client_secret_sharepoint,
            )
            cls._scopes = ['https://graph.microsoft.com/.default']

            cls._client = GraphServiceClient(credentials=cls._credentials, scopes=cls._scopes)
        return cls._client

    @classmethod
    async def decode_token(cls):
        token = await cls.get_access_token()
        decoded_token = jwt.decode(token, options={"verify_signature": False})
        return decoded_token

    @classmethod
    async def get_access_token(cls):
        if cls._credentials is None:
            cls.get_client()
        
        token = await cls._credentials.get_token(*cls._scopes)
        return token.token
    
class SharePointDAO:
    def __init__(self):
        self.client = GraphClientSingleton.get_client()
        
if __name__ == "__main__":
    async def test_api():
        token = await GraphClientSingleton.decode_token()
        sp_dao = SharePointDAO()
        # Example 1
        from msgraph.generated.sites.sites_request_builder import SitesRequestBuilder
        from kiota_abstractions.base_request_configuration import RequestConfiguration
        # To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
        query_params = SitesRequestBuilder.SitesRequestBuilderGetQueryParameters(
            select = ["siteCollection", "webUrl"],
            filter = "siteCollection/root ne null",
        )
        request_configuration = RequestConfiguration(
            query_parameters = query_params,
        )
        sites = await sp_dao.client.sites.get(request_configuration = request_configuration)
        # Example 2 (not sure how to map the "real" URL with the needed url here)
        site_request_builder = sp_dao.client.sites.with_url(
            "https://graph.microsoft.com/v1.0/sites/mycompanyname.sharepoint.com:/mysitename"
        )
        site = await site_request_builder.get()
        # Example 3 (return empty list under "value")
        sites = await sp_dao.client.sites.get()
        # Example 4 (return 403 error "Access Denied")
        sites = await sp_dao.client.sites.get_all_sites.get()
        logger.info(sites)
    import asyncio
    asyncio.run(test_api())
python azure sharepoint microsoft-graph-api
2个回答
0
投票

如果您使用像

Sites.Read.All
这样的应用程序权限,您可以调用
getAllSites
端点并按
webUrl
过滤站点。

from msgraph import GraphServiceClient
from msgraph.generated.sites.get_all_sites.get_all_sites_request_builder import GetAllSitesRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration

graph_client = GraphServiceClient(credentials, scopes)

query_params = GetAllSitesRequestBuilder.GetAllSitesRequestBuilderGetQueryParameters(
        filter = "webUrl eq 'https://mycompanyname.sharepoint.com/sites/mysitename'",
)

request_configuration = RequestConfiguration(
query_parameters = query_params,
)

result = await graph_client.sites.get_all_sites.get(request_configuration = request_configuration)

或者使用

$search
查询参数:

from msgraph import GraphServiceClient
from msgraph.generated.sites.sites_request_builder import SitesRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration

graph_client = GraphServiceClient(credentials, scopes)

query_params = SitesRequestBuilder.SitesRequestBuilderGetQueryParameters(
        search = "\"https://mycompanyname.sharepoint.com/sites/mysitename\"",
)

request_configuration = RequestConfiguration(
query_parameters = query_params,
)

result = await graph_client.sites.get(request_configuration = request_configuration)

0
投票

我同意@user2250152,您可以通过

webUrl
过滤网站或使用
$search
查询参数来获取特定的 SharePoint 网站 ID。

我有一个名为

TestSite
的 SharePoint 网站,其中包含以下驱动器:

GET https://graph.microsoft.com/v1.0/sites/siteId/drives

回复:

enter image description here

要使用 Python SDK 通过客户端凭据流程获取此数据,请使用以下示例代码,首先使用 $search 获取

site Id
并列出驱动器数据。

import asyncio
from azure.identity import ClientSecretCredential
from msgraph import GraphServiceClient
from msgraph.generated.sites.sites_request_builder import SitesRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration

tenant_id = "tenantId"
client_id = "appId"
client_secret = "secret"

site_url = "https://mytenant.sharepoint.com/sites/TestSite"

credential = ClientSecretCredential(
    tenant_id=tenant_id,
    client_id=client_id,
    client_secret=client_secret
)

client = GraphServiceClient(credential)

async def main():
    try:
        query_params = SitesRequestBuilder.SitesRequestBuilderGetQueryParameters(
            search=f"\"{site_url}\""
        )
        request_configuration = RequestConfiguration(
            query_parameters=query_params
        )
        
        result = await client.sites.get(request_configuration=request_configuration)
        sites = result.value
        
        if sites:
            for site in sites:
                print("Site ID:", site.id)
                print("Site Name:", site.display_name)
                print("Site Web URL:", site.web_url)
                print("-" * 50)

                site_id = site.id.split(",")[1]
                print("Actual Site ID:", site_id)

                drives = await client.sites.by_site_id(site_id).drives.get()
                for drive in drives.value:
                    print("Drive ID:", drive.id)
                    print("Drive Name:", drive.name)
                    print("-" * 50)
        else:
            print("No site found with the specified URL.")
    except Exception as e:
        print(f"Error fetching site or drives: {e}")

asyncio.run(main())

回复:

enter image description here

在运行代码之前,请确保在应用程序注册中授予

Sites.Read.All
Microsoft Graph Application 类型的权限:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.