def shorten_url(api_key, url): service_url = "https://www.googleapis.com/urlshortener/v1/url?key=" + api_key headers = [('Content-Type', 'application/json'), ] data = json.dumps({ 'longUrl': url }) response = gevent_url_open(service_url, headers, data) headers = response.headers if 'content-type' in headers: encoding = headers['content-type'].split('charset=')[-1] data = unicode(response.read(), encoding) else: data = response.read() data.decode('utf-8', 'replace') r = json.loads(data) if u'id' in r: return (r.get(u"longUrl", u""), r.get(u"id", u"")) else: return None
def search_google(query_string): query = urllib.urlencode({ 'q': query_string, 'rsz': MAX_RESULTS, 'hl': SEARCH_LANG, }) url = SEARCH_URL + "&" + query response = gevent_url_open(url) headers = response.headers encoding = headers['content-type'].split('charset=')[-1] data = unicode(response.read(), encoding) json_data = json.loads(data) if 'responseData' in json_data: if 'results' in json_data['responseData']: return [parse_result(x) for x in json_data['responseData']['results']] return [] # error