| 22 | pass |
| 23 | |
| 24 | class OpentableDownloader(object): |
| 25 | def __init__(self, login, password, opentable_filename, tsv_filename=None): |
| 26 | self.login = login |
| 27 | self.password = password |
| 28 | self.token = None |
| 29 | self.opentable_filename = opentable_filename |
| 30 | self.tsv_filename = tsv_filename |
| 31 | |
| 32 | # TODO(mgsergio): Check if token is actual in functions. |
| 33 | self._get_token() |
| 34 | |
| 35 | def download(self): |
| 36 | headers = self._add_auth_header({'Content-Type': 'application/json'}) |
| 37 | url = 'https://platform.opentable.com/sync/listings' |
| 38 | |
| 39 | with open(self.opentable_filename, 'w') as f: |
| 40 | offset = 0 |
| 41 | while True: |
| 42 | request = urllib2.Request(url + '?offset={}'.format(offset), headers=headers) |
| 43 | logging.debug('Fetching data with headers %s from %s', |
| 44 | str(headers), request.get_full_url()) |
| 45 | resp = urllib2.urlopen(request) |
| 46 | # TODO(mgsergio): Handle exceptions |
| 47 | data = json.loads(resp.read()) |
| 48 | for rest in data['items']: |
| 49 | print(json.dumps(rest), file=f) |
| 50 | |
| 51 | total_items = int(data['total_items']) |
| 52 | offset = int(data['offset']) |
| 53 | items_count = len(data['items']) |
| 54 | |
| 55 | if total_items <= offset + items_count: |
| 56 | break |
| 57 | |
| 58 | offset += items_count |
| 59 | |
| 60 | def _get_token(self): |
| 61 | url = 'https://oauth.opentable.com/api/v2/oauth/token?grant_type=client_credentials' |
| 62 | headers = self._add_auth_header({}) |
| 63 | request = urllib2.Request(url, headers=headers) |
| 64 | logging.debug('Fetching token with headers %s', str(headers)) |
| 65 | resp = urllib2.urlopen(request) |
| 66 | # TODO(mgsergio): Handle exceptions |
| 67 | if resp.getcode() != 200: |
| 68 | raise OpentableDownloaderError("Cant't get token. Response: {}".format(resp.read())) |
| 69 | self.token = json.loads(resp.read()) |
| 70 | logging.debug('Token is %s', self.token) |
| 71 | |
| 72 | def _add_auth_header(self, headers): |
| 73 | if self.token is None: |
| 74 | key = base64.b64encode('{}:{}'.format(self.login, self.password)) |
| 75 | headers['Authorization'] = 'Basic {}'.format(key) |
| 76 | else: |
| 77 | headers['Authorization'] = '{} {}'.format(self.token['token_type'], |
| 78 | self.token['access_token']) |
| 79 | return headers |
| 80 | |
| 81 |
no outgoing calls
no test coverage detected