Skip to content

Instantly share code, notes, and snippets.

@maplambda
Created March 18, 2013 07:06
Show Gist options
  • Save maplambda/5185513 to your computer and use it in GitHub Desktop.
Save maplambda/5185513 to your computer and use it in GitHub Desktop.
Hacker news search Python interface
import requests
import urllib
import json
def get(url, params):
print url, params
return json.loads(requests.get(url, params=params).text)
def iter_flatten(data):
for k, v in data.items():
if hasattr(v, '__iter__'):
for v2 in v:
yield k, v2
else:
yield k, v
class ThriftDb(object):
def __init__(self, base, bucket, collection):
self.base = base
self.bucket = bucket
self.collection = collection
def search(self, **kwargs):
if 'filter' in kwargs:
filter = kwargs['filter']
del kwargs['filter']
filter_query = ['filter' + '='.join(item) for item in iter_flatten(filter)]
url = '/'.join([self.base, self.bucket, self.collection, '_search?'])
params = urllib.urlencode(kwargs) + '&' + '&'.join(filter_query)
return get(url, params)
if __name__ == '__main__':
t = ThriftDb('http://api.thriftdb.com', 'api.hnsearch.com', 'items')
t.search(limit= '100',
pretty_print= 'true',
sortby= 'create_ts desc',
q= 'python',
filter= {'[fields][type]' : 'comment'})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment