Example #1
0
    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
Example #2
0
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]
Example #3
0
    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
Example #4
0
def get_matches_from_team_id(team_id):

    params = {
        'oauth_version': "1.0",
        'oauth_nonce': oauth.generate_nonce(),
        'oauth_timestamp': str(int(time.time())),
        'file': 'matchesarchive',
        'teamID': team_id,
    }

    req = oauth.Request(method="GET", url=url_content, parameters=params)
    req.sign_request(signature_method, consumer,token)

    with contextlib.closing(urllib2.urlopen(req.to_url(), timeout=10)) as x:
                # send the request
                responseData = x.read()
                #return responseData

    
    root = ET.fromstring(responseData)
    matches = []
    for child in root.findall('Team'):
        for res in child.findall('MatchList'):
            for match in res.findall('Match'):
                id     = match.find('MatchID').text
                type   = match.find('MatchType').text
                #status = match.find('Status').text
                date   = match.find('MatchDate').text                
                matches.append({"match_id":int(id),"match_type":int(type),#"match_status":status,
                                "match_date":date})

    return matches
def api_request(list_of_tweets):
    """Takes a list of up to 100 tweet ids and returns tweet details, including
    retweet count. Tweets in original list must be strings."""
    #Create api searcher:
    url1 = 'https://api.twitter.com/1.1/statuses/lookup.json'
    params = {
        "oauth_version": "1.0",
        "oauth_nonce": oauth2.generate_nonce(),
        "oauth_timestamp": int(time.time())
    }
    consumer = oauth2.Consumer(key=consumer_key, secret=consumer_secret)
    token = oauth2.Token(key=access_token_key, secret=access_token_secret)
    params["oauth_consumer_key"] = consumer.key
    params["oauth_token"] = token.key
    
    tweets_as_strings = ','.join(list_of_tweets)
    url = url1
    params['id'] = tweets_as_strings
    params['map'] = 'true'
    req = oauth2.Request(method="GET", url=url, parameters=params)
    signature_method = oauth2.SignatureMethod_HMAC_SHA1()
    req.sign_request(signature_method, consumer, token)
    headers = req.to_header()
    url = req.to_url()
    response = urllib2.Request(url)
    tweets = urllib2.urlopen(response)
    return json.load(tweets)
def get_users_by_screen_name(screen_names):   #18k per 15 mins

    url1 = "https://api.twitter.com/1.1/users/lookup.json"
    params = {
    "oauth_version": "1.0",
    "oauth_nonce": oauth2.generate_nonce(),
    "oauth_timestamp": int(time.time())
    }

    params["oauth_consumer_key"] = consumer.key
    params["oauth_token"] = token.key

    # Convert list to csv
    screen_names = ','.join(screen_names)
    params["screen_name"] = screen_names

    req = oauth2.Request(method="GET", url=url1, parameters=params)        #changed from "GET" to "POST" as twitter recommends
    signature_method = oauth2.SignatureMethod_HMAC_SHA1()
    req.sign_request(signature_method, consumer, token)
    url = req.to_url()

    response = urllib.request.urlopen(url)
    data = response.read().decode('utf-8')
    data = json.loads(data)

    return data
Example #7
0
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())
Example #8
0
File: yelp.py Project: gmyou/yelp
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())
Example #9
0
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())
Example #10
0
    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
Example #11
0
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()
Example #12
0
    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
Example #13
0
    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
Example #14
0
def gen_jwt_params(params={}, user=None):
    """Generates valid JWT parameters.

    Params can overwrite all results, including timestamp, nonce and signature to produce an invalid request."""
    req = BASE_PARAMS.copy()

    if user:
        req = {
            **req,
            **{
                'roles':
                settings.ROLES['Teacher'] if user.is_teacher else settings.ROLES['Student'],
                'user_id':
                user.lti_id,
                'custom_username':
                user.username,
                'custom_user_email':
                user.email,
                'custom_user_full_name':
                user.full_name,
            },
        }

    req['oauth_timestamp'] = str(int(time.time()))
    req['oauth_nonce'] = str(oauth2.generate_nonce())

    req = {**req, **params}

    if 'oauth_signature' in params:
        req['oauth_signature'] = req['oauth_signature']
    else:
        req['oauth_signature'] = get_signature(req)

    return {'jwt_params': lti_view.encode_lti_params(req)}
Example #15
0
    def set_verifier(self, oauth_verifier):
        if self.request_token is None:
            raise AuthHandlerError(
                ("Request token is not defined. "
                 "This ususally means that the access token has been loaded "
                 "from a file."))
        self.request_token.set_verifier(oauth_verifier)

        access_token_parms = {
            'oauth_consumer_key': self.key,
            'oauth_nonce': oauth2.generate_nonce(),
            'oauth_signature_method': "HMAC-SHA1",
            'oauth_timestamp': str(int(time.time())),
            'oauth_token': self.request_token.key,
            'oauth_verifier': self.request_token.verifier
        }

        req = oauth2.Request(method="GET",
                             url=ACCESS_TOKEN_URL,
                             parameters=access_token_parms)
        req.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), self.consumer,
                         self.request_token)
        resp = urlopen_and_read(req.to_url())
        access_token_resp = dict(urllib.parse.parse_qsl(resp))

        self.access_token = oauth2.Token(
            access_token_resp["oauth_token"],
            access_token_resp["oauth_token_secret"])
Example #16
0
 def request(self):
     ''' Returns an oauth2 request object to be used for connecting to the
     streaming API endpoint. For debugging purposes, the returned request
     object is cached in self._last_request.
         
     >>> req = stream.request
     >>> print req.to_url() #doctest: +ELLIPSIS
     https://sitestream.twitter.com/2b/site.json?...
     
     '''
     parameters = {
         'oauth_version': "1.0",
         'oauth_nonce': oauth.generate_nonce(),
         'oauth_timestamp': int(time.time()),
         'follow': ','.join(map(str, self.follow)),
         'with': self.stream_with,
         'oauth_token': self.token.key,
         'oauth_consumer_key': self.consumer.key
     }
     request = oauth.Request(METHOD, self.url, parameters=parameters)
     request.sign_request(
         oauth.SignatureMethod_HMAC_SHA1(), self.consumer, self.token)
     
     self._last_request = request
     logger.debug("OAuth Request Object Generated. %s" % request)
     return request
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
Example #18
0
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
Example #19
0
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())
Example #20
0
    def _generate_valid_signed_request_url(self,
                                           url,
                                           method='GET',
                                           querystring={}):

        consumer = oauth.Consumer(self.oauth_consumer_key,
                                  self.oauth_consumer_secret)

        oauth_params = {
            'oauth_version': '1.0',
            'oauth_nonce': oauth.generate_nonce(),
            'oauth_timestamp': int(time.time())
        }

        if querystring:
            oauth_params.update(querystring)

        signature_method = oauth.SignatureMethod_HMAC_SHA1()

        request = oauth.Request(method=method,
                                url=url,
                                parameters=oauth_params)
        request.sign_request(signature_method, consumer, None)

        signed_querystring = urlparse.urlparse(request.to_url())[4]
        return '{0}?{1}'.format(url, signed_querystring)
Example #21
0
    def get_signed_uri(self, serialized_body, uri, http_method):

        # There is no requirement for the token in two-legged
        # OAuth but we still need the token object.
        token = oauth.Token(key='', secret='')
        consumer = oauth.Consumer(key=self.oauth_key, secret=self.oauth_secret)

        parameters = {
            'user': self.user,
            'oauth_version': '1.0',
            'oauth_nonce': oauth.generate_nonce(),
            'oauth_timestamp': int(time.time())
        }

        try:
            req = oauth.Request(
                method=http_method,
                body=serialized_body,
                url=uri,
                parameters=parameters
            )
        except AssertionError:
            logger.error('uri: %s' % uri)
            logger.error('body: %s' % serialized_body)
            raise

        signature_method = oauth.SignatureMethod_HMAC_SHA1()
        req.sign_request(signature_method, consumer, token)

        return req.to_url()
Example #22
0
File: yelp.py Project: amni/SMSmart
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
Example #23
0
    def _makeOAuthRequest(self,
                          url,
                          token=None,
                          params=None,
                          http_method="GET"):
        '''Make a OAuth request from url and parameters
        
        Args:
          url: The Url to use for creating OAuth Request
          parameters:
             The URL parameters
          http_method:
             The HTTP method to use
        Returns:
          A OAauthRequest object
        '''

        oauth_base_params = {
            'oauth_version': "1.0",
            'oauth_nonce': oauth.generate_nonce(),
            'oauth_timestamp': int(time.time())
        }

        if params:
            params.update(oauth_base_params)
        else:
            params = oauth_base_params

        if not token:
            token = self._access_token
        request = oauth.Request(method=http_method, url=url, parameters=params)
        request.sign_request(self._signature_method, self._Consumer, token)
        return request
Example #24
0
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
Example #25
0
def get_barcodes(users=None, start_date=None):
    url = 'https://5339579.restlets.api.netsuite.com/app/site/hosting/restlet.nl?script=384&deploy=1&start_date=%s&end_date=%s'
    params = {
        'oauth_version': "1.0",
        'oauth_nonce': oauth.generate_nonce(),
        'oauth_timestamp': "%s" % int(time.time()),
        'oauth_token': token.key,
        'oauth_consumer_key': consumer.key
    }
    if not start_date:
        ba_obj = Barcodes.objects.all().order_by('-created')
        start_date = '11/01/2019'
        if ba_obj:
            start_date = ba_obj[0].created.strftime("%m/%d/%Y %H:%M")
    url = url % (start_date, datetime.now().strftime("%m/%d/%Y %H:%M"))

    headers = create_request_auth_header(http_method, url, params)
    res = requests.get(url, headers=headers)
    res = json.loads(res.content.decode())
    if res:
        querysetlist = []
        for val in res:
            check_re = Barcodes.objects.filter(sku=val['sku'])
            if not check_re:
                querysetlist.append(Barcodes(sku=val['sku'], user=users))
        if querysetlist:
            Barcodes.objects.bulk_create(querysetlist)
    return res
Example #26
0
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'])
Example #27
0
def get_team_details_from_team_id(team_id):

    params = {
        'oauth_version': "1.0",
        'oauth_nonce': oauth.generate_nonce(),
        'oauth_timestamp': str(int(time.time())),
        'file': 'teamdetails',
        'version': 3.2,
        'teamID': team_id,
    }

    req = oauth.Request(method="GET", url=url_content, parameters=params)
    req.sign_request(signature_method, consumer,token)

    with contextlib.closing(urllib2.urlopen(req.to_url(), timeout=10)) as x:
                # send the request                                                                                                                                                                                                            
                responseData = x.read()
                #return responseData                                                                                                                                                                                                          

    root = ET.fromstring(responseData)
    #for child in root.findall('CurrentMatchRound'):                                                                                                                                                                                         

    for child in root.findall('Teams'):
        t = child.find("Team")
        id   = t.find('TeamID').text
        name = t.find('TeamName').text
        birth = t.find('FoundedDate').text
        r = t.find("Region")
        region = r.find('RegionName').text
        l = t.find("League")
        league = l.find('LeagueName').text
    team = {"team_name":name,"team_id":int(id), "team_birth":birth,"team_region":region,"league_name":league}

    return team
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())
Example #29
0
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
Example #30
0
    def _build_request(self, string, reverse):
        """
        Returns a signed oauth request for the given query
        """
        request = oauth2.Request(
            method='GET',
            parameters={
                'oauth_nonce': oauth2.generate_nonce(),
                'oauth_timestamp': int(time.time()),
                'oauth_version': '1.0',
            },
            url='%s?location=%s&flags=J%s' % (
                '%s://yboss.yahooapis.com/geo/placefinder' % self.scheme,
                urllib.quote(string.encode('utf-8')),
                '&gflags=R' if reverse else '', # todo refactor
            ),
        )

        request.sign_request(
            oauth2.SignatureMethod_HMAC_SHA1(),
            oauth2.Consumer(self.consumer_key, self.consumer_secret),
            None,
        )

        return request
Example #31
0
def prepare_request(url, url_params):
    reqconfig = read_reqauth()
    config = read_config()

    token = oauth.Token(key=reqconfig.oauth_token,
                        secret=reqconfig.oauth_token_secret)

    consumer = oauth.Consumer(key=config.consumer_key,
                              secret=config.consumer_secret)

    params = {
        "oauth_version": "1.0",
        "oauth_nonce": oauth.generate_nonce(),
        "oauth_timestamp": str(int(time.time())),
        "oauth_token": token.key,
        "oauth_consumer_key": consumer.key,
    }

    params.update(url_params)

    req = oauth.Request(method="GET", url=url, parameters=params)

    signature_method = oauth.SignatureMethod_HMAC_SHA1()
    req.sign_request(signature_method, consumer, token)
    return req.to_url()
Example #32
0
    def send_tweet(self, msg):

        host = 'api.twitter.com'
        endpoint = '/1/statuses/update.json'

        url = 'http://' + host + endpoint

        token = oauth2.Token(key=config['twitter_access_token'], secret=config['twitter_access_secret'])
        consumer = oauth2.Consumer(key=config['twitter_consumer_token'], secret=config['twitter_consumer_secret'])

        params = {
            'status' : msg,
            'oauth_token' : token.key,
            'oauth_consumer_key' : consumer.key,
            'oauth_nonce' : oauth2.generate_nonce(),
            'oauth_timestamp' :int(time.time()),
            }

        req = oauth2.Request(method="POST", url=url, parameters=params)

        signature_method = oauth2.SignatureMethod_HMAC_SHA1()
        req.sign_request(signature_method, consumer, token)

        body = req.to_postdata()

        conn = httplib.HTTPConnection('api.twitter.com')
        conn.request('POST', '/1/statuses/update.json', body)

        rsp = conn.getresponse()
        return rsp.status
Example #33
0
    def get_signed_uri(self, serialized_body, uri, http_method):

        # There is no requirement for the token in two-legged
        # OAuth but we still need the token object.
        token = oauth.Token(key='', secret='')
        consumer = oauth.Consumer(key=self.oauth_key, secret=self.oauth_secret)

        parameters = {
            'user': self.user,
            'oauth_version': '1.0',
            'oauth_nonce': oauth.generate_nonce(),
            'oauth_timestamp': int(time.time())
        }

        try:
            req = oauth.Request(method=http_method,
                                body=serialized_body,
                                url=uri,
                                parameters=parameters)
        except AssertionError:
            logger.error('uri: %s' % uri)
            logger.error('body: %s' % serialized_body)
            raise

        signature_method = oauth.SignatureMethod_HMAC_SHA1()
        req.sign_request(signature_method, consumer, token)

        return req.to_url()
Example #34
0
    def validateAuthorization(self, pin) :
        #Generate Token
        self.token.set_verifier(pin)
    
        #access params
        access_token_params = {
            'oauth_consumer_key': flickrAuthConstants.keys['apikey'],
            'oauth_nonce': oauth2.generate_nonce(),
            'oauth_signature_method':"HMAC-SHA1",
            'oauth_timestamp': str(int(time.time())),
            'oauth_token': self.req_token['oauth_token'],
            'oauth_verifier' : pin
        }
    
        #setup request
        req = oauth2.Request(method="GET", url=flickrAuthConstants.access_token_url,
            parameters=access_token_params)
            
        #create the signature
        signature = oauth2.SignatureMethod_HMAC_SHA1().sign(req,self.consumer,self.token)
        
        # assign the signature to the request
        req['oauth_signature'] = signature
        try:
            #make the request
            h = httplib2.Http(".cache")
            resp, content = h.request(req.to_url(), "GET")

            #parse the response
            self.access_token = dict(urlparse.parse_qsl(content))
        except Exception, e:
            print e;
Example #35
0
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)
Example #36
0
    def validateTokenOnFlickr(self):
        params = {
            'method':'flickr.auth.oauth.checkToken',
            'oauth_nonce': oauth2.generate_nonce(),
            'oauth_signature_method':"HMAC-SHA1",
            'oauth_timestamp': str(int(time.time())),
            'oauth_consumer_key':flickrAuthConstants.keys['apikey'],
            'oauth_token':self.access_token['oauth_token']
            ,'format':'json'
            ,'nojsoncallback':1
        }
        
        # Create our request. Change method, etc. accordingly.
        req = oauth2.Request(method="GET",
                             url=flickrAuthConstants.base_url,
                             parameters=params);

        
        # Create the signature
        signature = oauth2.SignatureMethod_HMAC_SHA1().sign(req, self.consumer, self.token);
        
        req['oauth_signature'] = signature;
        
        h = httplib2.Http(".cache")

        resp, jsonData = h.request(req.to_url(), "GET")
        
        content = json.loads(jsonData);
        
        return content['stat'];
Example #37
0
    def post_response_for_url(self, url, context, account):
        parameters = self.params
        parameters['oauth_nonce'] = oauth.generate_nonce()
        parameters['oauth_timestamp'] = '%s' % int(time.time())
        if account:
            parameters['account'] = account
        elif self.account:
            parameters['account'] = self.account

        for key in context:
            if isinstance(context[key],collections.Iterable):
                parameters[key] = quote(context[key])
            else:
                parameters[key] = context[key]

        req = oauth.Request(method="POST", url=url, parameters=parameters)
        # Sign the request.
        signature_method = oauth.SignatureMethod_HMAC_SHA1()
        req.sign_request(signature_method, self.consumer, None)
        response, content = self.request(url,
                                        method="POST",
                                        body=req.to_postdata(),
                                        headers={'Content-Type': 'application/x-www-form-urlencoded'},
                                        redirections=httplib2.DEFAULT_MAX_REDIRECTS,
                                        connection_type=None)
        if response['status'] != '200':
            raise Exception("Invalid response %s" % response['status'])
        return ContextIOResponse(response, content)
def get_profile_banner_info(screen_name, user_id):
    # e.g.
    # https://api.twitter.com/1.1/users/profile_banner.json?screen_name=rjsinha

    url1 = "https://api.twitter.com/1.1/users/profile_banner.json"
    params = {
        "oauth_version": "1.0",
        "oauth_nonce": oauth2.generate_nonce(),
        "oauth_timestamp": int(time.time())
    }

    params["oauth_consumer_key"] = consumer.key
    params["oauth_token"] = token.key
    #params["screen_name"] = screen_name
    params["user_id"] = user_id

    req = oauth2.Request(method="GET", url=url1, parameters=params)
    signature_method = oauth2.SignatureMethod_HMAC_SHA1()
    req.sign_request(signature_method, consumer, token)
    url = req.to_url()

    response = urllib.request.urlopen(url)
    data = response.read().decode('utf-8')
    data = json.loads(data)

    return data
Example #39
0
def post(body, title=None, type='text', state='published', tags='', date=None):
    endpoint = TUMBLR + BLOG + '/post'
    if date is None:
        date = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S GMT')
    params = {
            'type': type,
            'state': state,
            'tags': tags,
            'date': date,
            'title': title,
            'body': body,
            'oauth_version': '1.0',
            'oauth_nonce': oauth.generate_nonce(),
            'oauth_timestamp': int(time.time()),
            'oauth_token': ACCESS_TOKEN,
            'oauth_consumer_key': CONSUMER_KEY
    }

    req = oauth.Request(method='POST', url=endpoint, parameters=params)
    sig_method = oauth.SignatureMethod_HMAC_SHA1()
    req.sign_request(sig_method, consumer, token)
    print(params)
    data = urlencode(params).encode('utf-8')
    resp, content = client.request(endpoint, 'POST', data)
    if resp['status'] != '201':
        raise Exception('Post creation failed.')
def get_followers_data(follower_ids):  #18k per 15 mins

    url1 = "https://api.twitter.com/1.1/users/lookup.json"
    params = {
        "oauth_version": "1.0",
        "oauth_nonce": oauth2.generate_nonce(),
        "oauth_timestamp": int(time.time())
    }

    params["oauth_consumer_key"] = consumer.key
    params["oauth_token"] = token.key

    params["user_id"] = str(follower_ids)[:-1][1:]

    req = oauth2.Request(
        method="GET", url=url1,
        parameters=params)  #changed from "GET" to "POST" as twitter recommends
    signature_method = oauth2.SignatureMethod_HMAC_SHA1()
    req.sign_request(signature_method, consumer, token)
    url = req.to_url()

    response = urllib.request.urlopen(url)
    data = response.read().decode('utf-8')
    data = json.loads(data)

    return data
Example #41
0
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 __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
Example #43
0
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
Example #44
0
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 get_profile_banner_info(screen_name, user_id):
    # e.g.
    # https://api.twitter.com/1.1/users/profile_banner.json?screen_name=rjsinha

    url1 = "https://api.twitter.com/1.1/users/profile_banner.json"
    params = {
        "oauth_version": "1.0",
        "oauth_nonce": oauth2.generate_nonce(),
        "oauth_timestamp": int(time.time())
    }

    params["oauth_consumer_key"] = consumer.key
    params["oauth_token"] = token.key
    #params["screen_name"] = screen_name
    params["user_id"] = user_id

    req = oauth2.Request(method="GET", url=url1,
                         parameters=params)
    signature_method = oauth2.SignatureMethod_HMAC_SHA1()
    req.sign_request(signature_method, consumer, token)
    url = req.to_url()

    response = urllib.request.urlopen(url)
    data = response.read().decode('utf-8')
    data = json.loads(data)

    return data
Example #46
0
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
Example #47
0
def get_kit_skus(start_date=None):
    url = 'https://5339579.restlets.api.netsuite.com/app/site/hosting/restlet.nl?script=376&deploy=1&start_date=%s&end_date=%s'
    params = {
        'oauth_version': "1.0",
        'oauth_nonce': oauth.generate_nonce(),
        'oauth_timestamp': "%s" % int(time.time()),
        'oauth_token': token.key,
        'oauth_consumer_key': consumer.key
    }
    if not start_date:
        kit_obj = KitSkus.objects.all().order_by('-created')
        start_date = '10/24/2019'
        if kit_obj:
            start_date = kit_obj[0].created.strftime("%m/%d/%Y")
    url = url % (start_date, datetime.now().strftime("%m/%d/%Y"))

    headers = create_request_auth_header(http_method, url, params)
    res = requests.get(url, headers=headers)
    res = json.loads(res.content.decode())
    querylist = []
    kit_list = []
    for val in res:
        try:
            kit_list.append(val['kit'])
            querylist.append(KitSkus(kit=val['kit'], sku=val['sku']))
        except:
            continue
    del_li = KitSkus.objects.filter(kit__in=kit_list)
    if del_li:
        del_li.delete()
    if querylist:
        KitSkus.objects.bulk_create(querylist)
Example #48
0
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())
Example #49
0
def api_save_kit_sku(data, kit_country, fulfill_type):
    url = 'https://5339579.restlets.api.netsuite.com/app/site/hosting/restlet.nl?script=396&deploy=1'
    params = {
        'oauth_version': "1.0",
        'oauth_nonce': oauth.generate_nonce(),
        'oauth_timestamp': "%s" % int(time.time()),
        'oauth_token': token.key,
        'oauth_consumer_key': consumer.key
    }
    body = {
        'kit_country': kit_country,
        'fulfill_type': fulfill_type,
        'kit_items': data
    }
    http_method = 'POST'
    headers = create_request_auth_header(http_method, url, params)
    response = requests.post(url, json=body, headers=headers)
    res = {'code': 1001}
    if response.status_code != 200:
        response = json.loads(response.content.decode())
        if 'error' in response:
            res.update({
                'code' : 1001,
                'msg' :  response['error']['message']
            })
        return res
    response = json.loads(response.content.decode())
    res.update({
        'code': 1,
        'id': response
    })
    return res
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 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
Example #52
0
def get_series_id_from_name(series_name):

    params = {
        'oauth_version': "1.0",
        'oauth_nonce': oauth.generate_nonce(),
        'oauth_timestamp': str(int(time.time())),
        'file': 'search',
        'version': 1.2,
        'searchType': 3,
        'searchString': series_name
    }

    req = oauth.Request(method="GET", url=url_content, parameters=params)
    req.sign_request(signature_method, consumer, token)

    with contextlib.closing(urllib2.urlopen(req.to_url(), timeout=10)) as x:
                # send the request
                responseData = x.read()
                #print responseData

    root = ET.fromstring(responseData)

    for child in root.findall('SearchResults'):
        for res in child.findall('Result'):
            id   = res.find('ResultID').text
            name = res.find('ResultName').text
            if (name==series_name): return int(id)
Example #53
0
    def _makeOAuthRequest(self, url, token=None, params=None, http_method="GET"):
        """Make a OAuth request from url and parameters
        
        Args:
          url: The Url to use for creating OAuth Request
          parameters:
             The URL parameters
          http_method:
             The HTTP method to use
        Returns:
          A OAauthRequest object
        """

        oauth_base_params = {
            "oauth_version": "1.0",
            "oauth_nonce": oauth.generate_nonce(),
            "oauth_timestamp": int(time.time()),
        }

        if params:
            params.update(oauth_base_params)
        else:
            params = oauth_base_params

        if not token:
            token = self._access_token
        request = oauth.Request(method=http_method, url=url, parameters=params)
        request.sign_request(self._signature_method, self._Consumer, token)
        return request
Example #54
0
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())
Example #55
0
    def __init__(self,
                 application_name,
                 consumer_key,
                 consumer_secret,
                 token_key=None,
                 token_secret=None):
        self.server = 'api-public.netflix.com'
        self.connection = httplib.HTTPConnection(self.server, '80')

        self.catalog = NetflixCatalog(self)

        self.params = {
            'oauth_version': "1.0",
            'oauth_nonce': oauth.generate_nonce(),
            'oauth_timestamp': int(time.time()),
            'output': 'json',
            'application_name': application_name,
        }

        self.signature_method = oauth.SignatureMethod_HMAC_SHA1()

        self.consumer = oauth.Consumer(key=consumer_key,
                                       secret=consumer_secret)
        self.params['oauth_consumer_key'] = self.consumer.key

        if token_key and token_secret:
            self.token = oauth.Token(key=token_key, secret=token_secret)
            self.params['oauth_token'] = self.token.key

            self.user = NetflixUser()
        else:
            self.user = None
Example #56
0
def yahoo_get_resource(url, oauth_token, oauth_token_secret, extras=None):

    base_url = 'http://fantasysports.yahooapis.com/fantasy/v2/'

    params = {
            'format': 'json', 
            'oauth_version': "1.0",
            'oauth_nonce': oauth.generate_nonce(),
            'oauth_timestamp': int(time.time()),
    }

    if extras:
        params = dict(params.items() + extras.items())

    token = oauth.Token(key=oauth_token, secret=oauth_token_secret)
    consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret)

    params['oauth_token'] = token.key
    params['oauth_consumer_key'] = consumer.key

    signature_method = oauth.SignatureMethod_HMAC_SHA1()

    oauth_request = oauth.Request.from_consumer_and_token(consumer, token=token, http_method='GET', http_url=base_url+url, parameters=params)
    oauth_request.sign_request(signature_method, consumer, token)
    #print 'REQUEST'
    url = oauth_request.to_url()
    #print url
    resp, content = httplib2.Http.request(oauth.Client(consumer), url, 'GET')
    #print 'GOT'
    #print resp
    return resp, json.loads(content)