This class call the Code Carbon API
| 31 | |
| 32 | |
| 33 | class ApiClient: # (AsyncClient) |
| 34 | """ |
| 35 | This class call the Code Carbon API |
| 36 | """ |
| 37 | |
| 38 | run_id = None |
| 39 | |
| 40 | def __init__( |
| 41 | self, |
| 42 | endpoint_url="https://api.codecarbon.io", |
| 43 | experiment_id=None, |
| 44 | api_key=None, |
| 45 | access_token=None, |
| 46 | conf=None, |
| 47 | create_run_automatically=True, |
| 48 | ): |
| 49 | """ |
| 50 | :endpoint_url: URL of the API endpoint |
| 51 | :experiment_id: ID of the experiment |
| 52 | :api_key: Code Carbon API_KEY |
| 53 | :access_token: Code Carbon API access token |
| 54 | :conf: Metadata of the experiment |
| 55 | :create_run_automatically: If False, do not create a run. To use API in read only mode. |
| 56 | """ |
| 57 | # super().__init__(base_url=endpoint_url) # (AsyncClient) |
| 58 | self.url = endpoint_url |
| 59 | self.experiment_id = experiment_id |
| 60 | self.api_key = api_key |
| 61 | self.conf = conf |
| 62 | self.access_token = access_token |
| 63 | if self.experiment_id is not None and create_run_automatically: |
| 64 | self._create_run(self.experiment_id) |
| 65 | |
| 66 | def _get_headers(self): |
| 67 | headers = {"Content-Type": "application/json"} |
| 68 | if self.api_key: |
| 69 | # set the x-api-token header |
| 70 | headers["x-api-token"] = self.api_key |
| 71 | elif self.access_token: |
| 72 | headers["Authorization"] = f"Bearer {self.access_token}" |
| 73 | return headers |
| 74 | |
| 75 | def set_access_token(self, token: str): |
| 76 | """This method sets the access token to be used for the API. |
| 77 | Args: |
| 78 | token (str): access token to be used for the API |
| 79 | """ |
| 80 | self.access_token = token |
| 81 | |
| 82 | def check_auth(self): |
| 83 | """ |
| 84 | Check API access to user account |
| 85 | """ |
| 86 | url = self.url + "/auth/check" |
| 87 | headers = self._get_headers() |
| 88 | r = requests.get(url=url, timeout=2, headers=headers) |
| 89 | if r.status_code != 200: |
| 90 | self._log_error(url, {}, r) |
no outgoing calls
searching dependent graphs…