ms-graph 1.5.2__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.
ms_graph/session.py ADDED
@@ -0,0 +1,182 @@
1
+ """ Session Class to initiate GraphSession object. """
2
+
3
+ import json as json_lib
4
+ from ms_graph.logger.logger_setup import log
5
+ from typing import Dict, List, Union
6
+
7
+ import requests
8
+
9
+ class GraphSession():
10
+
11
+ """Serves as the Session for the Current Microsoft
12
+ Graph API."""
13
+
14
+ def __init__(self, client: object) -> None:
15
+ """Initializes the `GraphSession` client.
16
+
17
+ ### Overview:
18
+ ----
19
+ The GraphSession object handles all the requests made
20
+ for the different endpoints on the Microsoft Graph API.
21
+
22
+ ### Arguments:
23
+ ----
24
+ client (str): The Microsoft Graph API Python Client.
25
+
26
+ ### Usage:
27
+ ----
28
+ >>> graph_session = GraphSession()
29
+ """
30
+ from ms_graph.client import MicrosoftGraphClient
31
+
32
+ self.client: MicrosoftGraphClient = client
33
+
34
+ def build_headers(self, additional_args: dict = None) -> Dict:
35
+ """Used to build the headers needed to make the request.
36
+
37
+ ### Parameters
38
+ ----
39
+ additional_args : dict (optional, Default=None)
40
+ Any additional headers that need to be sent in the
41
+ request.
42
+
43
+ ### Returns
44
+ ----
45
+ dict :
46
+ A dictionary containing all the components.
47
+ """
48
+
49
+ # Define the base headers.
50
+ headers = {
51
+ "Authorization": f"Bearer {self.client.access_token}"
52
+ }
53
+
54
+ if additional_args:
55
+ headers.update(additional_args)
56
+
57
+ return headers
58
+
59
+ def build_url(self, endpoint: str) -> str:
60
+ """Build the URL used the make string.
61
+
62
+ ### Parameters
63
+ ----
64
+ endpoint : str
65
+ The endpoint used to make the full URL.
66
+
67
+ ### Returns
68
+ ----
69
+ str:
70
+ The full URL with the endpoint needed.
71
+ """
72
+
73
+ url = self.client.RESOURCE + self.client.api_version + "/" + endpoint
74
+ log.debug("Prepared URL - %s", url)
75
+ return url
76
+
77
+ def make_request(
78
+ self,
79
+ method: str,
80
+ endpoint: str,
81
+ params: dict = None,
82
+ data: dict = None,
83
+ json: dict = None,
84
+ additional_headers: dict = None,
85
+ expect_no_response: bool = False
86
+ ) -> Union[Dict, List]:
87
+ """Handles all the requests in the library.
88
+
89
+ ### Overview:
90
+ ---
91
+ A central function used to handle all the requests made in the library,
92
+ this function handles building the URL, defining Content-Type, passing
93
+ through payloads, and handling any errors that may arise during the request.
94
+
95
+ ### Arguments:
96
+ ----
97
+ method : str
98
+ The Request method, can be one of the
99
+ following: ["get","post","put","delete","patch"]
100
+
101
+ endpoint : str
102
+ The API URL endpoint, example is "quotes"
103
+
104
+ params : dict (optional, Default=None)
105
+ The URL params for the request.
106
+
107
+ data : dict (optional, Default=None)
108
+ A data payload for a request.
109
+
110
+ json : dict (optional, Default=None)
111
+ A json data payload for a request
112
+
113
+ expect_no_response: bool (optional, Default=False)
114
+ Some responses will only return a status code,
115
+ so if this is set to True it will only return
116
+ the status code.
117
+
118
+ ### Returns:
119
+ ----
120
+ Union[List, Dict]:
121
+ The resource object or objects.
122
+ """
123
+
124
+ # Build the URL.
125
+ url = self.build_url(endpoint=endpoint)
126
+
127
+ # Define the headers.
128
+ headers = self.build_headers(additional_args=additional_headers)
129
+
130
+ # Define a new session.
131
+ request_session = requests.Session()
132
+ request_session.verify = True
133
+
134
+ # Define a new request.
135
+ request_request = requests.Request(
136
+ method=method.upper(),
137
+ headers=headers,
138
+ url=url,
139
+ params=params,
140
+ data=data,
141
+ json=json
142
+ ).prepare()
143
+
144
+ # Send the request.
145
+ response: requests.Response = request_session.send(
146
+ request=request_request
147
+ )
148
+
149
+ if request_request.body is not None:
150
+ log.debug(request_request.body)
151
+ log.debug(response.content)
152
+
153
+ # Close the session.
154
+ request_session.close()
155
+
156
+ # If it"s okay and no details.
157
+ if response.ok and expect_no_response:
158
+ return {"status_code": response.status_code}
159
+ elif response.ok and len(response.content) > 0:
160
+ return response.json()
161
+ elif len(response.content) == 0 and response.ok:
162
+ return {
163
+ "message": "Request was successful, status code provided.",
164
+ "status_code": response.status_code
165
+ }
166
+ elif not response.ok:
167
+
168
+ # Define the error dict.
169
+ error_dict = {
170
+ "error_code": response.status_code,
171
+ "response_url": response.url,
172
+ "response_body": json_lib.loads(response.content.decode("ascii")),
173
+ "response_request": dict(response.request.headers),
174
+ "response_method": response.request.method,
175
+ }
176
+
177
+ # Log the error.
178
+ log.error(
179
+ msg=json_lib.dumps(obj=error_dict, indent=4)
180
+ )
181
+
182
+ raise requests.HTTPError()
ms_graph/users.py ADDED
@@ -0,0 +1,45 @@
1
+ from ms_graph.session import GraphSession
2
+
3
+ class Users():
4
+
5
+ """
6
+ ## Overview:
7
+ ----
8
+ You can use Microsoft Graph to build compelling app experiences
9
+ based on users, their relationships with other users and groups,
10
+ and their mail, calendar, and files.
11
+ """
12
+
13
+ def __init__(self, session: object) -> None:
14
+ """Initializes the `Users` object.
15
+
16
+ ### Parameters
17
+ ----
18
+ session : object
19
+ An authenticated session for our Microsoft Graph Client.
20
+ """
21
+
22
+ # Set the session.
23
+ self.graph_session: GraphSession = session
24
+
25
+ # Set the endpoint.
26
+ self.endpoint = "users"
27
+
28
+ def list_users(self) -> dict:
29
+ """Retrieve a list of user objects.
30
+
31
+ ### Returns
32
+ ----
33
+ dict :
34
+ If successful, this method returns a 200 OK response code
35
+ and collection of user objects in the response body. If a
36
+ large user collection is returned, you can use paging in your
37
+ app.
38
+ """
39
+
40
+ content = self.graph_session.make_request(
41
+ method="get",
42
+ endpoint=self.endpoint
43
+ )
44
+
45
+ return content
@@ -0,0 +1,331 @@
1
+ from enum import Enum
2
+ from typing import Union
3
+ from dataclasses import fields
4
+ from dataclasses import dataclass
5
+ from dataclasses import is_dataclass
6
+
7
+
8
+ def _to_dict(data_class_obj: Union[dataclass, dict]) -> dict:
9
+ """Converts a `dataclass` object to a normal python `dict`.
10
+ ### Parameter
11
+ ----
12
+ data_class_obj : Union[dataclass, dict]
13
+ The python `dataclass` object or a normal
14
+ python `dict` that may contain `dataclass`
15
+ objects.
16
+ ### Returns
17
+ ----
18
+ dict :
19
+ A python dict that can be sent to the Microsoft
20
+ Graph API.
21
+ """
22
+
23
+ class_dict = {}
24
+
25
+ if is_dataclass(data_class_obj):
26
+
27
+ # Loop through each field and grab the value and key.
28
+ for field in fields(data_class_obj):
29
+
30
+ key = field.name
31
+ value = getattr(data_class_obj, field.name)
32
+
33
+ # Handle values that could be Enums.
34
+ if isinstance(value, Enum):
35
+ value = value.value
36
+
37
+ if isinstance(value, dict):
38
+ value = _to_dict(data_class_obj=value)
39
+
40
+ if isinstance(value, list):
41
+ value = [_to_dict(data_class_obj=item) for item in value]
42
+
43
+ if value is not None:
44
+ class_dict[key] = value
45
+
46
+ elif isinstance(data_class_obj, dict):
47
+
48
+ for key, value in data_class_obj.items():
49
+
50
+ # Handle values that could be Enums.
51
+ if isinstance(value, Enum):
52
+ value = value.value
53
+
54
+ if isinstance(value, dict):
55
+ value = _to_dict(data_class_obj=value)
56
+
57
+ if isinstance(value, list):
58
+ value = [_to_dict(data_class_obj=item) for item in value]
59
+
60
+ if value is not None:
61
+ class_dict[key] = value
62
+
63
+ return class_dict
64
+
65
+
66
+ @dataclass
67
+ class RangeProperties:
68
+
69
+ """
70
+ ### Overview
71
+ ----
72
+ A python dataclass which is used to represent Range Properties.
73
+ The Microsoft Graph API allows users to update Range objects and
74
+ this utility makes constructing those updates in a concise way that
75
+ is python friendly.
76
+ ### Parameters
77
+ ----
78
+ column_hidden : bool (optional, Default=None)
79
+ Represents if all columns of the current range are hidden.
80
+ formulas : list (optional, Default=None)
81
+ Represents the formula in A1-style notation.
82
+ formulas_local : list (optional, Default=None)
83
+ Represents the formula in A1-style notation, in the user's
84
+ language and number-formatting locale. For example, the
85
+ English "=SUM(A1, 1.5)" formula would become
86
+ "=SUMME(A1; 1,5)" in German.
87
+ formulas_r1c1 : list (optional, Default=None)
88
+ Represents the formula in R1C1-style notation.
89
+ number_format : str (optional, Default=None)
90
+ Represents Excel's number format code for the given cell.
91
+ row_hidden : bool (optional, Default=None)
92
+ Represents if all rows of the current range are hidden.
93
+ values : list (optional, Default=None)
94
+ Represents the raw values of the specified range. The
95
+ data returned could be of type string, number, or a
96
+ boolean. Cell that contain an error will return the
97
+ error string.
98
+ """
99
+
100
+ column_hidden: bool
101
+ row_hidden: bool
102
+ formulas: list
103
+ formulas_local: list
104
+ formulas_r1c1: list
105
+ number_format: str
106
+ values: list
107
+
108
+ def to_dict(self) -> dict:
109
+ """Generates a dictionary containing all the field
110
+ names and values.
111
+ ### Returns
112
+ ----
113
+ dict :
114
+ A dictionary object where the Fieldnames
115
+ are the keys and Field values are the
116
+ values.
117
+ """
118
+
119
+ return _to_dict(data_class_obj=self)
120
+
121
+
122
+ @dataclass
123
+ class RangeFormatProperties:
124
+
125
+ """
126
+ ### Overview
127
+ ----
128
+ A python dataclass which is used to represent Range Format
129
+ Properties. A format object encapsulating the range's font,
130
+ fill, borders, alignment, and other properties.
131
+ ### Parameters
132
+ ----
133
+ column_width : float (optional, Default=None)
134
+ Sets the width of all columns within the range. If the
135
+ column widths are not uniform, null will be returned.
136
+ horizontal_alignment : Union[str, Enum] (optional, Default='General')
137
+ Represents the horizontal alignment for the specified
138
+ object. The possible values are: `General`, `Left`, `Center`,
139
+ `Right`, `Fill`, `Justify`, `CenterAcrossSelection`,
140
+ and `Distributed`.
141
+ row_height : float (optional, Default=None)
142
+ Sets the height of all rows in the range. If the
143
+ row heights are not uniform, null will be returned.
144
+ vertical_alignment : Union[str, Enum] (optional, Default='General')
145
+ Represents the vertical alignment for the specified
146
+ object. The possible values are: `Top`, `Center`, `Bottom`,
147
+ `Justify`, and `Distributed`.
148
+ wrap_text : bool (optional, Default=False)
149
+ Indicates if Excel wraps the text in the object.
150
+ A null value indicates that the entire range doesn't
151
+ have uniform wrap setting
152
+ """
153
+
154
+ column_width: float = None
155
+ horizontal_alignment: Union[str, Enum] = "General"
156
+ row_height: float = None
157
+ vertical_alignment: Union[str, Enum] = "General"
158
+ wrap_text: bool = False
159
+
160
+ def to_dict(self) -> dict:
161
+ """Generates a dictionary containing all the field
162
+ names and values.
163
+ ### Returns
164
+ ----
165
+ dict :
166
+ A dictionary object where the Fieldnames
167
+ are the keys and Field values are the
168
+ values.
169
+ """
170
+
171
+ return _to_dict(data_class_obj=self)
172
+
173
+ @dataclass
174
+ class RangeFillProperties:
175
+
176
+ """
177
+ ### Overview
178
+ ----
179
+ A python dataclass which is used to represent Range Fill
180
+ Properties. Represents the background of a range object.
181
+ ### Parameters
182
+ ----
183
+ color : str (optional, Default=None)
184
+ HTML color code representing the color of the border
185
+ line, of the form #RRGGBB (e.g. "FFA500") or as a
186
+ named HTML color (e.g. "orange").
187
+ """
188
+
189
+ column_width: str = None
190
+
191
+ def to_dict(self) -> dict:
192
+ """Generates a dictionary containing all the field
193
+ names and values.
194
+ ### Returns
195
+ ----
196
+ dict :
197
+ A dictionary object where the Fieldnames
198
+ are the keys and Field values are the
199
+ values.
200
+ """
201
+
202
+ return _to_dict(data_class_obj=self)
203
+
204
+ @dataclass
205
+ class RangeFontProperties:
206
+
207
+ """
208
+ ### Overview
209
+ ----
210
+ A python dataclass which is used to represent Range Font
211
+ Properties. This object represents the font attributes
212
+ (font name, font size, color, etc.) for an object.
213
+ ### Parameters
214
+ ----
215
+ bold : bool (optional, Default=False)
216
+ Represents the bold status of font. If set to `True`
217
+ font will be bold, `False` it will not.
218
+ color : str (optional, Default=None)
219
+ HTML color code representation of the text color.
220
+ E.g. #FF0000 represents Red.
221
+ italic : bool (optional, Default=False)
222
+ Represents the italic status of font. If set to `True`
223
+ font will be italic, `False` it will not.
224
+ name : str (optional, Default=None)
225
+ The font name. For example, `Calibri`.
226
+ size : float (optional, Default=None)
227
+ Sets the size of the font.
228
+ underline : Union[str, Enum] (optional, Default='None')
229
+ Type of underline applied to the font. The possible
230
+ values are: `None`, `Single`, `Double`,
231
+ `SingleAccountant`, `DoubleAccountant`.
232
+ """
233
+
234
+ bold: bool = False
235
+ color: str = None
236
+ italic: bool = False
237
+ name: str = None
238
+ size: float = None
239
+ underline: Union[str, Enum] = "None"
240
+
241
+ def to_dict(self) -> dict:
242
+ """Generates a dictionary containing all the field
243
+ names and values.
244
+ ### Returns
245
+ ----
246
+ dict :
247
+ A dictionary object where the Fieldnames
248
+ are the keys and Field values are the
249
+ values.
250
+ """
251
+
252
+ return _to_dict(data_class_obj=self)
253
+
254
+ @dataclass
255
+ class RangeBorderProperties:
256
+
257
+ """
258
+ ### Overview
259
+ ----
260
+ A python dataclass which is used to represent Range Border
261
+ Properties. Represents the border of an object.
262
+ ### Parameters
263
+ ----
264
+ color : str (optional, Default=None)
265
+ HTML color code representing the color of the border
266
+ line, of the form #RRGGBB (e.g. "FFA500") or as a
267
+ named HTML color (e.g. "orange"). the text color.
268
+ style : Union[str, Enum] (optional, Default="None")
269
+ One of the constants of line style specifying the
270
+ line style for the border. The possible values
271
+ are: `None`, `Continuous`, `Dash`, `DashDot`,
272
+ `DashDotDot`, `Dot`, `Double`, `SlantDashDot`.
273
+ weight : Union[str, Enum] (optional, Default=None)
274
+ Specifies the weight of the border around a
275
+ range. The possible values are: `Hairline`,
276
+ `Thin`, `Medium`, and `Thick`.
277
+ """
278
+
279
+ color: str = None
280
+ style: Union[str, Enum] = "None"
281
+ weight: Union[str, Enum] = None
282
+
283
+ def to_dict(self) -> dict:
284
+ """Generates a dictionary containing all the field
285
+ names and values.
286
+ ### Returns
287
+ ----
288
+ dict :
289
+ A dictionary object where the Fieldnames
290
+ are the keys and Field values are the
291
+ values.
292
+ """
293
+
294
+ return _to_dict(data_class_obj=self)
295
+
296
+ @dataclass
297
+ class RangeFormatProtectionProperties:
298
+
299
+ """
300
+ ### Overview
301
+ ----
302
+ A python dataclass which is used to represent Range Format
303
+ Protection Properties. Represents the format protection
304
+ of a range object.
305
+ ### Parameters
306
+ ----
307
+ formula_hidden : bool (optional, Default=False)
308
+ Indicates if Excel hides the formula for the cells
309
+ in the range. A null value indicates that the entire
310
+ range doesn't have uniform formula hidden setting.
311
+ locked : bool (optional, Default=False)
312
+ Indicates if Excel locks the cells in the object.
313
+ A null value indicates that the entire range
314
+ doesn't have uniform lock setting.
315
+ """
316
+
317
+ formula_hidden: bool = False
318
+ locked: bool = False
319
+
320
+ def to_dict(self) -> dict:
321
+ """Generates a dictionary containing all the field
322
+ names and values.
323
+ ### Returns
324
+ ----
325
+ dict :
326
+ A dictionary object where the Fieldnames
327
+ are the keys and Field values are the
328
+ values.
329
+ """
330
+
331
+ return _to_dict(data_class_obj=self)
@@ -0,0 +1,23 @@
1
+ """Workbooks and charts subpackage for ms_graph."""
2
+
3
+ from ms_graph.workbooks_and_charts.workbook import Workbooks
4
+ from ms_graph.workbooks_and_charts.worksheets import Worksheet
5
+ from ms_graph.workbooks_and_charts.table import Table
6
+ from ms_graph.workbooks_and_charts.range import Range
7
+ from ms_graph.workbooks_and_charts.enums import (
8
+ CalculationTypes,
9
+ WorksheetVisibility,
10
+ RangeShift,
11
+ Underline,
12
+ )
13
+
14
+ __all__ = [
15
+ "Workbooks",
16
+ "Worksheet",
17
+ "Table",
18
+ "Range",
19
+ "CalculationTypes",
20
+ "WorksheetVisibility",
21
+ "RangeShift",
22
+ "Underline",
23
+ ]
@@ -0,0 +1,109 @@
1
+ from enum import Enum
2
+ from typing import Union
3
+ from ms_graph.session import GraphSession
4
+
5
+
6
+ class WorkbookApplication:
7
+
8
+ """
9
+ ## Overview:
10
+ ----
11
+ Represents the Excel application that manages
12
+ the workbook.
13
+ """
14
+
15
+ def __init__(self, session: object) -> None:
16
+ """Initializes the `WorkbookApplication` object.
17
+
18
+ ### Parameters
19
+ ----
20
+ session : object
21
+ An authenticated session for our Microsoft Graph Client.
22
+ """
23
+
24
+ # Set the session.
25
+ self.graph_session: GraphSession = session
26
+
27
+ def get(self, item_id: str = None, item_path: str = None) -> dict:
28
+ """Retrieve the properties and relationships of a workbookApplication
29
+ object using the Item ID or Item Path.
30
+
31
+ ### Parameters
32
+ ----
33
+ item_id : str (optional, Default=None)
34
+ The Drive Item Resource ID.
35
+
36
+ item_path : str (optional, Default=None)
37
+ The Item Path. An Example would be the following:
38
+ `/TestFolder/TestFile.txt`
39
+
40
+ ### Returns
41
+ ----
42
+ dict:
43
+ A workbookApplication resource object.
44
+ """
45
+
46
+ if item_id:
47
+ content = self.graph_session.make_request(
48
+ method="get",
49
+ endpoint=f"/me/drive/items/{item_id}/workbook/application",
50
+ )
51
+ elif item_path:
52
+ content = self.graph_session.make_request(
53
+ method="get",
54
+ endpoint=f"/me/drive/root:/{item_path}:/workbook/application",
55
+ )
56
+
57
+ return content
58
+
59
+ def calculate(
60
+ self,
61
+ calculation_type: Union[str, Enum],
62
+ item_id: str = None,
63
+ item_path: str = None
64
+ ) -> dict:
65
+ """Recalculate all currently opened workbooks in Excel using the
66
+ Item ID or Item Path.
67
+
68
+ ### Parameters
69
+ ----
70
+ calculation_type :
71
+ Specifies the calculation type to use. Possible
72
+ values are: `Recalculate`, `Full`, `FullRebuild`.
73
+
74
+ item_id : str (optional, Default=None)
75
+ The Drive Item Resource ID.
76
+
77
+ item_path : str (optional, Default=None)
78
+ The Item Path. An Example would be the following:
79
+ `/TestFolder/TestFile.txt`
80
+
81
+ ### Returns
82
+ ----
83
+ dict:
84
+ A response object status code, 200 for success.
85
+ """
86
+
87
+ if isinstance(calculation_type, Enum):
88
+ data = {"calculationType": calculation_type.value}
89
+ else:
90
+ data = {"calculationType": calculation_type}
91
+
92
+ if item_id:
93
+ content = self.graph_session.make_request(
94
+ method="get",
95
+ endpoint=f"/me/drive/items/{item_id}/workbook/application",
96
+ json=data,
97
+ additional_headers={"Content-type": "application/json"},
98
+ expect_no_response=True,
99
+ )
100
+ elif item_path:
101
+ content = self.graph_session.make_request(
102
+ method="get",
103
+ endpoint=f"/me/drive/root:/{item_path}:/workbook/application",
104
+ json=data,
105
+ additional_headers={"Content-type": "application/json"},
106
+ expect_no_response=True,
107
+ )
108
+
109
+ return content