msdev-kit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,105 @@
1
+ import os
2
+ import mimetypes
3
+ import requests
4
+ from datetime import datetime
5
+ from typing import Optional, Union
6
+ from msdev_kit.auth import Auth
7
+
8
+
9
+ class SharePointClient:
10
+ _GRAPH_BASE = 'https://graph.microsoft.com/v1.0'
11
+
12
+ def __init__(self, auth: Auth, sp_hostname: str, sp_site_path: str):
13
+ self._auth = auth
14
+
15
+ hostname = sp_hostname.replace('https://', '').replace('http://', '').rstrip('/')
16
+ if not hostname.endswith('.sharepoint.com'):
17
+ hostname = f'{hostname}.sharepoint.com'
18
+ self._sp_hostname = hostname
19
+
20
+ site_path = sp_site_path.strip('/')
21
+ if not site_path.startswith('sites/'):
22
+ site_path = f'sites/{site_path}'
23
+ self._sp_site_path = site_path
24
+
25
+ self._site_id: Optional[str] = None
26
+
27
+ def _headers(self) -> dict:
28
+ return {
29
+ 'Authorization': f'Bearer {self._auth.get_token("graph")}',
30
+ 'Content-Type': 'application/json',
31
+ }
32
+
33
+ def _ts(self) -> str:
34
+ return datetime.now().strftime('%Y-%m-%d %H:%M:%S')
35
+
36
+ def _get_site_id(self) -> str:
37
+ """Resolve and cache the Graph site ID for this SharePoint site."""
38
+ if self._site_id:
39
+ return self._site_id
40
+
41
+ resp = requests.get(
42
+ f'{self._GRAPH_BASE}/sites/{self._sp_hostname}:/{self._sp_site_path}',
43
+ headers=self._headers(),
44
+ params={'$select': 'id'},
45
+ timeout=30,
46
+ )
47
+ resp.raise_for_status()
48
+ self._site_id = resp.json()['id']
49
+ return self._site_id
50
+
51
+ def download_file(self, file_path: str, local_dir: str) -> str:
52
+ """Download a file from the site's default document library. Returns local file path."""
53
+ site_id = self._get_site_id()
54
+ local_path = os.path.join(local_dir, os.path.basename(file_path))
55
+
56
+ resp = requests.get(
57
+ f'{self._GRAPH_BASE}/sites/{site_id}/drive/root:{file_path}:/content',
58
+ headers={'Authorization': f'Bearer {self._auth.get_token("graph")}'},
59
+ timeout=120,
60
+ )
61
+ resp.raise_for_status()
62
+ print(f'[{self._ts()}] Downloaded: {file_path}')
63
+
64
+ with open(local_path, 'wb') as f:
65
+ f.write(resp.content)
66
+ return local_path
67
+
68
+ def create_folder(self, folder_path: str):
69
+ """Create a folder and all intermediate folders in the default document library."""
70
+ site_id = self._get_site_id()
71
+ parts = [p for p in folder_path.strip('/').split('/') if p]
72
+ current_path = ''
73
+
74
+ for part in parts:
75
+ parent_ref = f'root:{current_path}' if current_path else 'root'
76
+ resp = requests.post(
77
+ f'{self._GRAPH_BASE}/sites/{site_id}/drive/{parent_ref}:/children',
78
+ headers=self._headers(),
79
+ json={
80
+ 'name': part,
81
+ 'folder': {},
82
+ '@microsoft.graph.conflictBehavior': 'replace',
83
+ },
84
+ timeout=30,
85
+ )
86
+ resp.raise_for_status()
87
+ current_path = f'{current_path}/{part}'
88
+
89
+ def upload_file(self, remote_path: str, source: Union[str, bytes], content_type: Optional[str] = None):
90
+ """Upload (or overwrite) a file to the default document library.
91
+ source: local file path (str) or raw bytes."""
92
+ mime_type = content_type or mimetypes.guess_type(remote_path)[0] or 'application/octet-stream'
93
+ site_id = self._get_site_id()
94
+ content = open(source, 'rb').read() if isinstance(source, str) else source
95
+
96
+ resp = requests.put(
97
+ f'{self._GRAPH_BASE}/sites/{site_id}/drive/root:{remote_path}:/content',
98
+ headers={
99
+ 'Authorization': f'Bearer {self._auth.get_token("graph")}',
100
+ 'Content-Type': mime_type,
101
+ },
102
+ data=content,
103
+ timeout=60,
104
+ )
105
+ resp.raise_for_status()
@@ -0,0 +1,269 @@
1
+ Metadata-Version: 2.4
2
+ Name: msdev-kit
3
+ Version: 0.1.0
4
+ Summary: Microsoft developer toolkit: Fabric, MS Graph, and SharePoint
5
+ License: MIT
6
+ Author: Bernardo Rufino
7
+ Author-email: contact@bernardorufino.com
8
+ Requires-Python: >=3.10
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Requires-Dist: azure-identity (>=1.24.0,<2)
17
+ Requires-Dist: azure-kusto-data (>=6.0.1,<7.0.0)
18
+ Requires-Dist: cryptography (>=46.0.6,<47.0.0)
19
+ Requires-Dist: numpy (==2.1.3)
20
+ Requires-Dist: openpyxl (==3.1.5)
21
+ Requires-Dist: pandas (==2.2.3)
22
+ Requires-Dist: pyodbc (==5.2.0)
23
+ Requires-Dist: python-dotenv (==1.0.1)
24
+ Requires-Dist: pyyaml (>=6.0.3,<7.0.0)
25
+ Requires-Dist: requests (>=2.33.0)
26
+ Requires-Dist: sqlalchemy (==2.0.44)
27
+ Project-URL: Homepage, https://github.com/Bernardo-Rufino/msdev-kit
28
+ Project-URL: Repository, https://github.com/Bernardo-Rufino/msdev-kit
29
+ Description-Content-Type: text/markdown
30
+
31
+ # msdev-kit
32
+
33
+ Microsoft developer toolkit for Python: Fabric/Power BI, MS Graph (Entra), and SharePoint.
34
+
35
+ ## Installation
36
+
37
+ ### Install from PyPI (recommended)
38
+
39
+ ```shell
40
+ pip install msdev-kit
41
+ ```
42
+
43
+ ### Install from GitHub
44
+
45
+ ```shell
46
+ pip install git+https://github.com/Bernardo-Rufino/msdev-kit.git
47
+ ```
48
+
49
+ ### Install for local development
50
+
51
+ ```shell
52
+ git clone https://github.com/Bernardo-Rufino/msdev-kit.git
53
+ cd msdev-kit
54
+ pip install -e .
55
+ ```
56
+
57
+ ---
58
+
59
+ ## Prerequisites
60
+
61
+ - Python >= 3.10
62
+ - An Azure app registration with a client ID and client secret
63
+
64
+ ## Getting Started
65
+
66
+ ### Authentication
67
+
68
+ All classes use a shared `Auth` object. You can use different service principals for different services:
69
+
70
+ ```python
71
+ from msdev_kit import Auth
72
+
73
+ # service principal auth
74
+ auth = Auth(tenant_id="...", client_id="...", client_secret="...")
75
+
76
+ token = auth.get_token() # Power BI API (default)
77
+ token = auth.get_token('fabric') # Fabric API
78
+ token = auth.get_token('graph') # MS Graph API
79
+ token = auth.get_token('azure') # Azure Management API
80
+
81
+ # interactive user auth
82
+ token = auth.get_token_for_user('pbi')
83
+ ```
84
+
85
+ ### Credentials
86
+
87
+ Set up credentials via environment variables or a `.env` file:
88
+
89
+ ```shell
90
+ TENANT_ID='<YOUR_TENANT_ID>'
91
+ CLIENT_ID='<YOUR_CLIENT_ID>'
92
+ CLIENT_SECRET='<YOUR_CLIENT_SECRET>'
93
+ ```
94
+
95
+ ---
96
+
97
+ ## Sub-packages
98
+
99
+ ### `msdev_kit.fabric` — Fabric & Power BI
100
+
101
+ All existing Fabric/Power BI classes, accessed via the `fabric` sub-package:
102
+
103
+ ```python
104
+ from msdev_kit.fabric import Workspace, Dataset, Report, Dataflow, Pipeline
105
+ from msdev_kit import Auth
106
+
107
+ auth = Auth(tenant_id, client_id, client_secret)
108
+ ws = Workspace(auth.get_token('fabric'))
109
+ ```
110
+
111
+ #### Workspace
112
+
113
+ Manage Power BI workspaces, users, and permissions.
114
+
115
+ | Method | Description |
116
+ |---|---|
117
+ | `list_workspaces_for_user(...)` | List all workspaces the user has access to, with optional filters. |
118
+ | `get_workspace_details(workspace_id)` | Get details for a specific workspace. |
119
+ | `list_users(workspace_id)` | List all users in a workspace. |
120
+ | `list_reports(workspace_id)` | List all reports in a workspace. |
121
+ | `add_user(user_principal_name, workspace_id, access_right, user_type)` | Add a user or service principal to a workspace. |
122
+ | `update_user(user_principal_name, workspace_id, access_right)` | Update a user's role on a workspace. |
123
+ | `remove_user(user_principal_name, workspace_id)` | Remove a user from a workspace. |
124
+ | `batch_update_user(user, workspaces_list)` | Batch update a user across multiple workspaces. |
125
+
126
+ #### Dataset
127
+
128
+ Manage datasets (semantic models), permissions, and execute DAX queries.
129
+
130
+ | Method | Description |
131
+ |---|---|
132
+ | `list_datasets(workspace_id)` | List all datasets in a workspace. |
133
+ | `get_dataset_details(workspace_id, dataset_id)` | Get details of a specific dataset. |
134
+ | `get_dataset_name(workspace_id, dataset_id)` | Resolve the display name of a dataset. Tries the PBI API first, falls back to the Fabric semantic models API. |
135
+ | `execute_query(workspace_id, dataset_id, query)` | Execute a DAX query against a dataset. Runs a COUNTROWS pre-check to detect if API row/value limits would truncate the result and returns truncation metadata. |
136
+ | `list_users(workspace_id, dataset_id)` | List users with access to a dataset. |
137
+ | `add_user(user_principal_name, workspace_id, dataset_id, access_right)` | Grant a user access to a dataset. |
138
+ | `update_user(user_principal_name, workspace_id, dataset_id, access_right)` | Update a user's access to a dataset. |
139
+ | `remove_user(user_principal_name, workspace_id, dataset_id)` | Remove a user's access to a dataset. |
140
+ | `list_dataset_related_reports(workspace_id, dataset_id)` | List all reports linked to a dataset. |
141
+ | `export_dataset_related_reports(workspace_id, dataset_id)` | Export all reports linked to a dataset as `.pbix` files. |
142
+
143
+ #### Report
144
+
145
+ Retrieve report metadata, definitions, visuals, and report-level measures.
146
+
147
+ | Method | Description |
148
+ |---|---|
149
+ | `list_reports(workspace_id)` | List all reports in a workspace. |
150
+ | `get_report_metadata(workspace_id, report_id)` | Get metadata for a specific report. |
151
+ | `get_report_name(workspace_id, report_id)` | Get a report's display name. |
152
+ | `list_report_pages(workspace_id, report_id)` | List all pages in a report. |
153
+ | `get_report_json_pages_and_visuals(json_data, workspace_id, report_id)` | Parse a PBIR-Legacy report JSON and extract pages and visual details into a DataFrame. |
154
+ | `get_legacy_report_json(workspace_id, report_id, operations)` | Get and decode the full report definition for PBIR-Legacy reports. |
155
+ | `export_report(workspace_id, report_id, ...)` | Export a report as a `.pbix` file. |
156
+ | `get_report_measures(workspace_id, report_id, operations)` | Extract report-level measures and generate a DAX Query View script. Supports both PBIR and PBIR-Legacy formats. |
157
+ | `rebind_report(workspace_id, report_id, new_dataset_id, new_dataset_workspace_id, admin, dataset)` | Rebind a report to a new dataset/semantic model and migrate Read access to the new dataset. |
158
+
159
+ #### Dataflow
160
+
161
+ Manage Power BI and Fabric dataflows, including Gen1, Gen2, and Gen2 CI/CD.
162
+
163
+ | Method | Description |
164
+ |---|---|
165
+ | `list_dataflows(workspace_id)` | List all dataflows in a workspace (Gen1, Gen2 standard, and Gen2 CI/CD). Results are merged and deduplicated with a `source` column. |
166
+ | `get_dataflow_details(workspace_id, dataflow_id)` | Get details of a specific dataflow. |
167
+ | `get_dataflow_name(workspace_id, dataflow_id)` | Resolve the display name of a dataflow. |
168
+ | `create_dataflow(workspace_id, dataflow_content)` | Create a new Power BI dataflow. |
169
+ | `delete_dataflow(workspace_id, dataflow_id, type='pbi')` | Delete a dataflow. Use `type='fabric'` for Fabric API. |
170
+ | `export_dataflow_json(workspace_id, dataflow_id, dataflow_name)` | Export a dataflow definition as JSON. |
171
+ | `get_dataflow_gen2_definition(workspace_id, dataflow_id)` | Get the definition of a Dataflow Gen2 CI/CD item. |
172
+ | `create_dataflow_gen2_from_definition(workspace_id, display_name, definition)` | Create a Dataflow Gen2 CI/CD from a definition. |
173
+ | `update_dataflow_gen2_from_definition(workspace_id, dataflow_id, display_name, definition)` | Update an existing Dataflow Gen2 CI/CD definition. |
174
+ | `get_data_destinations(workspace_id, dataflow_id)` | Get the data destination details for each table in a dataflow. |
175
+ | `change_data_destination(workspace_id, dataflow_id, destination_type, ...)` | Change a dataflow's data destination (Lakehouse/Warehouse). Supports `preview`, `replace`, and `create` modes. |
176
+ | `create_dataflow_with_new_destination(workspace_id, dataflow_id, ...)` | Create a new Gen2 CI/CD dataflow from an existing one with a different data destination. |
177
+ | `upgrade_to_gen2_cicd(...)` | Upgrade a Gen1 or Gen2 (standard) dataflow to Gen2 CI/CD. |
178
+
179
+ #### Pipeline
180
+
181
+ Manage Fabric Data Pipelines.
182
+
183
+ | Method | Description |
184
+ |---|---|
185
+ | `list_pipelines(workspace_id)` | List all Fabric Data Pipelines in a workspace. |
186
+ | `get_pipeline(workspace_id, pipeline_id)` | Get the metadata of a specific pipeline. |
187
+ | `get_pipeline_definition(workspace_id, pipeline_id)` | Get the full definition of a Fabric Data Pipeline. |
188
+ | `update_pipeline_definition(workspace_id, pipeline_id, definition)` | Update an existing pipeline definition. |
189
+ | `get_pipeline_activities(workspace_id, pipeline_id_or_name)` | Get the list of activities from a pipeline. |
190
+ | `find_pipelines_by_dataflow(workspace_id, dataflow_id_or_name)` | Find all pipelines in a workspace that reference a specific dataflow. |
191
+ | `replace_dataflow_id_in_pipeline(workspace_id, pipeline_id, old_dataflow_id, new_dataflow_id)` | Replace a dataflow ID in all RefreshDataflow activities of a pipeline. |
192
+
193
+ #### Other modules
194
+
195
+ | Module | Description |
196
+ |---|---|
197
+ | `Capacity` | Monitor and manage Power BI and Fabric capacities. |
198
+ | `Operations` | Track long-running Fabric API operations. |
199
+ | `Admin` | Power BI Admin API operations. |
200
+ | `KQLDatabase` | Query Kusto (KQL) databases in Microsoft Fabric. |
201
+ | `Notebook` | Manage Fabric notebooks. |
202
+ | `Database` | Query and write to SQL databases (Lakehouse, Warehouse) via ODBC. |
203
+
204
+ ---
205
+
206
+ ### `msdev_kit.graph` — MS Graph (Entra)
207
+
208
+ Manage Entra ID (Azure AD) users and groups via the MS Graph API.
209
+
210
+ ```python
211
+ from msdev_kit import Auth
212
+ from msdev_kit.graph import GraphClient
213
+
214
+ auth = Auth(tenant_id, client_id, client_secret)
215
+ graph = GraphClient(auth)
216
+
217
+ user_id = graph.get_user_id('user@company.com')
218
+ group_id = graph.get_group_id('Data Team')
219
+ members = graph.list_group_members(group_id)
220
+ ```
221
+
222
+ | Method | Description |
223
+ |---|---|
224
+ | `get_user_id(email)` | Resolve user object ID by UPN/email, with mail fallback. |
225
+ | `get_group_id(group_name)` | Resolve Entra group object ID by display name. |
226
+ | `list_group_members(group_id)` | Paginated member list (id, displayName, mail, UPN). |
227
+ | `add_group_member(group_id, user_id)` | Add user to group. Silently ignores already-member errors. |
228
+ | `remove_group_member(group_id, user_id)` | Remove user from group. Silently ignores 404/403. |
229
+
230
+ ---
231
+
232
+ ### `msdev_kit.sharepoint` — SharePoint
233
+
234
+ Manage SharePoint files and folders via MS Graph API (no ACS/Office365 dependency).
235
+
236
+ ```python
237
+ from msdev_kit import Auth
238
+ from msdev_kit.sharepoint import SharePointClient
239
+
240
+ auth = Auth(tenant_id, client_id, client_secret)
241
+ sp = SharePointClient(auth, sp_hostname='company', sp_site_path='sites/DataTeam')
242
+
243
+ sp.download_file('/Reports/monthly.xlsx', local_dir='./downloads')
244
+ sp.upload_file('/Reports/updated.xlsx', source='./local/updated.xlsx')
245
+ sp.create_folder('/Reports/2026')
246
+ ```
247
+
248
+ | Method | Description |
249
+ |---|---|
250
+ | `download_file(file_path, local_dir)` | Download a file from the default document library. Returns local file path. |
251
+ | `upload_file(remote_path, source, content_type?)` | Upload/overwrite a file. `source` is a local file path (str) or raw bytes. |
252
+ | `create_folder(folder_path)` | Create a folder and all intermediate folders. |
253
+
254
+ Hostname and site path inputs are normalized automatically — accepts short names (`company`), FQDNs (`company.sharepoint.com`), or full URLs (`https://company.sharepoint.com`).
255
+
256
+ ---
257
+
258
+ ## Limitations
259
+
260
+ - The Power BI REST API has a **200 requests per hour** rate limit.
261
+ - Not all users can be updated via the API. See Microsoft docs: [Dataset permissions](https://learn.microsoft.com/en-us/power-bi/developer/embedded/datasets-permissions#get-and-update-dataset-permissions-with-apis).
262
+ - **Dataset query limits** (executeQueries API):
263
+ - Max **100,000 rows** or **1,000,000 values** (rows x columns) per query, whichever is hit first.
264
+ - Max **15 MB** of data per query.
265
+ - **120 query requests per minute** per user.
266
+ - Only **DAX** queries are supported (no MDX, INFO functions, or DMV).
267
+ - Datasets hosted in Azure Analysis Services or with a live connection to on-premises AAS are not supported.
268
+ - Service Principals are not supported for datasets with RLS or SSO enabled.
269
+
@@ -0,0 +1,22 @@
1
+ msdev_kit/__init__.py,sha256=HQjvf_65Nwvc7cxAZZQ9_TR4u3-EvkDll05TjC8O9xY,46
2
+ msdev_kit/auth.py,sha256=Otbx4XRj59xiewh6DyI7c4a0Nv17zSdnY6OS12h1IKo,1421
3
+ msdev_kit/fabric/__init__.py,sha256=MbagjG-lrWJGEejg8R4MtOPQXnNUW4pcbeKToUHJIZ4,333
4
+ msdev_kit/fabric/admin.py,sha256=K6CdlJAhFeA5BMfEPodEsQzWXsouXP6edkX6TDrfEAk,1323
5
+ msdev_kit/fabric/capacity.py,sha256=HZoHRIEWIJHI6GUuiwhAKMKND64A7epUbaMhXhfKd08,6511
6
+ msdev_kit/fabric/database.py,sha256=fcQBH8dJlm3W7MEy9i-0_rnCykcpnNPoGSg-JPA-msQ,3172
7
+ msdev_kit/fabric/dataflow.py,sha256=kkaTrJA80tVGqs3dri5KHYq03a0Vpe7bvVVfk_-XrNk,85144
8
+ msdev_kit/fabric/dataset.py,sha256=mA7Z6ehbxvPufrh3KuIBNATAlyQS8k1bUKpnSayOJG4,23283
9
+ msdev_kit/fabric/kql.py,sha256=eHJieINlglqaa1JjwPVtiJUj7yg0VgH_XpQzG5a7zos,2437
10
+ msdev_kit/fabric/notebook.py,sha256=IOTYyFL-0EY-n2GOFgFe5BpfRVfl0EFQyHv962pDf3Y,3534
11
+ msdev_kit/fabric/operations.py,sha256=g6AZsUGYgJG78rQe3MHq76PLGW0tTyLMVExpgQkGrpU,3267
12
+ msdev_kit/fabric/pipeline.py,sha256=T2wpt6XiQGT0zeZOCZ56_IiWgeCwxzXHLo2IS8C02v0,22745
13
+ msdev_kit/fabric/report.py,sha256=A0UNAvlmAxDBhqqZA6ZtDt8h76LcibcDpahjnnP9EkA,39386
14
+ msdev_kit/fabric/utilities.py,sha256=fs_9hgIJOH0KTDzHP-kbecltPQSOVmJ7MVoDzlk8ABQ,243
15
+ msdev_kit/fabric/workspace.py,sha256=ft6tMzcN3mjWDydutWg5T3bfhPCYUUtIm3yTRhjGo_c,19307
16
+ msdev_kit/graph/__init__.py,sha256=_RKbx-v6AbmSXE1w7ryTflpoSLfTSGUzY2-akSsKca0,32
17
+ msdev_kit/graph/client.py,sha256=276xyD4N_QK-K6z2FEmSu3MQTMF2MdSm_qilL04bX60,3473
18
+ msdev_kit/sharepoint/__init__.py,sha256=3exFqHAlKbS0DOI8QlqEPFMLM-I63492lHseW5_OP6s,37
19
+ msdev_kit/sharepoint/client.py,sha256=TQNa2BP2HPPlqOsCmnaEq0MMsSCQBuNXrnHC5ZIUNms,3903
20
+ msdev_kit-0.1.0.dist-info/METADATA,sha256=RrYRNxbNHV5hrPOIXAgvW4qufIlQKpj7UCmCc52YXzc,12043
21
+ msdev_kit-0.1.0.dist-info/WHEEL,sha256=Vz2fHgx6HFtSwhs8KvkHLqH5Ea4w1_rner5uNVGCeIE,88
22
+ msdev_kit-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.3.2
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any