ms-graph 1.6.2__tar.gz → 1.6.3__tar.gz

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.
Files changed (26) hide show
  1. {ms_graph-1.6.2 → ms_graph-1.6.3}/PKG-INFO +1 -1
  2. ms_graph-1.6.3/ms_graph/session.py +301 -0
  3. {ms_graph-1.6.2 → ms_graph-1.6.3}/pyproject.toml +1 -1
  4. ms_graph-1.6.2/ms_graph/session.py +0 -182
  5. {ms_graph-1.6.2 → ms_graph-1.6.3}/LICENSE +0 -0
  6. {ms_graph-1.6.2 → ms_graph-1.6.3}/README.md +0 -0
  7. {ms_graph-1.6.2 → ms_graph-1.6.3}/ms_graph/__init__.py +0 -0
  8. {ms_graph-1.6.2 → ms_graph-1.6.3}/ms_graph/client.py +0 -0
  9. {ms_graph-1.6.2 → ms_graph-1.6.3}/ms_graph/drive_items.py +0 -0
  10. {ms_graph-1.6.2 → ms_graph-1.6.3}/ms_graph/drives.py +0 -0
  11. {ms_graph-1.6.2 → ms_graph-1.6.3}/ms_graph/groups.py +0 -0
  12. {ms_graph-1.6.2 → ms_graph-1.6.3}/ms_graph/logger/logger_setup.py +0 -0
  13. {ms_graph-1.6.2 → ms_graph-1.6.3}/ms_graph/mail.py +0 -0
  14. {ms_graph-1.6.2 → ms_graph-1.6.3}/ms_graph/notes.py +0 -0
  15. {ms_graph-1.6.2 → ms_graph-1.6.3}/ms_graph/personal_contacts.py +0 -0
  16. {ms_graph-1.6.2 → ms_graph-1.6.3}/ms_graph/search.py +0 -0
  17. {ms_graph-1.6.2 → ms_graph-1.6.3}/ms_graph/users.py +0 -0
  18. {ms_graph-1.6.2 → ms_graph-1.6.3}/ms_graph/utils/range.py +0 -0
  19. {ms_graph-1.6.2 → ms_graph-1.6.3}/ms_graph/workbooks_and_charts/__init__.py +0 -0
  20. {ms_graph-1.6.2 → ms_graph-1.6.3}/ms_graph/workbooks_and_charts/application.py +0 -0
  21. {ms_graph-1.6.2 → ms_graph-1.6.3}/ms_graph/workbooks_and_charts/comments.py +0 -0
  22. {ms_graph-1.6.2 → ms_graph-1.6.3}/ms_graph/workbooks_and_charts/enums.py +0 -0
  23. {ms_graph-1.6.2 → ms_graph-1.6.3}/ms_graph/workbooks_and_charts/range.py +0 -0
  24. {ms_graph-1.6.2 → ms_graph-1.6.3}/ms_graph/workbooks_and_charts/table.py +0 -0
  25. {ms_graph-1.6.2 → ms_graph-1.6.3}/ms_graph/workbooks_and_charts/workbook.py +0 -0
  26. {ms_graph-1.6.2 → ms_graph-1.6.3}/ms_graph/workbooks_and_charts/worksheets.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ms-graph
3
- Version: 1.6.2
3
+ Version: 1.6.3
4
4
  Summary: A Python Client Application that allows interaction with the Microsoft Graph API.
5
5
  License: MIT
6
6
  License-File: LICENSE
@@ -0,0 +1,301 @@
1
+ """ Session Class to initiate GraphSession object. """
2
+
3
+ import json as json_lib
4
+ from typing import Dict, List, Optional, Union
5
+
6
+ import requests
7
+
8
+ from ms_graph.logger.logger_setup import log
9
+
10
+ # Headers whose values are credentials. These must never reach a log sink: a
11
+ # Graph access token stays valid for roughly an hour, and container logs get
12
+ # copied into bug reports, support bundles and pasted terminal output long
13
+ # before that expires.
14
+ SENSITIVE_HEADERS = frozenset(
15
+ {
16
+ "authorization",
17
+ "proxy-authorization",
18
+ "cookie",
19
+ "set-cookie",
20
+ "x-api-key",
21
+ }
22
+ )
23
+
24
+ REDACTED = "<redacted>"
25
+
26
+ # Ceiling on how much of a body reaches the debug log. Graph returns whole
27
+ # file listings and workbook ranges; logging those in full buries everything
28
+ # else and can spill user content into the log.
29
+ MAX_LOGGED_BODY = 2048
30
+
31
+ # Without a timeout a stalled connection hangs the caller forever. Long-lived
32
+ # pollers are the usual victim -- they simply stop, with no error to show.
33
+ #
34
+ # Deliberately generous. requests applies this to the connect and to the gap
35
+ # between bytes, not to total duration, and some Graph endpoints (copy
36
+ # operations, large workbook recalculations, tenant-wide search) sit quiet for
37
+ # a while before the first byte. A tight value here would turn working calls
38
+ # in existing consumers into timeouts; this only converts an indefinite hang
39
+ # into a bounded failure. Pass `timeout` explicitly to tighten it per call.
40
+ DEFAULT_TIMEOUT = 120
41
+
42
+
43
+ def redact_headers(headers: Optional[Dict[str, str]]) -> Dict[str, str]:
44
+ """Copy `headers`, replacing credential values with a placeholder.
45
+
46
+ ### Parameters
47
+ ----
48
+ headers : dict
49
+ The headers to sanitise. Matching is case-insensitive, since
50
+ `requests` preserves whatever casing the server or caller used.
51
+
52
+ ### Returns
53
+ ----
54
+ dict :
55
+ The same mapping with sensitive values replaced by `REDACTED`.
56
+ """
57
+
58
+ if not headers:
59
+ return {}
60
+
61
+ return {
62
+ key: (REDACTED if key.lower() in SENSITIVE_HEADERS else value)
63
+ for key, value in headers.items()
64
+ }
65
+
66
+
67
+ def truncate_body(body: Union[str, bytes, None]) -> str:
68
+ """Render a request or response body for logging, bounded in size.
69
+
70
+ ### Parameters
71
+ ----
72
+ body : str | bytes | None
73
+ The payload to render.
74
+
75
+ ### Returns
76
+ ----
77
+ str :
78
+ The decoded body, cut off at `MAX_LOGGED_BODY` characters with a note
79
+ recording the original length.
80
+ """
81
+
82
+ if body is None:
83
+ return ""
84
+
85
+ if isinstance(body, bytes):
86
+ # errors="replace" rather than "ascii": Graph returns UTF-8, and file
87
+ # names routinely carry non-ASCII characters.
88
+ text = body.decode("utf-8", errors="replace")
89
+ else:
90
+ text = str(body)
91
+
92
+ if len(text) <= MAX_LOGGED_BODY:
93
+ return text
94
+
95
+ return f"{text[:MAX_LOGGED_BODY]}... [truncated, {len(text)} characters total]"
96
+
97
+
98
+ class GraphSession:
99
+
100
+ """Serves as the Session for the Current Microsoft
101
+ Graph API."""
102
+
103
+ def __init__(self, client: object) -> None:
104
+ """Initializes the `GraphSession` client.
105
+
106
+ ### Overview:
107
+ ----
108
+ The GraphSession object handles all the requests made
109
+ for the different endpoints on the Microsoft Graph API.
110
+
111
+ ### Arguments:
112
+ ----
113
+ client (str): The Microsoft Graph API Python Client.
114
+
115
+ ### Usage:
116
+ ----
117
+ >>> graph_session = GraphSession()
118
+ """
119
+ from ms_graph.client import MicrosoftGraphClient
120
+
121
+ self.client: MicrosoftGraphClient = client
122
+
123
+ # One session for the life of the object rather than one per call, so
124
+ # the TLS handshake and connection pool are reused across requests.
125
+ self._request_session = requests.Session()
126
+ self._request_session.verify = True
127
+
128
+ def close(self) -> None:
129
+ """Release the underlying HTTP connection pool."""
130
+
131
+ self._request_session.close()
132
+
133
+ def build_headers(self, additional_args: dict = None) -> Dict:
134
+ """Used to build the headers needed to make the request.
135
+
136
+ ### Parameters
137
+ ----
138
+ additional_args : dict (optional, Default=None)
139
+ Any additional headers that need to be sent in the
140
+ request.
141
+
142
+ ### Returns
143
+ ----
144
+ dict :
145
+ A dictionary containing all the components.
146
+ """
147
+
148
+ # Define the base headers.
149
+ headers = {
150
+ "Authorization": f"Bearer {self.client.access_token}"
151
+ }
152
+
153
+ if additional_args:
154
+ headers.update(additional_args)
155
+
156
+ return headers
157
+
158
+ def build_url(self, endpoint: str) -> str:
159
+ """Build the URL used the make string.
160
+
161
+ ### Parameters
162
+ ----
163
+ endpoint : str
164
+ The endpoint used to make the full URL.
165
+
166
+ ### Returns
167
+ ----
168
+ str:
169
+ The full URL with the endpoint needed.
170
+ """
171
+
172
+ url = self.client.RESOURCE + self.client.api_version + "/" + endpoint
173
+ log.debug("Prepared URL - %s", url)
174
+ return url
175
+
176
+ def make_request(
177
+ self,
178
+ method: str,
179
+ endpoint: str,
180
+ params: dict = None,
181
+ data: dict = None,
182
+ json: dict = None,
183
+ additional_headers: dict = None,
184
+ expect_no_response: bool = False,
185
+ timeout: Optional[float] = DEFAULT_TIMEOUT,
186
+ ) -> Union[Dict, List]:
187
+ """Handles all the requests in the library.
188
+
189
+ ### Overview:
190
+ ---
191
+ A central function used to handle all the requests made in the library,
192
+ this function handles building the URL, defining Content-Type, passing
193
+ through payloads, and handling any errors that may arise during the request.
194
+
195
+ ### Arguments:
196
+ ----
197
+ method : str
198
+ The Request method, can be one of the
199
+ following: ["get","post","put","delete","patch"]
200
+
201
+ endpoint : str
202
+ The API URL endpoint, example is "quotes"
203
+
204
+ params : dict (optional, Default=None)
205
+ The URL params for the request.
206
+
207
+ data : dict (optional, Default=None)
208
+ A data payload for a request.
209
+
210
+ json : dict (optional, Default=None)
211
+ A json data payload for a request
212
+
213
+ expect_no_response: bool (optional, Default=False)
214
+ Some responses will only return a status code,
215
+ so if this is set to True it will only return
216
+ the status code.
217
+
218
+ timeout : float (optional, Default=30)
219
+ Seconds to wait for the server before giving up. Pass `None` to
220
+ wait indefinitely.
221
+
222
+ ### Returns:
223
+ ----
224
+ Union[List, Dict]:
225
+ The resource object or objects.
226
+
227
+ ### Raises:
228
+ ----
229
+ requests.HTTPError:
230
+ If the API returns a non-2xx status. The exception carries the
231
+ status line, the method and the URL, and the originating response
232
+ is attached as `.response`.
233
+ """
234
+
235
+ # Build the URL.
236
+ url = self.build_url(endpoint=endpoint)
237
+
238
+ # Define the headers.
239
+ headers = self.build_headers(additional_args=additional_headers)
240
+
241
+ # Define a new request.
242
+ request_request = requests.Request(
243
+ method=method.upper(),
244
+ headers=headers,
245
+ url=url,
246
+ params=params,
247
+ data=data,
248
+ json=json
249
+ ).prepare()
250
+
251
+ # Send the request.
252
+ response: requests.Response = self._request_session.send(
253
+ request=request_request,
254
+ timeout=timeout,
255
+ )
256
+
257
+ if request_request.body is not None:
258
+ log.debug("Request body - %s", truncate_body(request_request.body))
259
+ log.debug("Response body - %s", truncate_body(response.content))
260
+
261
+ # If it"s okay and no details.
262
+ if response.ok and expect_no_response:
263
+ return {"status_code": response.status_code}
264
+ elif response.ok and len(response.content) > 0:
265
+ return response.json()
266
+ elif len(response.content) == 0 and response.ok:
267
+ return {
268
+ "message": "Request was successful, status code provided.",
269
+ "status_code": response.status_code
270
+ }
271
+ elif not response.ok:
272
+
273
+ # An error body is not guaranteed to be JSON -- a gateway or proxy
274
+ # in front of Graph may return HTML -- so fall back to raw text
275
+ # rather than letting the decode failure mask the real error.
276
+ try:
277
+ response_body = response.json()
278
+ except ValueError:
279
+ response_body = truncate_body(response.content)
280
+
281
+ # Define the error dict. Request headers are redacted: this dict is
282
+ # written straight to the error log, and the Authorization header
283
+ # holds a live bearer token.
284
+ error_dict = {
285
+ "error_code": response.status_code,
286
+ "response_url": response.url,
287
+ "response_body": response_body,
288
+ "request_headers": redact_headers(response.request.headers),
289
+ "response_method": response.request.method,
290
+ }
291
+
292
+ # Log the error.
293
+ log.error(
294
+ msg=json_lib.dumps(obj=error_dict, indent=4)
295
+ )
296
+
297
+ raise requests.HTTPError(
298
+ f"{response.status_code} {response.reason} for "
299
+ f"{response.request.method} {response.url}",
300
+ response=response,
301
+ )
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "ms-graph"
3
- version = "1.6.2"
3
+ version = "1.6.3"
4
4
  description = "A Python Client Application that allows interaction with the Microsoft Graph API."
5
5
  authors = ["bek42 <bharani.nitturi@gmail.com>"]
6
6
  license = "MIT"
@@ -1,182 +0,0 @@
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()
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes