|
| 1 | +from typing import List, Optional |
| 2 | + |
| 3 | +from requests import Session |
| 4 | + |
| 5 | +from msgraphcore.client_factory import HTTPClientFactory |
| 6 | +from msgraphcore.middleware.abc_token_credential import TokenCredential |
| 7 | +from msgraphcore.middleware.middleware import BaseMiddleware |
| 8 | +from msgraphcore.middleware.options.middleware_control import middleware_control |
| 9 | + |
| 10 | + |
| 11 | +class GraphClient: |
| 12 | + """Constructs a custom HTTPClient to be used for requests against Microsoft Graph |
| 13 | +
|
| 14 | + :keyword credential: TokenCredential used to acquire an access token for the Microsoft |
| 15 | + Graph API. Created through one of the credential classes from `azure.identity` |
| 16 | + :keyword list middleware: Custom middleware(HTTPAdapter) list that will be used to create |
| 17 | + a middleware pipeline. The middleware should be arranged in the order in which they will |
| 18 | + modify the request. |
| 19 | + :keyword enum api_version: The Microsoft Graph API version to be used, for example |
| 20 | + `APIVersion.v1` (default). This value is used in setting the base url for all requests for |
| 21 | + that session. |
| 22 | + :class:`~msgraphcore.enums.APIVersion` defines valid API versions. |
| 23 | + :keyword enum cloud: a supported Microsoft Graph cloud endpoint. |
| 24 | + Defaults to `NationalClouds.Global` |
| 25 | + :class:`~msgraphcore.enums.NationalClouds` defines supported sovereign clouds. |
| 26 | + :keyword tuple timeout: Default connection and read timeout values for all session requests. |
| 27 | + Specify a tuple in the form of Tuple(connect_timeout, read_timeout) if you would like to set |
| 28 | + the values separately. If you specify a single value for the timeout, the timeout value will |
| 29 | + be applied to both the connect and the read timeouts. |
| 30 | + :keyword obj session: A custom Session instance from the python requests library |
| 31 | + """ |
| 32 | + __instance = None |
| 33 | + |
| 34 | + def __new__(cls, *args, **kwargs): |
| 35 | + if not GraphClient.__instance: |
| 36 | + GraphClient.__instance = object.__new__(cls) |
| 37 | + return GraphClient.__instance |
| 38 | + |
| 39 | + def __init__(self, **kwargs): |
| 40 | + """ |
| 41 | + Class constructor that accepts a session object and kwargs to |
| 42 | + be passed to the HTTPClientFactory |
| 43 | + """ |
| 44 | + self.graph_session = self.get_graph_session(**kwargs) |
| 45 | + |
| 46 | + @middleware_control.get_middleware_options |
| 47 | + def get(self, url: str, **kwargs): |
| 48 | + r"""Sends a GET request. Returns :class:`Response` object. |
| 49 | + :param url: URL for the new :class:`Request` object. |
| 50 | + :param \*\*kwargs: Optional arguments that ``request`` takes. |
| 51 | + :rtype: requests.Response |
| 52 | + """ |
| 53 | + return self.graph_session.get(self._graph_url(url), **kwargs) |
| 54 | + |
| 55 | + @middleware_control.get_middleware_options |
| 56 | + def post(self, url, data=None, json=None, **kwargs): |
| 57 | + r"""Sends a POST request. Returns :class:`Response` object. |
| 58 | + :param url: URL for the new :class:`Request` object. |
| 59 | + :param data: (optional) Dictionary, list of tuples, bytes, or file-like |
| 60 | + object to send in the body of the :class:`Request`. |
| 61 | + :param json: (optional) json to send in the body of the :class:`Request`. |
| 62 | + :param \*\*kwargs: Optional arguments that ``request`` takes. |
| 63 | + :rtype: requests.Response |
| 64 | + """ |
| 65 | + return self.graph_session.post(self._graph_url(url), data, json, **kwargs) |
| 66 | + |
| 67 | + @middleware_control.get_middleware_options |
| 68 | + def put(self, url, data=None, **kwargs): |
| 69 | + r"""Sends a PUT request. Returns :class:`Response` object. |
| 70 | + :param url: URL for the new :class:`Request` object. |
| 71 | + :param data: (optional) Dictionary, list of tuples, bytes, or file-like |
| 72 | + object to send in the body of the :class:`Request`. |
| 73 | + :param \*\*kwargs: Optional arguments that ``request`` takes. |
| 74 | + :rtype: requests.Response |
| 75 | + """ |
| 76 | + return self.graph_session.put(self._graph_url(url), data, **kwargs) |
| 77 | + |
| 78 | + @middleware_control.get_middleware_options |
| 79 | + def patch(self, url, data=None, **kwargs): |
| 80 | + r"""Sends a PATCH request. Returns :class:`Response` object. |
| 81 | + :param url: URL for the new :class:`Request` object. |
| 82 | + :param data: (optional) Dictionary, list of tuples, bytes, or file-like |
| 83 | + object to send in the body of the :class:`Request`. |
| 84 | + :param \*\*kwargs: Optional arguments that ``request`` takes. |
| 85 | + :rtype: requests.Response |
| 86 | + """ |
| 87 | + return self.graph_session.patch(self._graph_url(url), data, **kwargs) |
| 88 | + |
| 89 | + @middleware_control.get_middleware_options |
| 90 | + def delete(self, url, **kwargs): |
| 91 | + r"""Sends a DELETE request. Returns :class:`Response` object. |
| 92 | + :param url: URL for the new :class:`Request` object. |
| 93 | + :param \*\*kwargs: Optional arguments that ``request`` takes. |
| 94 | + :rtype: requests.Response |
| 95 | + """ |
| 96 | + return self.graph_session.delete(self._graph_url(url), **kwargs) |
| 97 | + |
| 98 | + def _graph_url(self, url: str) -> str: |
| 99 | + """Appends BASE_URL to user provided path |
| 100 | + :param url: user provided path |
| 101 | + :return: graph_url |
| 102 | + """ |
| 103 | + return self.graph_session.base_url + url if (url[0] == '/') else url |
| 104 | + |
| 105 | + @staticmethod |
| 106 | + def get_graph_session(**kwargs): |
| 107 | + """Method to always return a single instance of a HTTP Client""" |
| 108 | + |
| 109 | + credential = kwargs.get('credential') |
| 110 | + middleware = kwargs.get('middleware') |
| 111 | + |
| 112 | + if credential and middleware: |
| 113 | + raise ValueError( |
| 114 | + "Invalid parameters! Both TokenCredential and middleware cannot be passed" |
| 115 | + ) |
| 116 | + if not credential and not middleware: |
| 117 | + raise ValueError("Invalid parameters!. Missing TokenCredential or middleware") |
| 118 | + |
| 119 | + if credential: |
| 120 | + return HTTPClientFactory(**kwargs).create_with_default_middleware(credential) |
| 121 | + return HTTPClientFactory(**kwargs).create_with_custom_middleware(middleware) |
0 commit comments