Ejemplo n.º 1
0
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 = 'https://{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
Ejemplo n.º 2
0
def get_teams_from_series_id(league_id):

    params = {
        'oauth_version': "1.0",
        'oauth_nonce': oauth.generate_nonce(),
        'oauth_timestamp': str(int(time.time())),
        'file': 'leaguedetails',
        'version': 1.4,
        'leagueLevelUnitID': league_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)
    teams = []
    #for child in root.findall('CurrentMatchRound'):
    round = root.find('CurrentMatchRound').text

    for child in root.findall('Team'):
        id   = child.find('TeamID').text
        name = child.find('TeamName').text
        position = child.find('Position').text
        points = child.find('Points').text
        goalsFor = child.find('GoalsFor').text
        goalsAga = child.find('GoalsAgainst').text
        matches = child.find('Matches').text
        won = child.find('Won').text
        draws = child.find('Draws').text
        lost = child.find('Lost').text
        teams.append({"team_name":name,"team_id":int(id), "team_points":int(points),"team_position":int(position), 
                      "team_gFor":int(goalsFor), "team_gAga":int(goalsAga), "team_matches":int(matches),
                      "team_won":int(won),"team_draws":int(draws),"team_lost":int(lost),"round":int(round)})

    return teams
def post_tweet(tweet_text, pkg_id):
    '''
    Attempts to post the tweet. Returns a boolean success variable and a
    message describing the reason for the failure/success in posting the tweet.
    :param tweet_text: The text to post. This is passed in rather than
    generated inside the method to allow users to change the tweet before
    posting (if enabled).
    :param pkg_id: The package ID (for caching).
    :return: boolean, str
    '''
    if config_helpers.twitter_is_debug():
        logger.debug('Not posted (debug): ' + tweet_text)
        return False, 'debug'

    # if not enough time has passed since the last tweet
    if not cache_helpers.expired(pkg_id):
        logger.debug('Not posted (insufficient rest period): ' + tweet_text)
        return False, 'insufficient rest period'

    # if we can't authenticate
    if not twitter_authenticate():
        logger.debug('Not posted (not authenticated): ' + tweet_text)
        return False, 'not authenticated'

    # try to actually post
    client = twitter_client()
    url = 'https://api.twitter.com/1.1/statuses/update.json'
    params = {
        'status': tweet_text
        }
    request = oauth2.Request(method = 'POST', url = url, parameters = params)
    postdata = request.to_postdata()
    response, content = client.request(url, 'POST', postdata)
    if response.status == 200:
        cache_helpers.cache(pkg_id)
        logger.debug('Posted successfully: ' + tweet_text)
    else:
        logger.debug('Not posted (tweet unsuccessful): ' + tweet_text)
    return response.status == 200, '{0} {1}'.format(response.status,
                                                    response.reason)
Ejemplo n.º 4
0
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())
Ejemplo n.º 5
0
def sign_request(slumber,
                 extra=None,
                 headers=None,
                 method=None,
                 params=None,
                 url=None,
                 **kwargs):
    args = {
        'oauth_consumer_key': extra['key'],
        'oauth_nonce': oauth.generate_nonce(),
        'oauth_signature_method': 'HMAC-SHA1',
        'oauth_timestamp': int(time.time()),
        'oauth_version': '1.0'
    }
    # Update the signed params with the query string params.
    if params:
        args.update(params)

    req = oauth.Request(method=method, url=url, parameters=args)
    consumer = oauth.Consumer(extra['key'], extra['secret'])
    req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, None)
    headers['Authorization'] = req.to_header()['Authorization']
Ejemplo n.º 6
0
    def _media_update(self, url, file_, params=None):
        params = params or {}
        oauth_params = {
            'oauth_timestamp': int(time.time()),
        }

        #create a fake request with your upload url and parameters
        faux_req = oauth.Request(method='POST',
                                 url=url,
                                 parameters=oauth_params)

        #sign the fake request.
        signature_method = oauth.SignatureMethod_HMAC_SHA1()

        class dotdict(dict):
            """
            This is a helper func. because python-oauth2 wants a
            dict in dot notation.
            """
            def __getattr__(self, attr):
                return self.get(attr, None)

            __setattr__ = dict.__setitem__
            __delattr__ = dict.__delitem__

        consumer = {'key': self.app_key, 'secret': self.app_secret}
        token = {'key': self.oauth_token, 'secret': self.oauth_secret}

        faux_req.sign_request(signature_method, dotdict(consumer),
                              dotdict(token))

        #create a dict out of the fake request signed params
        self.headers.update(faux_req.to_header())

        req = requests.post(url,
                            data=params,
                            files=file_,
                            headers=self.headers)
        return req.content
Ejemplo n.º 7
0
    def search(self, query, count):

        for i in range(1):
            url = self.url1
            self.params["q"] = query
            self.params["count"] = count
            req = oauth2.Request(method="GET", url=url, parameters=self.params)
            signature_method = oauth2.SignatureMethod_HMAC_SHA1()
            req.sign_request(signature_method, self.consumer, self.token)
            headers = req.to_header()
            url = req.to_url()
            try:
                response = urllib2.Request(url)

                data = json.load(urllib2.urlopen(response))
                if data:
                    return data
                else:
                    return False
            except urllib2.HTTPError:
                print "Http error" + str(urllib2.HTTPError.code)
                return False
Ejemplo n.º 8
0
def search(target):
    url_params = {"q": target, "result_type": "recent"}
    url = "https://{0}{1}?".format("api.twitter.com",
                                   "/1.1/search/tweets.json")
    consumer = oauth2.Consumer(TWITTER_CONSUMER_KEY, TWITTER_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": TWITTER_TOKEN,
        "oauth_consumer_key": TWITTER_CONSUMER_KEY
    })
    token = oauth2.Token(TWITTER_TOKEN, TWITTER_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)
    except Exception, e:
        return
Ejemplo n.º 9
0
    def request_token(self):
        # parameters
        params = {
            'oauth_signature_method': "HMAC-SHA1",
            'oauth_version': "1.0",
            'oauth_callback': "oob",
            'oauth_timestamp': str(int(time.time())),
            'oauth_nonce': oauth2.generate_nonce(),
            #             'oauth_consumer_key': keys['apikey']
            'oauth_consumer_key': flickrAuthConstants.keys['apikey']
        }

        # Create our request. Change method, etc. accordingly.
        req = oauth2.Request(method="GET",
                             url=flickrAuthConstants.request_token_url,
                             parameters=params)

        # Create the signature
        signature = oauth2.SignatureMethod_HMAC_SHA1().sign(
            req, self.consumer, None)

        # Add the Signature to the request
        req['oauth_signature'] = signature

        try:
            # Make the request to get the oauth_token and the oauth_token_secret
            # I had to directly use the httplib2 here, instead of the oauth library.
            h = httplib2.Http(".cache")
            resp, content = h.request(req.to_url(), "GET")

            # lets get contents into dictionary
            self.req_token = dict(urlparse.parse_qsl(content))

            # Create the token object with returned oauth_token and oauth_token_secret
            self.token = oauth2.Token(self.req_token['oauth_token'],
                                      self.req_token['oauth_token_secret'])
        except Exception, e:
            print e
            self.token = None
Ejemplo n.º 10
0
def yelp_request(host, path, url_params=None):
    """Query the v2 API.

    Args:
      host (str): The domain host of the API.
      path (str): The path of the API after the domain.
      url_params (dict): The parameters of the request. 
    Returns:
      dict: The JSON response from the request.
    """

    url_params = url_params or {}
    if DEBUG:
        sys.stderr.write('DEBUG: URL parameters are {0}\n'.format(url_params))
    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()

    if DEBUG:
        sys.stderr.write('DEBUG: Querying {0}...\n'.format(url))

    try:
        conn = urllib2.urlopen(signed_url, None)
    except urllib2.HTTPError, error:
        print "HTTP Error occurred: ", error.read()
        sys.exit(1)
Ejemplo n.º 11
0
def request(url_params):
    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())
        conn.close()
    except:
        response = {}
    return response
    def get_oauth_header(self, param_part):
        global oauth_info_list
        oauth_index = random.randint(0, (len(oauth_info_list) - 1))

        oauth_info = oauth_info_list[oauth_index]

        oauth_consumer = oauth.Consumer(key=oauth_info['consumer_key'],
                                        secret=oauth_info['consumer_secret'])
        oauth_token = oauth.Token(key=oauth_info['access_token_key'],
                                  secret=oauth_info['access_token_secret'])

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

        req_url = 'https://api.twitter.com/1.1/search/tweets.json' + '?' + param_part

        req = oauth.Request(method='GET', parameters=oauth_params, url=req_url)
        req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), oauth_consumer,
                         oauth_token)
        return req.to_header()['Authorization'].encode('utf-8')
Ejemplo n.º 13
0
    def makeCall(self):
        uniques = {
            'oauth_timestamp': str(int(time.time())),
            'oauth_nonce': oauth.generate_nonce(),
        }
        self.parameters.update(uniques)
        self.parameters.update(self.getParameters())
        req = oauth.Request(method="GET",
                            url=self.url,
                            parameters=self.parameters)
        req['oauth_signature'] = oauth.SignatureMethod_HMAC_SHA1().sign(
            req, self.consumer, self.token)
        h = httplib2.Http(".cache")

        resp, content = h.request(req.to_url(), "GET")
        self.content = content
        self.json = json.loads(content)

        if self.json["stat"] == "ok":
            return True
        else:
            return False
    def get_oauth_header(self):
        global oauth_info

        oauth_consumer = oauth.Consumer(key=oauth_info['consumer_key'],
                                        secret=oauth_info['consumer_secret'])
        oauth_token = oauth.Token(key=oauth_info['access_token_key'],
                                  secret=oauth_info['access_token_secret'])

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

        req_url = 'https://stream.twitter.com/1.1/statuses/filter.json' + '?' + urllib.urlencode(
            self.get_post_params())

        req = oauth.Request(method='POST',
                            parameters=oauth_params,
                            url=req_url)
        req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), oauth_consumer,
                         oauth_token)
        return req.to_header()['Authorization'].encode('utf-8')
Ejemplo n.º 15
0
    def test_to_postdata(self):
        realm = "http://sp.example.com/"

        params = {
            'multi': ['FOO', 'BAR'],
            'oauth_version': "1.0",
            'oauth_nonce': "4572616e48616d6d65724c61686176",
            'oauth_timestamp': "137131200",
            'oauth_consumer_key': "0685bd9184jfhq22",
            'oauth_signature_method': "HMAC-SHA1",
            'oauth_token': "ad180jjd733klru7",
            'oauth_signature': "wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D",
        }

        req = oauth.Request("GET", realm, params)

        flat = [('multi', 'FOO'), ('multi', 'BAR')]
        del params['multi']
        flat.extend(params.items())
        kf = lambda x: x[0]
        self.assertEquals(sorted(flat, key=kf),
                          sorted(parse_qsl(req.to_postdata()), key=kf))
Ejemplo n.º 16
0
    def _makeOAuthRequest(self,
                          url,
                          token=None,
                          params=None,
                          http_method="GET"):

        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
Ejemplo n.º 17
0
 def _gen_signed_url(self, url_params):
     """ Generate a signed URL to call using the token and consumer identifiers and their respective secrets.
     url_params contains extra parameters to pass to Yelp's API URL beyond the authentication stuff;
     In our case, we're using it to pass along the type of food we want and our zip code.
     returns: signed_url_string """
     self.consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET)
     logging.debug(self.consumer)
     self.request = oauth2.Request(method='GET', url = self.base_url, parameters = url_params)
     logging.debug(self.request)
     self.request.update(
         {
             'oauth_nonce': oauth2.generate_nonce(),
             'oauth_timestamp': oauth2.generate_timestamp(),
             'oauth_token': TOKEN,
             'oauth_consumer_key': CONSUMER_KEY
         }
     )
     logging.debug(self.request)
     self.token = oauth2.Token(TOKEN, TOKEN_SECRET)
     logging.debug(self.token)
     self.request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), self.consumer, self.token)
     return self.request.to_url()
Ejemplo n.º 18
0
    def setUp(self):
        url = "http://sp.example.com/"

        params = {
            'oauth_version': "1.0",
            'oauth_nonce': "4572616e48616d6d65724c61686176",
            'oauth_timestamp': int(time.time()),
            'bar': 'blerg',
            'multi': ['FOO', 'BAR'],
            'foo': 59
        }

        self.consumer = oauth.Consumer(key="consumer-key",
                                       secret="consumer-secret")
        self.token = oauth.Token(key="token-key", secret="token-secret")

        params['oauth_token'] = self.token.key
        params['oauth_consumer_key'] = self.consumer.key
        self.request = oauth.Request(method="GET", url=url, parameters=params)

        signature_method = oauth.SignatureMethod_HMAC_SHA1()
        self.request.sign_request(signature_method, self.consumer, self.token)
Ejemplo n.º 19
0
    def _request(self, 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:
            urllib.HTTPError: An error occurs from the HTTP request.
        """
        url_params = url_params or {}
        url = 'https://{0}{1}?'.format(host,
                                       urllib.parse.quote(path.encode('utf8')))

        consumer = oauth2.Consumer(self.consumer_key, self.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.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()

        with urllib.request.urlopen(signed_url, None) as httpresponse:
            response = json.loads(httpresponse.read().decode('utf-8'))

        return response
Ejemplo n.º 20
0
    def put(self,
            url,
            consumer=None,
            token=None,
            callback=False,
            verifier=None,
            data={},
            content_type=MULTIPART_CONTENT,
            **kwargs):
        """
        Send a resource to the server using PUT.
        """
        # If data has come from JSON remove unicode keys.
        data = dict([(str(k), v) for k, v in data.items()])
        url = get_absolute_url(url)
        params = _get_args(consumer, callback=callback, verifier=verifier)
        params.update(data_keys(data))

        req = oauth.Request(method='PUT', url=url, parameters=params)
        req.sign_request(self.signature_method, consumer, token)
        post_data = encode_multipart(BOUNDARY, data)

        parsed = urlparse.urlparse(url)
        query_string = urllib.urlencode(req, doseq=True)
        r = {
            'CONTENT_LENGTH': len(post_data),
            'CONTENT_TYPE': content_type,
            'PATH_INFO': urllib.unquote(parsed[2]),
            'QUERY_STRING': query_string,
            'REQUEST_METHOD': 'PUT',
            'wsgi.input': FakePayload(post_data),
            'HTTP_HOST': 'api',
            'HTTP_AUTHORIZATION': 'OAuth realm=""',
        }
        r.update(req)

        response = self.request(**r)
        return response
Ejemplo n.º 21
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(YELP_CONSUMER_KEY, YELP_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': YELP_TOKEN,
            'oauth_consumer_key': YELP_CONSUMER_KEY
        }
    )
    token = oauth2.Token(YELP_TOKEN, YELP_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
Ejemplo n.º 22
0
    def _request(self, url, url_parameters):
        """ Connection routine. It's here to prevent repetition. """

        request = oauth2.Request(method='GET',
                                 url=url,
                                 parameters=url_parameters)
        request.update({
            'oauth_nonce': oauth2.generate_nonce(),
            'oauth_timestamp': oauth2.generate_timestamp(),
            'oauth_token': self.token,
            'oauth_consumer_key': self.key
        })
        request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), self.consumer,
                             self.oauth_token)
        signed_url = request.to_url()
        connection = urllib2.urlopen(signed_url, None)

        try:
            response = json.loads(connection.read())
        finally:
            connection.close()

        return response
Ejemplo n.º 23
0
    def __oauth(self):
        """ Get oauth authorization token. """
        CONSUMER = oauth2.Consumer(self.CONSUMER_KEY, self.CONSUMER_SECRET)
        access_token = oauth2.Token(key=self.ACCESS_KEY,
                                    secret=self.ACCESS_SECRET)

        params = {
            'oauth_version': "1.0",
            'oauth_nonce': oauth2.generate_nonce(),
            'oauth_timestamp': int(time.time()),
            'oauth_token': access_token.key,
            'oauth_consumer_key': CONSUMER.key
        }

        req = oauth2.Request(method="GET",
                             url=self.url,
                             parameters=params,
                             is_form_encoded=True)

        req.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), CONSUMER,
                         access_token)

        return req.to_header()['Authorization'].encode('utf-8')
def build_request(url, method='GET', groupid = None, page = None):
    params = {                                            
        'oauth_version': "1.0",
        'oauth_nonce': oauth2.generate_nonce(),
        'oauth_timestamp': int(time.time()),
        'method': 'flickr.groups.pools.getPhotos',
        'group_id': groupid,
        'per_page': '500',
        'page': page,
        'format': 'json',
        'nojsoncallback':'1'     
    }
    consumer = oauth2.Consumer(key='cc6e0093965331473ef6d9be604b****', secret='a758040164b1****')
    token = oauth2.Token(key='72157709455713622-99a678a48136****', secret='4a13c4e35c89****')

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


    req = oauth2.Request(method=method, url=url, parameters=params)
    signature_method = oauth2.SignatureMethod_HMAC_SHA1()
    req.sign_request(signature_method, consumer, token)
    return req
Ejemplo n.º 25
0
    def test_to_url(self):
        url = "http://sp.example.com/"

        params = {
            'oauth_version': "1.0",
            'oauth_nonce': "4572616e48616d6d65724c61686176",
            'oauth_timestamp': "137131200",
            'oauth_consumer_key': "0685bd9184jfhq22",
            'oauth_signature_method': "HMAC-SHA1",
            'oauth_token': "ad180jjd733klru7",
            'oauth_signature': "wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D",
        }

        req = oauth.Request("GET", url, params)
        exp = urlparse.urlparse("%s?%s" % (url, urllib.urlencode(params)))
        res = urlparse.urlparse(req.to_url())
        self.assertEquals(exp.scheme, res.scheme)
        self.assertEquals(exp.netloc, res.netloc)
        self.assertEquals(exp.path, res.path)

        a = parse_qs(exp.query)
        b = parse_qs(res.query)
        self.assertEquals(a, b)
Ejemplo n.º 26
0
    def get_token_and_auth_url(self, callback_url=None):
        """First step is to get the token and then send the request that 
        provides the auth URL

        Returns a tuple of token and the authorisation URL.

        """

        client = oauth.Client(self.consumer) 

        params = {}
        params['oauth_callback'] = callback_url or 'oob'

        request = oauth.Request(parameters=params)
        url = REQUEST_TOKEN_URL
        resp, content = client.request(url, "POST", request.to_postdata()) 
        
        if resp.get('status') == '200':
            token = oauth.Token.from_string(content)
            data = dict(parse_qsl(content))
            return token, data['xoauth_request_auth_url'] 
        else:
            raise YQLError, (resp, content)
Ejemplo n.º 27
0
def hackpad(**kwargs):
    fname = kwargs['fname'].encode('utf-8')
    lname = kwargs['lname'].encode('utf-8')
    email = kwargs['email'].encode('utf-8')
    padId = kwargs['padId']
    friendly_email = email.encode('utf-8')
    lowered_email = friendly_email.lower()
    api_method = "https://spaceapps.hackpad.com/ep/api/embed-pad"
    # 0-leg OAUTH
    params = {
        'oauth_version': "1.0",
        'oauth_nonce': oauth2.generate_nonce(),
        'oauth_timestamp': int(time.time()),
        'email': lowered_email,
        'name': fname + ' ' + lname,
        'padId': padId
    }
    consumer = oauth2.Consumer(key="", secret="")
    params['oauth_consumer_key'] = consumer.key
    req = oauth2.Request(method='GET', url=api_method, parameters=params)
    signature_method = oauth2.SignatureMethod_HMAC_SHA1()
    req.sign_request(signature_method, consumer, None)
    return req.to_url()
Ejemplo n.º 28
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, e:
            logger.error('uri: %s' % uri)
            logger.error('body: %s' % serialized_body)
            raise
Ejemplo n.º 29
0
def auth(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': auth_token,
                        'oauth_consumer_key': consumer_key})

	token = oauth2.Token(auth_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())
Ejemplo n.º 30
0
    def post_multipart(self, url, params, files):
        """
        Generates and issues a multipart request for data files

        :param url: a string, the url you are requesting
        :param params: a dict, a key-value of all the parameters
        :param files:  a list, the list of tuples for your data

        :returns: a dict parsed from the JSON response
        """
        #combine the parameters with the generated oauth params
        params = dict(params.items() + self.generate_oauth_params().items())
        faux_req = oauth.Request(method="POST", url=url, parameters=params)
        faux_req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), self.consumer, self.token)
        params = dict(parse_qsl(faux_req.to_postdata()))

        content_type, body = self.encode_multipart_formdata(params, files)
        headers = {'Content-Type': content_type, 'Content-Length': str(len(body))}

        #Do a bytearray of the body and everything seems ok
        r = urllib2.Request(url, bytearray(body), headers)
        content = urllib2.urlopen(r).read()
        return self.json_parse(content)