Skip to content

Instantly share code, notes, and snippets.

@splee
Created July 27, 2011 21:45
Show Gist options
  • Save splee/1110450 to your computer and use it in GitHub Desktop.
Save splee/1110450 to your computer and use it in GitHub Desktop.
Periodic Rewards - Main function
from bigdoorkit import Client
from collections import defaultdict
import restkit
def reward_users(client, currency_id, transaction_ids):
"""Rewards the top 3 leaders on a specified currency's leaderboard.
@param client {bigdoorkit.Client} The preconfigured client to access the
BigDoor API.
@param currency_id {int} ID of the currency for the leaderboard.
@param transaction_ids {list} IDs of Transactions to run, from first place
to last place in index order.
"""
# try to get enough users from the leaderboard for currency_id.
lb_params = dict(filter_value=currency_id, max_records=len(transaction_ids))
lb_resp = client.get('leaderboard/execute', params=lb_params)
end_user_logins = [r['end_user_login'] for r in lb_resp[0]['results']]
# base endpoint template for Named Transaction Group Execution
transaction_uri_tmpl = 'named_transaction_group/%d/execute/%s'
# queue of transaction id/end_user_login pairs for execution via the API.
# This produces a list of tuples, e.g.: [(1, 'eul_1'), (2, 'eul_2')]
transaction_queue = zip(transaction_ids, end_user_logins)
# a simple recursion guard which counts the number of times a specific
# transaction id/end user login pair has been seen so we don't retry the
# execution ad infinitum.
execution_count = defaultdict(int)
executed_transactions = []
for transaction_detail in transaction_queue:
# create the endpoint URI for transaction execution
endpoint = transaction_uri_tmpl % transaction_detail
# mark this transaction as having been seen.
execution_count[transaction_detail] += 1
try:
# execute the transaction via the API
resp = client.post(endpoint)
except restkit.errors.RequestFailed, e:
# Something unexpected happened. If it hasn't already hit our
# simple recursion guard this transaction will be retried.
resp = None
executed_transactions.append((transaction_detail, resp))
if not resp == 0 and execution_count[transaction_detail] < 3:
# the transaction failed for some reason. Try again once the others
# are done, but only try each transaction up to 3 times
transaction_queue.append(transaction_detail)
# and we're done
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment