def getCert(self, id, cfg, token, verifier): oauthKey = cfg[OAUTH_CONSUMER_KEY] params = { 'oauth_nonce': generate_nonce(), 'oauth_token': token, 'oauth_verifier': verifier, 'oauth_timestamp': generate_timestamp(), 'oauth_signature_method': 'RSA-SHA1', 'oauth_consumer_key': oauthKey, 'oauth_version': '1.0' } consumer = Consumer(oauthKey, '') rsa_sha1 = SignatureMethod_RSA_SHA1( privateKeyFile=cfg[PRIVATE_KEY_FILE_TAG]) client = OA4MPClient(consumer=consumer) client.set_signature_method(rsa_sha1) response, content = client.request(cfg[SERVICE_URI_TAG] + '/token', parameters=params) tokens = content.split('&') access_token = urllib.unquote(tokens[0].split('=')[1]) params = { 'oauth_nonce': generate_nonce(), 'oauth_token': access_token, 'oauth_timestamp': generate_timestamp(), 'oauth_signature_method': 'RSA-SHA1', 'oauth_consumer_key': oauthKey, 'oauth_version': '1.0' } # we now have the token and the secret. consumer = Consumer(oauthKey, '') rsa_sha1 = SignatureMethod_RSA_SHA1( privateKeyFile=cfg[PRIVATE_KEY_FILE_TAG]) client = OA4MPClient(consumer=consumer) client.set_signature_method(rsa_sha1) response, content = client.request(cfg[SERVICE_URI_TAG] + '/getcert', parameters=params) tokens = content.split('\n') username = urllib.unquote(tokens[0].split('=')[1]) tokens = tokens[1:] certs = '\n'.join(tokens) fileStore = FileStore(cfg) asset = fileStore.get(id) asset[USERNAME_KEY] = username asset[CERTS_KEY] = certs fileStore.put(id, asset) return username, certs
def do(config): key = config['consumer_key'] sec = config['consumer_sec'] consumer = oauth.Consumer(key, sec) c = oauth.Client(consumer) params = dict( oauth_signature_method='HMAC-SHA1', oauth_nonce=oauth.generate_nonce(), oauth_timestamp=oauth.generate_timestamp()) req = oauth.Request.from_consumer_and_token( consumer=consumer, http_method='POST', http_url=REQUEST_TOKEN_URL, parameters=params, is_form_encoded=True) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, None) res = c.request(REQUEST_TOKEN_URL, method='POST', headers=req.to_header()) r = urlparse.parse_qs(res[1]) print r rt = oauth.Token(r['oauth_token'][0], r['oauth_token_secret'][0]) print AUTHORIZE_URL + '?oauth_token=' + urllib.quote(rt.key) v = raw_input("PIN: ") params = dict( oauth_signature_method='HMAC-SHA1', oauth_nonce=oauth.generate_nonce(), oauth_timestamp=oauth.generate_timestamp(), oauth_token=rt.key, oauth_token_secret=rt.secret, oauth_verifier=v) req = oauth.Request.from_consumer_and_token( consumer=consumer, token=rt, http_method='POST', http_url=ACCESS_TOKEN_URL, parameters=params, is_form_encoded=True) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, rt) res = c.request(ACCESS_TOKEN_URL, method='POST', headers=req.to_header()) r = urlparse.parse_qs(res[1]) print " key: '%s'" % r['oauth_token'][0] print " sec: '%s'" % r['oauth_token_secret'][0]
def requestData(location): ''' Authenticates a request and returns data from Yelp API. ''' data = [] url = 'https://api.yelp.com/v2/search/?location=San Francisco, CA' oauth_request = oauth2.Request(method="GET", url=url) oauth_request.update( { 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': TOKEN, 'oauth_consumer_key': CONSUMER_KEY } ) consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET) token = oauth2.Token(TOKEN, TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() req = requests.get(signed_url) response = req.text return response
def sign_request(self, url_params={}): """ Prepares OAuth authentication and signs the request """ url = 'http://{0}{1}'.format(self.API_HOST, self.API_SEARCH_PATH) consumer = oauth2.Consumer(self.CONSUMER_KEY, self.CONSUMER_SECRET) params = { 'oauth_token' : self.TOKEN, 'oauth_nonce' : oauth2.generate_nonce(), 'oauth_timestamp' : oauth2.generate_timestamp(), 'oauth_consumer_key' : self.CONSUMER_KEY } if url_params: params.update(url_params) oauth_request = oauth2.Request('GET', url, params) token = oauth2.Token(self.TOKEN, self.TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() return signed_url
def get_response(lat, lon, token, consumer_key, consumer_secret, token_secret): url_params = {'term': 'coffee', 'sort': 1, 'll': lat + "," + lon} encoded_params = '' if url_params: encoded_params = urllib.urlencode(url_params) url = 'http://api.yelp.com/v2/search?%s' % (encoded_params) print 'URL: %s' % (url, ) # Sign the URL consumer = oauth2.Consumer(consumer_key, consumer_secret) oauth_request = oauth2.Request('GET', url, {}) oauth_request.update({ 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': token, 'oauth_consumer_key': consumer_key }) token = oauth2.Token(token, token_secret) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() print 'Signed URL: %s\n' % (signed_url, ) response = "" # Connect try: conn = urllib2.urlopen(signed_url, None) try: response = json.loads(conn.read()) finally: conn.close() except urllib2.HTTPError, error: response = json.loads(error.read())
def requester(host, path, url_params, consumer_key, consumer_secret, token, token_secret): """Returns response for API request.""" # Unsigned URL encoded_params = '' if url_params: encoded_params = urllib.urlencode(url_params) url = 'http://%s%s?%s' % (host, path, encoded_params) # Sign the URL consumer = oauth2.Consumer(consumer_key, consumer_secret) oauth_request = oauth2.Request('GET', url, {}) oauth_request.update({'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': token, 'oauth_consumer_key': consumer_key}) token = oauth2.Token(token, token_secret) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() # Connect try: conn = urllib2.urlopen(signed_url, None) try: response = json.loads(conn.read()) finally: conn.close() except urllib2.HTTPError, error: response = json.loads(error.read())
def request(host, path, url_params=None): #url_params = url_params or {} encoded_params = urllib.urlencode(url_params) url = 'http://{0}{1}?{2}'.format(host, path, encoded_params) consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET) oauth_request = oauth2.Request('GET', url, {}) oauth_request.update( { 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': TOKEN, 'oauth_consumer_key': CONSUMER_KEY } ) token = oauth2.Token(TOKEN, TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() print 'Querying {0} ...'.format(url) conn = urllib2.urlopen(signed_url, None) try: response = json.loads(conn.read()) finally: conn.close() return response
def search(term, address): consumer_key = 'YQjC8cOZxSyb-x21hpoLxg' consumer_secret = 'AJ6u905ojzMr9VkHDN_BkAbQrIA' token = '4Q20XFJ24cB8SL1CRKWY_2kNYqGnk60y' token_secret = '2hPhKm5s4kt8L5EicFD3h26cLh4' consumer= oauth2.Consumer(consumer_key,consumer_secret) url= 'http://api.yelp.com/v2/search?term=%s&location=%s&limit=%d&format=json&radius_filter=400&category=food'%(term, address, 5) oauth_request = oauth2.Request('GET', url, {}) oauth_request.update({'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': token, 'oauth_consumer_key': consumer_key}) token = oauth2.Token(token, token_secret) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() #connect try: conn = urllib2.urlopen(signed_url) try: response =json.load(conn) finally: conn.close() except urllib2.HTTPError,error: response=json.load(error)
def api_request(url, url_params): """ Make a request with Yelp's API """ consumer = oauth2.Consumer(CONSUMER, CONSUMER_SECRET) token = oauth2.Token(TOKEN, TOKEN_SECRET) oauth_request = oauth2.Request(method="GET", url=url, parameters=url_params) oauth_request.update({ 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': TOKEN, 'oauth_consumer_key': CONSUMER }) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() conn = urllib2.urlopen(signed_url, None) try: response = json.loads(conn.read()) finally: conn.close() return response
def requestYelp(latlong): print "-----------------------------\n Using Yelp API" term = 'restaurant' limit = 5 #encoded_params = urllib.urlencode(url_params) url = 'http://api.yelp.com/v2/search?term=' + term + '&ll=' + latlong + '&limit=' + str( limit) #'http://{0}{1}?{2}'.format(host, path, encoded_params) consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET) oauth_request = oauth2.Request('GET', url, {}) oauth_request.update({ 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': TOKEN, 'oauth_consumer_key': CONSUMER_KEY }) token = oauth2.Token(TOKEN, TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() conn = urllib2.urlopen(signed_url, None) try: json_data = json.loads(conn.read()) finally: conn.close() #if json_data['status'] == 'OK': for place in json_data['businesses']: print '%s\n' % (place['name'])
def yelp_req(url, offset): """ Pass in a url that follows the format of Yelp API, and this function will return either a JSON object or error messages. """ # Create URL # source: http://letstalkdata.com/2014/02/how-to-use-the-yelp-api-in-python/ params = {} params["term"] = "restaurants" params["location"] = "San Francisco, CA" params["offset"] = offset params["sort"] = "2" oauth_request = oauth2.Request('GET', url, parameters=params) oauth_request.update( { 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': TOKEN, 'oauth_consumer_key': CONSUMER_KEY } ) consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET) token = oauth2.Token(TOKEN, TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() conn = something.urlopen(signed_url, None) try: response = json.loads(conn.read().decode('utf-8')) finally: conn.close() return response
def get_ylp_stats(id): url = 'https://api.yelp.com/v2/business/' + id_lookup('ylp', id) consumer = oauth2.Consumer(config['ylp_ck'], config['ylp_cs']) oauth_request = oauth2.Request(method="GET", url=url, parameters=None) oauth_request.update({ 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': config['ylp_t'], 'oauth_consumer_key': config['ylp_ck'] }) token = oauth2.Token(config['ylp_t'], config['ylp_ts']) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() conn = urllib2.urlopen(signed_url, None) try: data = json.loads(conn.read()) finally: conn.close() # return rating, total ratings return [data['rating'], data['review_count']]
def requestData(location): ''' Authenticates a request and returns data from Yelp API. ''' data = [] url = 'https://api.yelp.com/v2/search/?location=San Francisco, CA' oauth_request = oauth2.Request(method="GET", url=url) oauth_request.update({ 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': TOKEN, 'oauth_consumer_key': CONSUMER_KEY }) consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET) token = oauth2.Token(TOKEN, TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() req = requests.get(signed_url) response = req.text return response
def do_search(self, query, field, consumer_key, consumer_secret, token, token_secret): """Returns response for API request.""" # Unsigned URL if not query: self.abort(400, "You must provide search query") url = 'http://%s%s?%s' % (SearchHandler.HOST, SearchHandler.SEARCH_PATH, query) # Sign the URL consumer = oauth2.Consumer(consumer_key, consumer_secret) oauth_request = oauth2.Request('GET', url, {}) oauth_request.update({ 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': token, 'oauth_consumer_key': consumer_key }) token = oauth2.Token(token, token_secret) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() # Connect try: conn = urllib2.urlopen(signed_url, None) try: response = self.get_value(json.loads(conn.read()), field) finally: conn.close() except urllib2.HTTPError, error: response = json.loads(error.read())
def request_yelp(url, url_params=None): #Initialization of credential parameters for Yelp API consumer_key = credentials.my_yelp_consumer_key consumer_secret = credentials.my_yelp_consumer_secret token = credentials.my_yelp_token token_secret = credentials.my_yelp_token_secret url_params = url_params or {} #Making the API get request using the oauth2 python library using the previously initialized credential parameters consumer = oauth2.Consumer(consumer_key, consumer_secret) oauth_request = oauth2.Request(method="GET", url=url, parameters=url_params) oauth_request.update({ 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': token, 'oauth_consumer_key': consumer_key }) token = oauth2.Token(token, token_secret) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() #Returning the value of the API get request return requests.get(signed_url).json()
def search(): params = { 'term': request.query.term, 'll': request.query.ll, 'limit': 20, 'radius_filter': (request.query.radius or 4000) } oauth_request = oauth2.Request( method = 'GET', url = 'https://api.yelp.com/v2/search/', parameters = params ) oauth_request.update( { 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': TOKEN, 'oauth_consumer_key': CONSUMER_KEY } ) token = oauth2.Token(TOKEN, TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() r = requests.get(signed_url) return r.json()
def yelpreq(url, method, terms, ll): consumer = oauth.Consumer(consumer_key, consumer_secret) req = oauth.Request('GET', url+"?term="+terms+"&ll="+ll) req.update({'oauth_nonce': oauth.generate_nonce(), 'oauth_timestamp': oauth.generate_timestamp(), 'oauth_token': token, 'oauth_consumer_key': consumer_key}) tokens = oauth.Token(token, token_secret) req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, tokens) url = req.to_url() headers = req.to_header() if http_method == "POST": encoded_post_data = req.to_postdata() else: encoded_post_data = None url = req.to_url() opener = urllib.OpenerDirector() opener.add_handler(http_handler) opener.add_handler(https_handler) response = opener.open(url, encoded_post_data) return response
def request(host, path, url_params=None): url_params = url_params or {} encoded_params = urllib.urlencode(url_params) path = unicodedata.normalize('NFKD', unicode(path)).encode('ascii','ignore') url = 'http://{0}{1}?{2}'.format(host, path, encoded_params) consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET) oauth_request = oauth2.Request('GET', url, {}) oauth_request.update( { 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': TOKEN, 'oauth_consumer_key': CONSUMER_KEY } ) token = oauth2.Token(TOKEN, TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() try: conn = urllib2.urlopen(signed_url, None) response = json.loads(conn.read()) conn.close() except HTTPError as error: sys.exit('Encountered HTTP error {0}. Abort program.'.format(error.code)) return response
def food(entities, latitude, longitude): term = 'food' for entity in entities: if entity.get('type') == "Information": term = entity.get('entity') consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET) api_url = str.format("https://api.yelp.com/v2/search?term={}&ll={},{}&limit=1&radius_filter=15000&sort=0", urllib.quote_plus(term), latitude, longitude) oauth_request = oauth2.Request(method="GET", url=api_url) oauth_request.update( { 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': TOKEN, 'oauth_consumer_key': CONSUMER_KEY } ) token = oauth2.Token(TOKEN, TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() response = json.loads(urllib2.urlopen(url=signed_url).read()) return response.get('businesses')[0].get('name') + " " + \ response.get('businesses')[0].get('location').get('display_address')[0]
def __oatuh(self, url): """ Puth the oatuh2 token in the url Return: A signed url, that can be passed to the yelp API """ consumer = oauth2.Consumer(self.consumer_key, self.consumer_secret) oauth_request = oauth2.Request('GET', url, {}) oauth_request.update( { 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': self.token, 'oauth_consumer_key': self.consumer_key } ) oauth_token = oauth2.Token(self.token, self.token_secret) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, oauth_token) signed_url = oauth_request.to_url() return signed_url
def search(query, location, consumer_key, consumer_secret, token, token_secret): host = 'api.yelp.com' path = '/v2/search' url_params = { 'term': query, 'location': location, 'category_filter': 'restaurants', } encoded_params = urllib.urlencode(url_params) url = 'http://%s%s?%s' % (host, path, encoded_params) consumer = oauth2.Consumer(consumer_key, consumer_secret) oauth_request = oauth2.Request('GET', url, {}) oauth_request.update({'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': token, 'oauth_consumer_key': consumer_key}) token = oauth2.Token(token, token_secret) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() res = requests.get(signed_url) response = json.loads(res.content) return response
def query(self, lat, lon): url_params = { 'category_filter': 'food', 'radius_filter': 2000, # 2 km on either side of route 'll': '{0},{1}'.format(lat, lon) } encoded_params = urllib.urlencode(url_params) url = 'http://api.yelp.com/v2/search/?' + encoded_params consumer = oauth2.Consumer(self.consumer_key, self.consumer_secret) oauth_request = oauth2.Request('GET', url, {}) oauth_request.update({ 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': self.token, 'oauth_consumer_key': self.consumer_key }) token = oauth2.Token(self.token, self.token_secret) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() connection = urllib2.urlopen(signed_url, None) try: response = json.loads(connection.read()) finally: connection.close() return response
def callAPI2(access_token): """Not sure what I'm doing here""" url = "http://social.yahooapis.com/v1/user/%s/profile?format=json&" % access_token["xoauth_yahoo_guid"] params = { 'oauth_nonce': oauth.generate_nonce(), 'oauth_timestamp': oauth.generate_timestamp(), "oauth_consumer_key": CONSUMER_KEY, "oauth_signature_method": "HMAC-SHA1", "oauth_signature": CONSUMER_SECRET, 'oauth_version': '1.0', "oauth_token": access_token["oauth_token"], "oauth_signature": access_token["oauth_token_secret"], "realm": "yahooapis.com", } url = url + "&".join([ k + "=" + str(v) for k, v in params.iteritems() ]) token = oauth.Token( access_token['oauth_token'], access_token['oauth_token_secret']) client = oauth.Client(consumer, token) resp, content = client.request(url, "GET") print resp print content return
def request(host, path, url_params, consumer_key="FH-RvZ_ScMpTCdMb1esSoQ", consumer_secret="QvfkebxG2ol0aZqem4Bka4LZZ6Y", token="-4NwiPsWveiVcTkVBC-5vXXgnnVk6r_l", token_secret="F2Q00ewraK8qfnm6yW2h3h-HG2g"): """Returns response for API request.""" # Unsigned URL encoded_params = '' if url_params: encoded_params = urllib.urlencode(url_params) url = 'http://%s%s?%s' % (host, path, encoded_params) #print 'URL: %s' % (url,) # Sign the URL consumer = oauth2.Consumer(consumer_key, consumer_secret) oauth_request = oauth2.Request('GET', url, {}) oauth_request.update({'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': token, 'oauth_consumer_key': consumer_key}) token = oauth2.Token(token, token_secret) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() #print 'Signed URL: %s\n' % (signed_url,) # Connect try: conn = urllib2.urlopen(signed_url, None) try: response = json.loads(conn.read()) finally: conn.close() except urllib2.HTTPError, error: response = json.loads(error.read())
def request(url_params): """ Retrieves data from the yelp api given search parameters Args: url_params: (String) the part of a url that contains the what the user wants to search Returns: response: (Dictionary) contains all the information from yelp api """ url = "https://api.yelp.com/v2/search/" consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET) oauth_request = oauth2.Request(method="GET", url=url, parameters=url_params) oauth_request["oauth_nonce"] = oauth2.generate_nonce() oauth_request["oauth_timestamp"] = oauth2.generate_timestamp() oauth_request["oauth_token"] = TOKEN oauth_request["oauth_consumer_key"] = CONSUMER_KEY token = oauth2.Token(TOKEN, TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() print(signed_url) conn = urllib2.urlopen(signed_url, None) response = json.loads(conn.read()) conn.close() return response
def request(host, path, url_params, consumer_key, consumer_secret, token, token_secret): """Returns response for API request.""" # Unsigned URL encoded_params = "" if url_params: encoded_params = urllib.urlencode(url_params) url = "http://%s%s?%s" % (host, path, encoded_params) print "URL: %s" % (url,) # Sign the URL consumer = oauth2.Consumer(consumer_key, consumer_secret) oauth_request = oauth2.Request("GET", url, {}) oauth_request.update( { "oauth_nonce": oauth2.generate_nonce(), "oauth_timestamp": oauth2.generate_timestamp(), "oauth_token": token, "oauth_consumer_key": consumer_key, } ) token = oauth2.Token(token, token_secret) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() print "Signed URL: %s\n" % (signed_url,) # Connect try: conn = urllib2.urlopen(signed_url, None) try: response = json.loads(conn.read()) finally: conn.close() except urllib2.HTTPError, error: response = json.loads(error.read())
def requestYelp(latlong): print "-----------------------------\n Using Yelp API" term = 'restaurant' limit = 5 #encoded_params = urllib.urlencode(url_params) url = 'http://api.yelp.com/v2/search?term=' + term + '&ll=' + latlong + '&limit=' + str(limit) #'http://{0}{1}?{2}'.format(host, path, encoded_params) consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET) oauth_request = oauth2.Request('GET', url, {}) oauth_request.update( { 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': TOKEN, 'oauth_consumer_key': CONSUMER_KEY } ) token = oauth2.Token(TOKEN, TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() conn = urllib2.urlopen(signed_url, None) try: json_data = json.loads(conn.read()) finally: conn.close() #if json_data['status'] == 'OK': for place in json_data['businesses']: print '%s\n' % (place['name'])
def search(self, lat, lon, offset): params = { 'term': self.DEFAULT_TERM, 'location': self.DEFAULT_LOCATION, 'cll': str(lat) + "," + str(lon), 'offset': offset } url = self.YELP_BASE + "search/" consumer = oauth2.Consumer(self.CONSUMER_KEY, self.CONSUMER_SECRET) oauth_request = oauth2.Request(method="GET", url=url, parameters=params) oauth_request.update({ 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': self.TOKEN, 'oauth_consumer_key': self.CONSUMER_KEY }) token = oauth2.Token(self.TOKEN, self.TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() print 'Querying {0} ...'.format(url) conn = urllib2.urlopen(signed_url, None) try: response = json.loads(conn.read()) finally: conn.close() return response
def request(host, path, url_params=None): url_params = url_params or {} url = 'http://{0}{1}?'.format(host, urllib.parse.quote(path.encode('utf8'))) consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET) oauth_request = oauth2.Request(method="GET", url=url, parameters=url_params) oauth_request.update({ 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': TOKEN, 'oauth_consumer_key': CONSUMER_KEY }) token = oauth2.Token(TOKEN, TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() try: conn = urlopen(signed_url, None) except urllib.error.HTTPError as error: response = json.loads('{"status":"failure"}') return response try: response = json.loads(conn.read().decode('utf-8')) finally: conn.close() return response
def request(host, path, url_params=None): url_params = url_params or {} url = 'http://{0}{1}?'.format(host, urllib.quote(path.encode('utf8'))) consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET) oauth_request = oauth2.Request(method="GET", url=url, parameters=url_params) oauth_request.update( { 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': TOKEN, 'oauth_consumer_key': CONSUMER_KEY } ) token = oauth2.Token(TOKEN, TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() print u'Querying {0} ...'.format(url) conn = urllib2.urlopen(signed_url, None) try: response = json.loads(conn.read()) finally: conn.close() return response
def request(url_params): encoded_params = urllib.urlencode(url_params) url = '%s?%s' % (base_url, encoded_params) # print 'URL: %s' % url # Oauth Sign consumer = oauth2.Consumer(auth['consumer_key'], auth['consumer_secret']) oauth_request = oauth2.Request('GET', url, {}) oauth_request.update({'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': auth['access_token'], 'oauth_consumer_key': auth['consumer_key']}) token = oauth2.Token(auth['access_token'], auth['access_token_secret']) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() # print 'Signed URL: %s\n' % (signed_url) # Connect try: conn = urllib2.urlopen(signed_url, None) try: response = conn.read() finally: conn.close() except urllib2.HTTPError, error: response = ""
def get_by_cache_key(klass, search_term): obj = memcache.get(search_term) # not in memcache, so check database and set memcache if not obj: obj = YelpCacheObject.all().filter('cache_key =', search_term).get() memcache.set(search_term, obj) # not in db, so hit yelp's api and put in db and memcache if not obj: url = '%s?%s' % (YELP_API_URL, search_term) # Sign the URL consumer = oauth.Consumer(YELP_CONSUMER_KEY, YELP_CONSUMER_SECRET) oauth_request = oauth.Request('GET', url, {}) oauth_request.update({ 'oauth_nonce': oauth.generate_nonce(), 'oauth_timestamp': oauth.generate_timestamp(), 'oauth_token': YELP_TOKEN, 'oauth_consumer_key': YELP_CONSUMER_KEY }) token = oauth.Token(YELP_TOKEN, YELP_TOKEN_SECRET) oauth_request.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() obj = YelpCacheObject( cache_key=search_term, result=urlfetch.fetch(signed_url).content.strip(), ) obj.put() memcache.set(search_term, obj) return obj
def get_response(lat, lon, token, consumer_key, consumer_secret, token_secret): url_params = {'term': 'coffee', 'sort': 1, 'll': lat + "," + lon} encoded_params = '' if url_params: encoded_params = urllib.urlencode(url_params) url = 'http://api.yelp.com/v2/search?%s' % (encoded_params) print 'URL: %s' % (url,) # Sign the URL consumer = oauth2.Consumer(consumer_key, consumer_secret) oauth_request = oauth2.Request('GET', url, {}) oauth_request.update({'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': token, 'oauth_consumer_key': consumer_key}) token = oauth2.Token(token, token_secret) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() print 'Signed URL: %s\n' % (signed_url,) response = "" # Connect try: conn = urllib2.urlopen(signed_url, None) try: response = json.loads(conn.read()) finally: conn.close() except urllib2.HTTPError, error: response = json.loads(error.read())
def request(host, path, url_params=None): url_params = url_params or {} url = 'https://{0}{1}?'.format(host, urllib.quote(path.encode('utf8'))) print url consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET) oauth_request = oauth2.Request(method="GET", url=url, parameters=url_params) oauth_request.update( { 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': TOKEN, 'oauth_consumer_key': CONSUMER_KEY } ) token = oauth2.Token(TOKEN, TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() conn = urllib2.urlopen(signed_url, None) try: response = json.loads(conn.read()) finally: conn.close() return response
def searchRequest(host, path, consumer_key, consumer_secret, token, token_secret,searchTerm): """Returns response for API request.""" #host = 'api.yelp.com' #path = '/v2/search' url = 'http://%s%s?' % (host, path) url = url + 'term='+ searchTerm +'&location=united+states&limit=1' #print 'URL: %s' % (url) # Sign the URL consumer = oauth2.Consumer(consumer_key, consumer_secret) oauth_request = oauth2.Request('GET', url, {}) oauth_request.update({'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': token, 'oauth_consumer_key': consumer_key}) token = oauth2.Token(token, token_secret) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() #print 'Signed URL: %s\n' % (signed_url,) # Connect try: conn = urllib2.urlopen(signed_url, None) try: response = json.loads(conn.read()) finally: conn.close() except urllib2.HTTPError, error: response = json.loads(error.read())
def requestData(location): ''' Authenticates a request and returns data from Yelp API. ''' data = [] url = 'http://api.yelp.com/v2/business/' + location + '?' consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET) oauth_request = oauth2.Request(method="GET", url=url) oauth_request.update( { 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': TOKEN, 'oauth_consumer_key': CONSUMER_KEY } ) token = oauth2.Token(TOKEN, TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() req = requests.get(signed_url) content = json.loads(req.content) data.append(content) return data
def get_signed_url(self, url, params): try: consumer_key = settings.YELP_CONSUMER_KEY consumer_secret = settings.YELP_CONSUMER_SECRET token = settings.YELP_TOKEN token_secret = settings.YELP_TOKEN_SECRET except: import traceback traceback.print_exc() print "Error: You need to set your yelp API keys!" consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret) oauth_request = oauth.Request("GET", url, params) oauth_request.update( { "oauth_nonce": oauth.generate_nonce(), "oauth_timestamp": oauth.generate_timestamp(), "oauth_token": token, "oauth_consumer_key": consumer_key, } ) token = oauth.Token(token, token_secret) oauth_request.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() return signed_url
def basic_yelp_request(location,keyword="omelette"): """ Adapted from Yelp API Search Example https://github.com/Yelp/yelp-api/blob/master/v2/python/search.py """ # Prepare URL url_params = {} url_params['location'] = location url_params['term'] = keyword encoded_params = urllib.urlencode(url_params) host = 'api.yelp.com' path = '/v2/search' url = 'http://%s%s?%s' % (host, path, encoded_params) # Sign URL consumer = oauth2.Consumer(keys["YELP_KEY"], keys["YELP_SECRET"]) oauth_request = oauth2.Request('GET', url, {}) oauth_request.update({'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': keys["YELP_TOKEN"], 'oauth_consumer_key': keys["YELP_KEY"]}) token = oauth2.Token(keys["YELP_TOKEN"], keys["YELP_TOKEN_SECRET"]) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() # Connect try: conn = urllib2.urlopen(signed_url, None) try: response = json.loads(conn.read()) finally: conn.close() except urllib2.HTTPError, error: response = json.loads(error.read())
def getBars(offset, metro_index): global token args = { 'location': getMetro(metro_index), 'category_filter': 'nightlife', 'limit': 20, 'offset': offset } url = 'http://api.yelp.com/v2/search?' consumer = oauth2.Consumer(consumer_key, consumer_secret) oauth_request = oauth2.Request('GET', url, args) oauth_request.update({ 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': token, 'oauth_consumer_key': consumer_key }) new_token = oauth2.Token(token, token_secret) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, new_token) signed_url = oauth_request.to_url() # logging.info('Signed URL: %s' % signed_url) # Connect try: conn = urllib2.urlopen(signed_url, None) try: response = json.loads(conn.read()) finally: conn.close() except urllib2.HTTPError, error: response = json.loads(error.read())
def search(term, address): consumer_key = 'YQjC8cOZxSyb-x21hpoLxg' consumer_secret = 'AJ6u905ojzMr9VkHDN_BkAbQrIA' token = '4Q20XFJ24cB8SL1CRKWY_2kNYqGnk60y' token_secret = '2hPhKm5s4kt8L5EicFD3h26cLh4' consumer = oauth2.Consumer(consumer_key, consumer_secret) url = 'http://api.yelp.com/v2/search?term=%s&location=%s&limit=%d&format=json&radius_filter=400&category=food' % ( term, address, 5) oauth_request = oauth2.Request('GET', url, {}) oauth_request.update({ 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': token, 'oauth_consumer_key': consumer_key }) token = oauth2.Token(token, token_secret) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() #connect try: conn = urllib2.urlopen(signed_url) try: response = json.load(conn) finally: conn.close() except urllib2.HTTPError, error: response = json.load(error)
def request(self, uri, method="POST", body=None, headers=None): params = { 'oauth_consumer_key': self.consumer.key, 'oauth_signature_method': self.method.name, 'oauth_token':self.token.key, 'oauth_timestamp':oauth2.generate_timestamp(), 'oauth_nonce':oauth2.generate_nonce(), 'oauth_version':'1.0' } echo_request = EchoRequest(method="GET", url=self.auth_service_provider, parameters=params ) signature=echo_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), self.consumer, self.token) if not headers: headers={} headers.update(echo_request.to_header(self.realm, self.auth_service_provider)) register_openers() datagen, heads = multipart_encode(body) headers.update(heads) req = urllib2.Request(uri, datagen, headers) response = urllib2.urlopen(req) return response
def request(host, path, url_params=None): # Prepares OAuth authentication and sends the request to the API. Args: # host (str): The domain host of the API. # path (str): The path of the API after the domain. # url_params (dict): An optional set of query parameters in the request. # Returns: dict: The JSON response from the request. # Raises: urllib2.HTTPError: An error occurs from the HTTP request. url_params = url_params or {} url = 'http://{0}{1}?'.format(host, urllib.quote(path.encode('utf8'))) consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET) oauth_request = oauth2.Request(method="GET", url=url, parameters=url_params) oauth_request.update( { 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': TOKEN, 'oauth_consumer_key': CONSUMER_KEY } ) token = oauth2.Token(TOKEN, TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() print u'Querying {0} ...'.format(url) conn = urllib2.urlopen(signed_url, None) try: response = json.loads(conn.read()) finally: conn.close() return response
def signed_url(self): # jw: My personal Yelp API keys, remove before production consumer_key = 'KJ6cR0iz4AFgyTiWI3rqVQ' consumer_secret = 'ASkzCfW9DJzOwrqJLIOxipeCe40' token = 'u5h0Xg8GKxDkld-D0i1A_m5udCxv4ka4' token_secret = '-PQcVtbGyx_lWiti1NvXBB76F7U' consumer = oauth2.Consumer(consumer_key, consumer_secret) url = self.us_url oauth_request = oauth2.Request('GET', url, {}) oauth_request.update({ 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': token, 'oauth_consumer_key': consumer_key }) token = oauth2.Token(token, token_secret) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() return signed_url
def request(url_params): """ Retrieves data from the yelp api given search parameters Args: url_params: (String) the part of a url that contains the what the user wants to search Returns: response: (Dictionary) contains all the information from yelp api """ url = "https://api.yelp.com/v2/search/" consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET) oauth_request = oauth2.Request(method="GET", url=url, parameters=url_params) oauth_request["oauth_nonce"] = oauth2.generate_nonce() oauth_request["oauth_timestamp"] = oauth2.generate_timestamp() oauth_request["oauth_token"] = TOKEN oauth_request["oauth_consumer_key"] = CONSUMER_KEY token = oauth2.Token(TOKEN,TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() print(signed_url) conn = urllib2.urlopen(signed_url, None) response = json.loads(conn.read()) conn.close() return response
def request(self, host, path, url_params=None): url_params = url_params or {} url = 'http://{0}{1}?'.format(host, urllib.quote(path.encode('utf8'))) consumer = oauth2.Consumer(self.credentials.consumer_key, self.credentials.consumer_secret) oauth_request = oauth2.Request(method="GET", url=url, parameters=url_params) oauth_request.update( { 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': self.credentials.token, 'oauth_consumer_key': self.credentials.consumer_key } ) token = oauth2.Token(self.credentials.token, self.credentials.token_secret) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() conn = urllib2.urlopen(signed_url, None) try: response = json.loads(conn.read()) finally: conn.close() return response
def search(std_url,payload): ''' This method handles OAUTH and url signing for the yelp search API v2. It inputs the std url and the arguments. This outputs the json response from the API. ''' consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET) oauth_request = oauth2.Request(method="GET", url=std_url, parameters=payload) oauth_request.update( { 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': TOKEN, 'oauth_consumer_key': CONSUMER_KEY } ) #print(std_url) token = oauth2.Token(TOKEN, TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() conn = urllib2.urlopen(signed_url,None) try: response = json.loads(conn.read()) finally: conn.close() return response
def requestData(location): """ Authenticates a request and returns data from Yelp API. """ data = [] url = "http://api.yelp.com/v2/business/" + location + "?" consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET) oauth_request = oauth2.Request(method="GET", url=url) oauth_request.update( { "oauth_nonce": oauth2.generate_nonce(), "oauth_timestamp": oauth2.generate_timestamp(), "oauth_token": TOKEN, "oauth_consumer_key": CONSUMER_KEY, } ) token = oauth2.Token(TOKEN, TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() req = requests.get(signed_url) content = json.loads(req.content) data.append(content) return data
def request(host, path, url_params, consumer_key, consumer_secret, token, token_secret): """Returns response for API request.""" # Unsigned URL encoded_params = None if url_params: encoded_params = urllib.urlencode(url_params) url = 'http://%s%s?%s' % (host, path, encoded_params) print 'URL: %s' % (url, ) # Sign the URL consumer = oauth2.Consumer(consumer_key, consumer_secret) oauth_request = oauth2.Request('GET', url, {}) oauth_request.update({ 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': token, 'oauth_consumer_key': consumer_key }) token = oauth2.Token(token, token_secret) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() print 'Signed URL: %s\n' % (signed_url, ) # Connect try: conn = urllib2.urlopen(signed_url, None) try: response = json.loads(conn.read()) finally: conn.close() except urllib2.HTTPError, error: response = json.loads(error.read())
def sign_url(self, host, path, url_params=None): """Prepares OAuth authentication and return the signed url. Args: host (str): The domain host of the API. path (str): The path of the API after the domain. url_params (dict): An optional set of query parameters in the request. Returns: dict: The JSON response from the request. Raises: urllib2.HTTPError: An error occurs from the HTTP request. """ url_params = url_params or {} url = 'http://{0}{1}?'.format(host, urllib.quote(path.encode('utf8'))) consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET) oauth_request = oauth2.Request(method="GET", url=url, parameters=url_params) oauth_request.update( { 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': TOKEN, 'oauth_consumer_key': CONSUMER_KEY } ) token = oauth2.Token(TOKEN, TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() return signed_url
def request(url, url_params=None): consumer_key = creds['consumer_key'] consumer_secret = creds['consumer_secret'] token = creds['token'] token_secret = creds['token_secret'] url_params = url_params or {} consumer = oauth2.Consumer(consumer_key, consumer_secret) oauth_request = oauth2.Request(method="GET", url=url, parameters=url_params) oauth_request.update({ 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': token, 'oauth_consumer_key': consumer_key }) token = oauth2.Token(token, token_secret) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() raw = urllib.urlopen(signed_url).read() data = json.loads(raw) return data
def get_business(business_id): path = BUSINESS_PATH + business_id url = "http://{0}{1}?".format(API_HOST, urllib.quote(path.encode("utf8"))) # Get authorization using oauth2 protocol consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET) oauth_request = oauth2.Request(method="GET", url=url) oauth_request.update( { "oauth_nonce": oauth2.generate_nonce(), "oauth_timestamp": oauth2.generate_timestamp(), "oauth_token": TOKEN, "oauth_consumer_key": CONSUMER_KEY, } ) token = oauth2.Token(TOKEN, TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() conn = urllib2.urlopen(signed_url, None) try: response = json.loads(conn.read()) finally: conn.close() return response
def request(host, path, key, key_secret, token, token_secret, url_params=None): """ Prepares OAuth authentication and sends the request to the API. Args: host (str): The domain host of the API. path (str): The path of the API after the domain. url_params (dict): An optional set of query parameters in the request. Returns: dict: The JSON response from the request. Raises: urllib2.HTTPError: An error occurs from the HTTP request. """ url_params = url_params or {} url = 'http://{0}{1}?'.format(host, urllib.quote(path.encode('utf8'))) consumer = oauth2.Consumer(key, key_secret) oauth_request = oauth2.Request(method="GET", url=url, parameters=url_params) oauth_request.update({ 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': token, 'oauth_consumer_key': key }) token = oauth2.Token(token, token_secret) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() conn = urllib2.urlopen(signed_url, None) try: response = json.loads(conn.read()) finally: conn.close() return response
def yelp_request(url_params, host='api.yelp.com', path='/v2/search'): """Returns response for API request.""" # Unsigned URL encoded_params = '' if url_params: encoded_params = urllib.urlencode(url_params) url = 'http://%s%s?%s' % (host, path, encoded_params) # Sign the URL consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET) oauth_request = oauth2.Request('GET', url, {}) oauth_request.update({'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': TOKEN, 'oauth_consumer_key': CONSUMER_KEY}) token = oauth2.Token(TOKEN, TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() # Connect try: conn = urllib2.urlopen(signed_url, None) try: response = json.loads(conn.read()) finally: conn.close() except urllib2.HTTPError, error: response = json.loads(error.read())
def get_request_token_url(self): # build the token request req = oauth.Request( method='GET', url=self.request_token_url, parameters={ 'oauth_callback': 'http://stage.ht-tools.eu/login', 'oauth_nonce': oauth.generate_nonce(), 'oauth_timestamp': oauth.generate_timestamp(), 'oauth_version': '1.0', }, is_form_encoded=True # needed to avoid oauth_body_hash ) # sign it req.sign_request(self.signature_method, self.consumer, None) with contextlib.closing(urllib2.urlopen(req.to_url())) as x: # send the request responseData = x.read() request_token = dict(urlparse.parse_qsl(responseData)) # parse the response self.oauth_req_token = request_token['oauth_token'] self.oauth_req_token_secret = request_token['oauth_token_secret'] # return the authorization url, with the token return request_token['oauth_token'], request_token[ 'oauth_token_secret'], "%s?oauth_token=%s" % ( self.authorize_path, request_token['oauth_token'])
def get_access_token(self, request_token, request_token_secret, pin): # build the request req = oauth.Request( method='GET', url=self.access_token_path, parameters={ 'oauth_nonce': oauth.generate_nonce(), 'oauth_timestamp': oauth.generate_timestamp(), 'oauth_version': '1.0', 'oauth_verifier': pin }, is_form_encoded=True # needed to avoid oauth_body_hash ) token = oauth.Token(request_token, request_token_secret) token.set_verifier(pin) # sign it req.sign_request(self.signature_method, self.consumer, token) with contextlib.closing(urllib2.urlopen(req.to_url())) as x: # send the request responseData = x.read() request_token = dict(urlparse.parse_qsl(responseData)) token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) return token
def yelp_req(url): """ Pass in a url that follows the format of Yelp API, and this function will return either a JSON object or error messages. """ oauth_request = oauth2.Request('GET', url, {}) oauth_request.update( { 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': TOKEN, 'oauth_consumer_key': CONSUMER_KEY } ) consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET) token = oauth2.Token(TOKEN, TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() conn = urllib2.urlopen(signed_url, None) try: response = json.loads(conn.read()) finally: conn.close() return response
def get_business(business_id): path = BUSINESS_PATH + business_id url = 'http://{0}{1}?'.format(API_HOST, urllib.quote(path.encode('utf8'))) # Get authorization using oauth2 protocol consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET) oauth_request = oauth2.Request(method="GET", url=url) oauth_request.update({ 'oauth_nonce': oauth2.generate_nonce(), 'oauth_timestamp': oauth2.generate_timestamp(), 'oauth_token': TOKEN, 'oauth_consumer_key': CONSUMER_KEY }) token = oauth2.Token(TOKEN, TOKEN_SECRET) oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token) signed_url = oauth_request.to_url() conn = urllib2.urlopen(signed_url, None) try: response = json.loads(conn.read()) finally: conn.close() return response