import json import requests import requests_cache import iso8601 import sys reload(sys) sys.setdefaultencoding("utf-8") apikey = '2452f140' base_url = "http://octopart.com/api/v3" def extract_int(json, key): try: val = json[key] if val is not None: return int(val) return None except KeyError: return None def extract_date(json, key): try: val = json[key] if val is not None: return iso8601.parse_date(val) return None except KeyError: return None class Category(): def __init__(self, json): self.uid = json['uid'] self.name = json['name'] self.parent_uid = json['parent_uid'] self.children_uids = json['children_uids'] self.ancestor_uids = json['ancestor_uids'] self.ancestor_names = json['ancestor_names'] self.num_parts = json['num_parts'] def map_price(json): print 'price: ' + str(json) return json class Price(): def __init__(self, currency, quantity, amount): self.currency = currency self.quantity = quantity self.amount = amount class PartOffer(): def __init__(self, json): self.sku = json['sku'] # self.seller = Seller(json['seller']) self.eligible_region = json['eligible_region'] self.product_url = json['product_url'] self.octopart_rfq_url = json['octopart_rfq_url'] self.prices = {} for currency, breaks in json['prices'].items(): bs = self.prices[currency] = [] for b in breaks: bs.append(Price(currency, b[0], float(b[1]))) self.in_stock_quantity = extract_int(json, 'in_stock_quantity') self.on_order_quantity = extract_int(json, 'on_order_quantity') self.on_eta = extract_date(json, 'on_eta') self.factory_lead_days = extract_int(json, 'factory_lead_days') self.factory_order_multiple = extract_int(json, 'factory_order_multiple') self.order_multiple = extract_int(json, 'order_multiple') self.moq = extract_int(json, 'moq') self.last_updated = extract_date(json, 'last_updated') class Part(): def __init__(self, json): self.uid = json['uid'] self.mpn = json['mpn'] self.offers = map(PartOffer, json['offers']) class SearchResult(): def __init__(self, json): self.item = Part(json['item']) # Undocumented self.snippet = json['snippet'] pass class SearchResponse(): def __init__(self, json): self.results = map(SearchResult, json['results']) self.hits = json['hits'] def params(p): p['apikey'] = apikey return p def get(path, p): url = base_url + path # print('path: {}, params: {}'.format(path, p)) print('path: {}'.format(path)) for k, v in p.iteritems(): print(' {0:60} = {1}'.format(k, v)) res = requests.get(url, params=params(p)) # print res.url j = res.json() print(json.dumps(j, indent=2, sort_keys=True)) return j class Seller(): def __init__(self, json): self.uid = json['uid'] self.name = json['name'] def seller_search_raw(q): p = {'q': q, 'start': 0, 'limit': 10} return get('/sellers/search', p) def seller_search(q): res = seller_search_raw(q) sellers = [] for result in res['results']: item = result['item'] sellers.append(Seller(item)) return sellers def category_search_raw(q): p = {'q': q, 'start': 0, 'limit': 10} return get('/categories/search', p) def category_search(q): res = category_search_raw(q) categories = [] for result in res['results']: item = result['item'] categories.append(Category(item)) return categories def part_search(q, start = 0, limit = False, fields={}, include=[]): p = {'q': q, 'start': 0} if limit: p['limit'] = limit for field, data in fields.iteritems(): if data is not None and data['q']: p['filter[fields][' + field + '][]'] = data['q'] # key = 'filter[fields][' + field + '][]' # if not key in p: # p[key] = arr = [] # else: # arr = p[key] # arr.append(data['q']) pass if len(include) > 0: p['include[]'] = include # p['spec_drilldown[include]'] = 'true' json = get('/parts/search', p) return SearchResponse(json) requests_cache.install_cache(cache_name='http_cache', backend='sqlite', expire_after=180)