Joe Gregorio | 0c73a67 | 2010-10-14 08:27:59 -0400 | [diff] [blame^] | 1 | from apiclient.discovery import build |
| 2 | from apiclient.discovery import HttpError |
| 3 | |
| 4 | import Queue |
| 5 | import httplib2 |
| 6 | import pickle |
| 7 | import threading |
| 8 | import time |
| 9 | |
| 10 | # Uncomment to get detailed logging |
| 11 | # httplib2.debuglevel = 4 |
| 12 | |
| 13 | |
| 14 | NUM_THREADS = 4 |
| 15 | NUM_ITEMS = 40 |
| 16 | |
| 17 | queue = Queue.Queue() |
| 18 | |
| 19 | |
| 20 | class Backoff: |
| 21 | """Exponential Backoff |
| 22 | |
| 23 | Implements an exponential backoff algorithm. |
| 24 | """ |
| 25 | def __init__(self, maxretries=8): |
| 26 | self.retry = 0 |
| 27 | self.maxretries = maxretries |
| 28 | self.first = True |
| 29 | |
| 30 | def loop(self): |
| 31 | if self.first: |
| 32 | self.first = False |
| 33 | return True |
| 34 | else: |
| 35 | return self.retry < self.maxretries |
| 36 | |
| 37 | def fail(self): |
| 38 | self.retry += 1 |
| 39 | delay = 2**self.retry |
| 40 | time.sleep(delay) |
| 41 | |
| 42 | |
| 43 | def start_threads(credentials): |
| 44 | # Start up NUM_THREADS to handle requests |
| 45 | |
| 46 | def process_requests(): |
| 47 | http = httplib2.Http() |
| 48 | http = credentials.authorize(http) |
| 49 | |
| 50 | while True: |
| 51 | request = queue.get() |
| 52 | backoff = Backoff() |
| 53 | while backoff.loop(): |
| 54 | try: |
| 55 | request.execute(http) |
| 56 | break |
| 57 | except HttpError, e: |
| 58 | if e.resp.status in [402, 403, 408, 503, 504]: |
| 59 | print "Increasing backoff, got status code: %d" % e.resp.status |
| 60 | backoff.fail() |
| 61 | |
| 62 | print "Completed request" |
| 63 | queue.task_done() |
| 64 | |
| 65 | for i in range(NUM_THREADS): |
| 66 | t = threading.Thread(target=process_requests) |
| 67 | t.daemon = True |
| 68 | t.start() |
| 69 | |
| 70 | def main(): |
| 71 | |
| 72 | f = open("moderator.dat", "r") |
| 73 | credentials = pickle.loads(f.read()) |
| 74 | f.close() |
| 75 | |
| 76 | start_threads(credentials) |
| 77 | |
| 78 | http = httplib2.Http() |
| 79 | http = credentials.authorize(http) |
| 80 | |
| 81 | p = build("moderator", "v1", http=http) |
| 82 | |
| 83 | series_body = { |
| 84 | "description": "An example of bulk creating topics", |
| 85 | "name": "Using threading and queues", |
| 86 | "videoSubmissionAllowed": False |
| 87 | } |
| 88 | series = p.series().insert(body=series_body).execute() |
| 89 | print "Created a new series" |
| 90 | |
| 91 | for i in range(NUM_ITEMS): |
| 92 | topic_body = { |
| 93 | "data": { |
| 94 | "description": "Sample Topic # %d" % i, |
| 95 | "name": "Sample", |
| 96 | "presenter": "me" |
| 97 | } |
| 98 | } |
| 99 | topic_request = p.topics().insert(seriesId=series['id']['seriesId'], body=topic_body) |
| 100 | print "Adding request to queue" |
| 101 | queue.put(topic_request) |
| 102 | |
| 103 | queue.join() |
| 104 | |
| 105 | |
| 106 | if __name__ == "__main__": |
| 107 | main() |