Skip to content

Commit

Permalink
0.1.8: tweak log levels
Browse files Browse the repository at this point in the history
  • Loading branch information
Patrick Steil committed Oct 8, 2024
1 parent c3dec13 commit 9d60d2c
Show file tree
Hide file tree
Showing 5 changed files with 22 additions and 14 deletions.
14 changes: 7 additions & 7 deletions brightpearl_client/base_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ def _respect_rate_limit(self) -> None:
time_since_last_request = current_time - self._last_request_time
if time_since_last_request < self._config.rate_limit:
sleep_time = self._config.rate_limit - time_since_last_request
logger.debug(f"Rate limit: Sleeping for {sleep_time:.2f} seconds")
# logger.debug(f"Rate limit: Sleeping for {sleep_time:.2f} seconds")
time.sleep(sleep_time)
self._last_request_time = time.time()

Expand All @@ -127,14 +127,14 @@ def _make_request(self, relative_url: str, response_model: Type[T], method: str
for attempt in range(self._config.max_retries):
try:
self._respect_rate_limit()
logger.debug(f"Making {method} request to: {url}")
# logger.debug(f"Making {method} request to: {url}")
if method.upper() == 'GET':
response = requests.get(url, headers=headers, timeout=self._config.timeout)
elif method.upper() == 'POST':
response = requests.post(url, headers=headers, json=kwargs.get('json'), timeout=self._config.timeout)
else:
raise ValueError(f"Unsupported HTTP method: {method}")
logger.info(f"API Response for {method} {url}:\n{json.dumps(response.json(), indent=3)}")
# logger.info(f"API Response for {method} {url}:\n{json.dumps(response.json(), indent=3)}")

# per the docs, a GET shouldn't be returning a 207
# 207 normally means multiple statuses, and only on POST, PUT and DELETE operations
Expand All @@ -145,7 +145,7 @@ def _make_request(self, relative_url: str, response_model: Type[T], method: str
raise BrightPearlApiError(f"API Error for {method} {url}:\n{response.text[:500]}")

response.raise_for_status()
logger.info(f"Successfully {method} data to/from: {url}")
# logger.info(f"Successfully {method} data to/from: {url}")
try:
response_data = response.json()
except ValueError:
Expand Down Expand Up @@ -188,7 +188,7 @@ def _handle_http_error(self, http_err: HTTPError, attempt: int):
raise BrightPearlApiError(f"Unexpected HTTP error: {http_err}")

def _parse_api_results(self, api_response: BrightPearlApiResponse) -> Tuple[List[OrderResult], OrdersMetadata]:
logger.info(f"Parsing API results")
# logger.info(f"Parsing API results")
if not isinstance(api_response.response.results, list):
logger.warning("API response is not in the expected format")
return [], api_response.response.metaData
Expand Down Expand Up @@ -221,7 +221,7 @@ def _get_cached_data(self, cache_key: str, cache_minutes: int) -> Optional[Any]:
if os.path.exists(cache_file):
cache_time = datetime.fromtimestamp(os.path.getmtime(cache_file))
if datetime.now() - cache_time < timedelta(minutes=cache_minutes):
logger.info(f"Using cached data for {cache_key}")
# logger.info(f"Using cached data for {cache_key}")
with open(cache_file, 'r') as cache_file:
return json.load(cache_file)
return None
Expand All @@ -237,4 +237,4 @@ def _save_to_cache(self, cache_key: str, data: Any) -> None:
cache_file = os.path.join(self._cache_dir, f'{cache_key}_cache.json')
with open(cache_file, 'w') as cache_file:
json.dump(data, cache_file)
logger.info(f"Saved data to cache for {cache_key}")
# logger.info(f"Saved data to cache for {cache_key}")
2 changes: 1 addition & 1 deletion brightpearl_client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def _save_to_cache(self, cache_key: str, data: Any) -> None:
cache_file = os.path.join(self._cache_dir, self._get_cache_filename(cache_key))
with open(cache_file, 'w') as cache_file:
json.dump(data, cache_file)
logger.info(f"Saved data to cache for {cache_key}")
# logger.info(f"Saved data to cache for {cache_key}")

def _invalidate_cache(self, cache_key: str):
cache_file = os.path.join(self._cache_dir, self._get_cache_filename(cache_key))
Expand Down
13 changes: 10 additions & 3 deletions example_usage.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
logging_level = logging.WARNING
logging_level = logging.INFO
logging_level = logging.DEBUG
logging_level = logging.ERROR

# Set global logging level to WARNING
logging.basicConfig(level=logging_level, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
Expand Down Expand Up @@ -47,7 +48,7 @@ def main():

# print( f"parsed_orders: {json.dumps(str(parsed_orders), indent=2)}")

exit(0)
# exit(0)

# Test stock correction
print("\nTesting stock correction...")
Expand Down Expand Up @@ -249,8 +250,14 @@ def main():
# Get orders with parsed results
parsed_orders = client.get_orders_by_status(4)
print(f"\nRetrieved {len(parsed_orders)} parsed orders with status 4 (invoiced):")
for order in parsed_orders[:5]: # Print first 5 orders
print(f" Order ID: {order.orderId}, Type: {order.order_type_id}, Status: {order.order_status_id}")

# example parsed_orders: [ OrderResult(orderId=200001, order_type_id=1, contact_id=217582, order_status_id=4, order_stock_status_id=3) ]
for order in parsed_orders[:5]:
for order_item in order:
if 'orderId' in order_item:
print(f"order_item.orderId: {order_item.orderId}, order_item.order_status_id: {order_item.order_status_id}")
# else:
# print(f"order_item: {order_item}")

# Get orders without parsing
raw_response = client.get_orders_by_status(38, parse_api_results=False)
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

setup(
name="brightpearl_client",
version="0.1.7",
version="0.1.8",
packages=find_packages(exclude=["tests"]),
install_requires=[
"requests",
Expand Down
5 changes: 3 additions & 2 deletions tag.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ if [ -n "$(git status --porcelain)" ]; then
exit 1
fi

release="0.1.8"
# tag the current commit
git tag -a v0.1.7 -m "Beta release 0.1.7"
git push origin v0.1.7
git tag -a v$release -m "Beta release $release"
git push origin v$release
git push

0 comments on commit 9d60d2c

Please sign in to comment.