diff --git a/shopping_client/shopping_client.py b/shopping_client/shopping_client.py index 3b93d6898f29d38991c94d14f6995cbb6964a2c2..a5b8c81c49ddf51d325ff721ae3ca89dabe34bd2 100644 --- a/shopping_client/shopping_client.py +++ b/shopping_client/shopping_client.py @@ -36,9 +36,13 @@ class shopping_client: self.connectors = connectors self.basket = None + self.username = None def get_basket( - self, convert_to_pandas: bool = False, reload: bool = False, filter_archives: bool = False + self, + convert_to_pandas: bool = False, + reload: bool = False, + filter_archives: bool = False, ) -> Union[list, pd.DataFrame, None]: """Retrieve the shopping basket for a user. Prompts for access token if one was not supplied to constructor. @@ -87,6 +91,56 @@ class shopping_client: return self.basket + def add_to_basket(self, items: list): + """Add items to user's shopping basket. + + Parameters + ---------- + items : list + List of objects, each containing the data for a single + shopping item. Objects should be JSON-serializable. Examples + include Python `dict`s or `list`s. + + Returns + ------- + bool + `True` if items were successfully added otherwise `False`. + """ + + url = urllib.parse.urljoin(self.host, shopping_client.endpoint) + + if self.username is None: + # Retrieve username + response = requests.get(url, headers=self._request_header()) + if response.ok: + self.username = json.loads(response.content)["results"][0]["user_name"] + else: + warn( + f"Unable to retrieve username from {self.host}; is your key valid?" + ) + return False, response + + # PATCH not working properly need to add existing basket items + payload = { + "shopping_cart": [ + json.loads(item["item_data"]) for item in self.get_basket() + ] + + items + } + + # trailing "/" required for PATCH + url = urllib.parse.urljoin(url, self.username) + "/" + + response = requests.patch(url, json=payload, headers=self._request_header()) + if response.ok: + print( + f"{len(items)} item{'s' if len(items) > 1 else ''} successfully added." + ) + return True + else: + warn(f"Unable to add data to basket at {self.host}; is your key valid?") + return False, response + def _request_header(self): while self.token is None: self._get_token() @@ -102,12 +156,14 @@ class shopping_client: item_data = json.loads(item["item_data"]) for connector in self.connectors: - if "archive" in item_data and item_data["archive"] == connector.archive: + if ( + "archive" in item_data + and item_data["archive"] == connector.archive + ): filtered_items.append(item) return filtered_items - def _basket_to_pandas(self): if len(self.connectors): converted_basket = {