Skip to content

Instantly share code, notes, and snippets.

@02strich
Created November 20, 2017 06:33
Show Gist options
  • Save 02strich/9d5ac1a71df036f718eca9676f34a0c7 to your computer and use it in GitHub Desktop.
Save 02strich/9d5ac1a71df036f718eca9676f34a0c7 to your computer and use it in GitHub Desktop.
apple_product_checker
import boto3
import os
from urllib.request import urlopen
import json
# could be for example: apple_product_code = MQAQ2LL/A
APPLE_PRODUCT_CODE = os.environ['apple_product_code'] # URL of the site to check, stored in the site environment variable
def lambda_handler(event, context):
available_count = 0
available_dist = 1000.0
unavailable_count = 0
with urlopen("https://www.apple.com/shop/retail/pickup-message?pl=true&cppart=TMOBILE/US&parts.0=" + APPLE_PRODUCT_CODE + "&location=Seattle,%20WA") as f:
response = json.loads(f.read().decode('utf-8'))
for store in response["body"]["stores"]:
if store['partsAvailability'][APPLE_PRODUCT_CODE]['storeSelectionEnabled']:
print("Part is available at " + store['storeName'])
available_count = available_count + 1
if store['storedistance'] < available_dist:
available_dist = store['storedistance']
else:
print("Part is unavailable at " + store['storeName'])
unavailable_count = unavailable_count + 1
cloudwatch = boto3.client('cloudwatch')
cloudwatch.put_metric_data(Namespace='AppleProductChecker', MetricData=[{'MetricName': 'AvailableCount', 'Unit': 'Count', 'Value': available_count},
{'MetricName': 'AvailableDistance', 'Unit': 'None', 'Value': available_dist}])
if available_count == 0:
raise Exception("Not available anywhere")
print("Closest store with inventory is " + str(available_dist) + " miles away")
if available_dist > 100:
raise Exception("Closest place is too far away")
return available_count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment