Skip to content

Instantly share code, notes, and snippets.

@tallpeak
Last active November 2, 2023 00:25
Show Gist options
  • Save tallpeak/1437dcb86b3f0b69e9788df459c2828a to your computer and use it in GitHub Desktop.
Save tallpeak/1437dcb86b3f0b69e9788df459c2828a to your computer and use it in GitHub Desktop.
structural pattern matching of a map
# Simplified example of how to handle throttling of requests returned from the Shopify API
import json
import time
# The web API (GraphQL API) returns a JSON string similar to this:
content = b'{"throttleStatus":{"maximumAvailable":1000.0,"currentlyAvailable":990,"restoreRate":50.0}}'
obj = json.loads(content) # Convert it to a Python object (a map)
# Actual code to retrieve part of the object from the full JSON from the Shopify GraphQL API:
# throttleStatus = js["extensions"]["cost"]["throttleStatus"]
# Simplified:
throttleStatus = obj["throttleStatus"]
match throttleStatus:
case { "maximumAvailable": maximumAvailable,
"currentlyAvailable": currentlyAvailable,
"restoreRate": restoreRate }:
delay = (maximumAvailable - currentlyAvailable) / restoreRate
print("sleeping:",delay,"seconds")
time.sleep(delay)
# Can also match the whole object, so this is equivalent:
match obj:
case { "throttleStatus" :
{ "maximumAvailable": maximumAvailable,
"currentlyAvailable": currentlyAvailable,
"restoreRate": restoreRate } }:
delay = (maximumAvailable - currentlyAvailable) / restoreRate
print("sleeping:",delay,"seconds")
time.sleep(delay)
case { "errors": errors}:
print("something went wrong", str(errors))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment