Python requests_oauthlib.OAuth1Session() Examples

The following are 30 code examples of requests_oauthlib.OAuth1Session(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module requests_oauthlib , or try the search function .
Example #1
Source File: test_pymkmapi.py    From pymkm with MIT License 6 votes vote down vote up
def test_find_user_articles(self):

        mock_oauth = Mock(spec=OAuth1Session)
        mock_oauth.get = MagicMock(
            return_value=self.MockResponse(
                TestCommon.cardmarket_find_user_articles_result, 200, "testing ok"
            )
        )
        user_id = 1
        game_id = 1

        result = self.api.find_user_articles(user_id, game_id, 0, mock_oauth)
        self.assertEqual(result[0]["comments"], "x")

        mock_oauth.get = MagicMock(
            return_value=self.MockResponse(
                TestCommon.cardmarket_find_user_articles_result, 206, "partial content"
            )
        )

        result = self.api.find_user_articles(user_id, game_id, 0, mock_oauth)
        self.assertEqual(result[0]["comments"], "x") 
Example #2
Source File: person.py    From impactstory-tng with MIT License 6 votes vote down vote up
def update_twitter_profile_data(self):
        if not self.twitter or not self.twitter_creds:
            print u"Can't update twitter, doesn't have twitter username or twitter_creds"
            return None

        oauth = OAuth1Session(
            os.getenv('TWITTER_CONSUMER_KEY'),
            client_secret=os.getenv('TWITTER_CONSUMER_SECRET')
        )
        url = "https://api.twitter.com/1.1/users/lookup.json?screen_name={}".format(self.twitter)
        r = oauth.get(url)
        response_data = r.json()
        first_profile = response_data[0]

        keys_to_update = ["profile_image_url", "profile_image_url_https"]
        for k in keys_to_update:
            self.twitter_creds[k] = first_profile[k]

        print u"Updated twitter creds for @{}".format(self.twitter)

        return self.twitter_creds 
Example #3
Source File: Bot.py    From MyTwitterBot with MIT License 6 votes vote down vote up
def get_trends(self, local):
        """
        Method to get the trending hashtags.

        :type local: str
        :rtype: list of str
        """
        session_string = "https://api.twitter.com/1.1/trends/place.json?id="
        local_id = self.get_local_identifier()[local]
        session_string += local_id
        session = OAuth1Session(ConsumerKey,
                                ConsumerSecret,
                                AccessToken,
                                AccessTokenSecret)
        response = session.get(session_string)
        if response.__dict__['status_code'] == 200:
            local_trends = json.loads(response.text)[0]["trends"]
            hashtags = [trend["name"]
                        for trend in local_trends if trend["name"][0] == '#']
        else:
            hashtags = []
        return hashtags 
Example #4
Source File: depy.py    From depy with Apache License 2.0 6 votes vote down vote up
def get_auth_token(self):
        """
        Retrieves an auth_session_token using DEP server token data prepared as an
        OAuth1Session() instance earlier on.
        """
        # Retrieve session auth token
        get_session = self.dep_prep('session', 'get', authsession=self.oauth)
        response = self.oauth.send(get_session)

        # Extract the auth session token from the JSON reply
        token = response.json()['auth_session_token']

        # The token happens to contain the UNIX timestamp of when it was generated
        # so we save it for later reference.
        timestamp = token[:10]

        # Roll a human-readable timestamp as well.
        ts_readable = datetime.datetime.fromtimestamp(
                      int(timestamp)).strftime(
                      '%Y-%m-%d %H:%M:%S')

        print "Token generated at %s" % ts_readable

        return token, timestamp 
Example #5
Source File: pymkmapi.py    From pymkm with MIT License 6 votes vote down vote up
def __setup_service(self, url, provided_oauth):
        oauth = None
        if provided_oauth is not None:
            return provided_oauth
        else:
            if self.config is not None:
                oauth = OAuth1Session(
                    self.config["app_token"],
                    client_secret=self.config["app_secret"],
                    resource_owner_key=self.config["access_token"],
                    resource_owner_secret=self.config["access_token_secret"],
                    realm=url,
                )

                if oauth is None:
                    raise ConnectionError("Failed to establish OAuth session.")
                else:
                    return oauth 
Example #6
Source File: accounts.py    From pyetrade with GNU General Public License v3.0 6 votes vote down vote up
def __init__(
        self, client_key, client_secret, resource_owner_key, resource_owner_secret
    ):
        """__init_()
           """
        self.client_key = client_key
        self.client_secret = client_secret
        self.resource_owner_key = resource_owner_key
        self.resource_owner_secret = resource_owner_secret
        self.base_url_prod = r"https://api.etrade.com/v1/accounts"
        self.base_url_dev = r"https://apisb.etrade.com/v1/accounts"
        self.session = OAuth1Session(
            self.client_key,
            self.client_secret,
            self.resource_owner_key,
            self.resource_owner_secret,
            signature_type="AUTH_HEADER",
        ) 
Example #7
Source File: test_pymkmapi.py    From pymkm with MIT License 6 votes vote down vote up
def test_get_articles(self):
        mock_oauth = Mock(spec=OAuth1Session)
        mock_oauth.get = MagicMock(
            return_value=self.MockResponse(
                TestCommon.cardmarket_find_user_articles_result, 200, "testing ok"
            )
        )
        product_id = 1

        result = self.api.get_articles(product_id, 0, mock_oauth)
        self.assertEqual(result[0]["comments"], "x")

        mock_oauth.get = MagicMock(
            return_value=self.MockResponse(
                TestCommon.cardmarket_find_user_articles_result, 206, "partial content"
            )
        )
        product_id = 1

        result = self.api.get_articles(product_id, 0, mock_oauth)
        self.assertEqual(result[0]["comments"], "x") 
Example #8
Source File: oauth.py    From API-Manager with GNU Affero General Public License v3.0 6 votes vote down vote up
def set_access_token(self, authorization_url):
        session = OAuth1Session(
            settings.OAUTH_CONSUMER_KEY,
            settings.OAUTH_CONSUMER_SECRET,
            resource_owner_key=self.token,
            resource_owner_secret=self.secret,
        )
        session.parse_authorization_response(authorization_url)
        url = settings.API_HOST + settings.OAUTH_ACCESS_TOKEN_PATH
        try:
            response = session.fetch_access_token(url)
        except (TokenRequestDenied, ConnectionError) as err:
            raise AuthenticatorError(err)
        else:
            self.token = response.get('oauth_token')
            self.secret = response.get('oauth_token_secret')
        LOGGER.log(logging.INFO, 'Updated token {}, secret {}'.format(
            self.token, self.secret)) 
Example #9
Source File: oauth.py    From API-Manager with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_authorization_url(self, callback_uri):
        session = OAuth1Session(
            settings.OAUTH_CONSUMER_KEY,
            client_secret=settings.OAUTH_CONSUMER_SECRET,
            callback_uri=callback_uri,
        )
        try:
            url = settings.API_HOST + settings.OAUTH_TOKEN_PATH
            response = session.fetch_request_token(url, verify=settings.VERIFY)
        except (ValueError, TokenRequestDenied, ConnectionError) as err:
            raise AuthenticatorError(err)
        else:
            self.token = response.get('oauth_token')
            self.secret = response.get('oauth_token_secret')
        url = settings.API_HOST + settings.OAUTH_AUTHORIZATION_PATH
        authorization_url = session.authorization_url(url)
        LOGGER.log(logging.INFO, 'Initial token {}, secret {}'.format(
            self.token, self.secret))
        return authorization_url 
Example #10
Source File: twitter.py    From IkaLog with Apache License 2.0 6 votes vote down vote up
def check_import(self):
        try:
            from requests_oauthlib import OAuth1Session
        except:
            print("モジュール requests_oauthlib がロードできませんでした。 Twitter 投稿ができません。")
            print("インストールするには以下のコマンドを利用してください。\n    pip install requests_oauthlib\n")

    ##
    # Constructor
    # @param self              The Object Pointer.
    # @param consumer_key      Consumer key of the application.
    # @param consumer_secret   Comsumer secret.
    # @param auth_token        Authentication token of the user account.
    # @param auth_token_secret Authentication token secret.
    # @param attach_image      If true, post screenshots.
    # @param footer            Footer text.
    # @param tweet_my_score    If true, post score.
    # @param tweet_kd          If true, post killed/death.
    # @param tweet_udemae      If true, post udemae(rank).
    # @param use_reply         If true, post the tweet as a reply to @_ikalog_
    # 
Example #11
Source File: twitter.py    From IkaLog with Apache License 2.0 6 votes vote down vote up
def tweet(self, s, media=None):
        if media is None:
            params = {"status": s}
        else:
            params = {"status": s, "media_ids": [media]}

        from requests_oauthlib import OAuth1Session

        CK = self._preset_ck if self.consumer_key_type == 'ikalog' else self.consumer_key
        CS = self._preset_cs if self.consumer_key_type == 'ikalog' else self.consumer_secret

        twitter = OAuth1Session(
            CK, CS, self.access_token, self.access_token_secret)
        return twitter.post(self.url, params=params, verify=self._get_cert_path())

    ##
    # Post a screenshot to Twitter
    # @param  self    The object pointer.
    # @param  img     The image to be posted.
    # @return media   The media ID
    # 
Example #12
Source File: auth.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
def get_access_token(self, verifier=None):
        """
        After user has authorized the request token, get access token
        with user supplied verifier.
        """
        try:
            url = self._get_oauth_url('access_token')
            self.oauth = OAuth1Session(self.consumer_key,
                                       client_secret=self.consumer_secret,
                                       resource_owner_key=self.request_token['oauth_token'],
                                       resource_owner_secret=self.request_token['oauth_token_secret'],
                                       verifier=verifier, callback_uri=self.callback)
            resp = self.oauth.fetch_access_token(url)
            self.access_token = resp['oauth_token']
            self.access_token_secret = resp['oauth_token_secret']
            return self.access_token, self.access_token_secret
        except Exception as e:
            raise TweepError(e) 
Example #13
Source File: auth.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
def __init__(self, consumer_key, consumer_secret, callback=None):
        if type(consumer_key) == six.text_type:
            consumer_key = consumer_key.encode('ascii')

        if type(consumer_secret) == six.text_type:
            consumer_secret = consumer_secret.encode('ascii')

        self.consumer_key = consumer_key
        self.consumer_secret = consumer_secret
        self.access_token = None
        self.access_token_secret = None
        self.callback = callback
        self.username = None
        self.oauth = OAuth1Session(consumer_key,
                                   client_secret=consumer_secret,
                                   callback_uri=self.callback) 
Example #14
Source File: api.py    From django-quickbooks-online with MIT License 6 votes vote down vote up
def __init__(self, owner_or_token):
        if isinstance(owner_or_token, User):
            self.token = QuickbooksToken.objects.filter(user=owner_or_token).first()
        elif isinstance(owner_or_token, QuickbooksToken):
            self.token = owner_or_token
        else:
            raise ValueError("API must be initialized with either a QuickbooksToken or User")

        session = OAuth1Session(client_key=settings.QUICKBOOKS['CONSUMER_KEY'],
                                client_secret=settings.QUICKBOOKS['CONSUMER_SECRET'],
                                resource_owner_key=self.token.access_token,
                                resource_owner_secret=self.token.access_token_secret)

        session.headers.update({'content-type': 'application/json', 'accept': 'application/json'})
        self.session = session
        self.realm_id = self.token.realm_id
        self.data_source = self.token.data_source
        self.url_base = {'QBD': QUICKBOOKS_DESKTOP_V3_URL_BASE,
                         'QBO': QUICKBOOKS_ONLINE_V3_URL_BASE}[self.token.data_source] 
Example #15
Source File: view.py    From osm-wikidata with GNU General Public License v3.0 6 votes vote down vote up
def start_oauth():
    next_page = request.args.get('next')
    if next_page:
        session['next'] = next_page

    client_key = app.config['CLIENT_KEY']
    client_secret = app.config['CLIENT_SECRET']

    request_token_url = 'https://www.openstreetmap.org/oauth/request_token'

    callback = url_for('oauth_callback', _external=True)

    oauth = OAuth1Session(client_key,
                          client_secret=client_secret,
                          callback_uri=callback)
    fetch_response = oauth.fetch_request_token(request_token_url)

    session['owner_key'] = fetch_response.get('oauth_token')
    session['owner_secret'] = fetch_response.get('oauth_token_secret')

    base_authorization_url = 'https://www.openstreetmap.org/oauth/authorize'
    authorization_url = oauth.authorization_url(base_authorization_url,
                                                oauth_consumer_key=client_key)
    return redirect(authorization_url) 
Example #16
Source File: figshare.py    From figshare with MIT License 5 votes vote down vote up
def __init__(self, consumer_key, consumer_secret, access_token,
                 access_token_secret):
        """
        Connects to the figshare API.
        """
        self.client = OAuth1Session(
            consumer_key, consumer_secret, access_token, access_token_secret)
        self.endpoint = 'http://api.figshare.com/v1/my_data' 
Example #17
Source File: test_pymkmapi.py    From pymkm with MIT License 5 votes vote down vote up
def test_delete_stock(self):
        mock_oauth = Mock(spec=OAuth1Session)
        mock_oauth.delete = MagicMock(
            return_value=self.MockResponse(
                TestCommon.get_stock_result, 200, "testing ok"
            )
        )

        result = self.api.delete_stock(TestCommon.get_stock_result, mock_oauth)
        self.assertEqual(len(result), 3) 
Example #18
Source File: test_pymkmapi.py    From pymkm with MIT License 5 votes vote down vote up
def test_set_stock(self):
        mock_oauth = Mock(spec=OAuth1Session)
        mock_oauth.put = MagicMock(
            return_value=self.MockResponse(
                TestCommon.get_stock_result, 200, "testing ok"
            )
        )

        result = self.api.set_stock(TestCommon.get_stock_result, mock_oauth)
        self.assertEqual(len(result), 3) 
Example #19
Source File: test_pymkmapi.py    From pymkm with MIT License 5 votes vote down vote up
def test_set_display_language(self):
        mock_oauth = Mock(spec=OAuth1Session)
        mock_oauth.put = MagicMock(
            return_value=self.MockResponse(
                TestCommon.fake_account_data, 200, "testing ok"
            )
        )
        display_language = 1

        result = self.api.set_display_language(display_language, mock_oauth)
        self.assertEqual(
            result["account"]["idDisplayLanguage"], str(display_language).lower()
        ) 
Example #20
Source File: test_pymkmapi.py    From pymkm with MIT License 5 votes vote down vote up
def test_set_vacation_status(self):
        mock_oauth = Mock(spec=OAuth1Session)
        mock_oauth.put = MagicMock(
            return_value=self.MockResponse(
                TestCommon.fake_account_data, 200, "testing ok"
            )
        )
        vacation_status = True

        result = self.api.set_vacation_status(vacation_status, mock_oauth)
        self.assertEqual(result["message"], "Successfully set the account on vacation.")
        self.assertEqual(result["account"]["onVacation"], vacation_status) 
Example #21
Source File: test_pymkmapi.py    From pymkm with MIT License 5 votes vote down vote up
def test_no_results(self):
        mock_oauth = Mock(spec=OAuth1Session)
        mock_oauth.get = MagicMock(
            return_value=self.MockResponse(None, 204, "testing ok")
        )
        with self.assertLogs(level="ERROR") as cm:
            empty_response = self.api.get_expansions(1, mock_oauth)
            log_record_message = cm.records[0].message
            self.assertEqual(log_record_message, "No results found.") 
Example #22
Source File: test_pymkmapi.py    From pymkm with MIT License 5 votes vote down vote up
def test_get_account(self):
        mock_oauth = Mock(spec=OAuth1Session)

        mock_oauth.get = MagicMock(
            return_value=self.MockResponse("test", 200, "testing ok")
        )
        self.assertEqual(self.api.get_account(mock_oauth), "test")
        mock_oauth.get.assert_called()

        mock_oauth.get = MagicMock(
            return_value=self.MockResponse("", 401, "Unauthorized")
        )
        with self.assertLogs(level="ERROR") as cm:
            self.api.get_account(mock_oauth)
            self.assertGreater(len(cm.records), 0) 
Example #23
Source File: test_pymkmapi.py    From pymkm with MIT License 5 votes vote down vote up
def test_get_stock(self):
        mock_oauth = Mock(spec=OAuth1Session)
        mock_oauth.get = MagicMock(
            return_value=self.MockResponse(
                TestCommon.cardmarket_get_stock_result, 200, "testing ok"
            )
        )
        stock = self.api.get_stock(None, mock_oauth)
        self.assertEqual(stock[0]["comments"], "x") 
Example #24
Source File: test_pymkmapi.py    From pymkm with MIT License 5 votes vote down vote up
def test_get_orders(self):
        mock_oauth = Mock(spec=OAuth1Session)
        mock_oauth.get = MagicMock(
            return_value=self.MockResponse(TestCommon.get_orders, 200, "testing ok")
        )
        orders = self.api.get_orders("buyer", "received", 1, mock_oauth)
        self.assertEqual(orders[0]["idOrder"], 22935635) 
Example #25
Source File: test_pymkmapi.py    From pymkm with MIT License 5 votes vote down vote up
def test_get_expansions(self):
        test_json = json.loads('{"test": "test"}')
        mock_oauth = Mock(spec=OAuth1Session)
        mock_oauth.get = MagicMock(
            return_value=self.MockResponse(test_json, 200, "testing ok")
        )
        game_id = 1
        self.assertEqual(self.api.get_expansions(game_id, mock_oauth), test_json) 
Example #26
Source File: test_pymkmapi.py    From pymkm with MIT License 5 votes vote down vote up
def test_get_wantslists(self):
        mock_oauth = Mock(spec=OAuth1Session)
        mock_oauth.get = MagicMock(
            return_value=self.MockResponse(
                TestCommon.cardmarket_get_wantslists, 200, "testing ok"
            )
        )
        result = self.api.get_wantslists(mock_oauth)
        self.assertEqual(result, TestCommon.get_wantslists) 
Example #27
Source File: test_pymkmapi.py    From pymkm with MIT License 5 votes vote down vote up
def test_get_cards_in_expansion(self):
        test_json = json.loads('{"test": "test"}')
        mock_oauth = Mock(spec=OAuth1Session)
        mock_oauth.get = MagicMock(
            return_value=self.MockResponse(test_json, 200, "testing ok")
        )
        expansion_id = 1
        self.assertEqual(
            self.api.get_cards_in_expansion(expansion_id, mock_oauth), test_json
        ) 
Example #28
Source File: test_pymkmapi.py    From pymkm with MIT License 5 votes vote down vote up
def test_get_product(self):
        test_json = json.loads('{"test": "test"}')
        mock_oauth = Mock(spec=OAuth1Session)
        mock_oauth.get = MagicMock(
            return_value=self.MockResponse(test_json, 200, "testing ok")
        )
        product_id = 1
        self.assertEqual(self.api.get_product(product_id, mock_oauth), test_json) 
Example #29
Source File: test_pymkmapi.py    From pymkm with MIT License 5 votes vote down vote up
def test_get_metaproduct(self):
        test_json = json.loads('{"test": "test"}')
        mock_oauth = Mock(spec=OAuth1Session)
        mock_oauth.get = MagicMock(
            return_value=self.MockResponse(test_json, 200, "testing ok")
        )
        metaproduct_id = 1
        self.assertEqual(
            self.api.get_metaproduct(metaproduct_id, mock_oauth), test_json
        ) 
Example #30
Source File: test_pymkmapi.py    From pymkm with MIT License 5 votes vote down vote up
def test_find_product(self):
        mock_oauth = Mock(spec=OAuth1Session)
        mock_oauth.get = MagicMock(
            return_value=self.MockResponse(
                TestCommon.fake_product_response, 200, "testing ok"
            )
        )
        search_string = "test"
        result = self.api.find_product(search_string, mock_oauth)
        self.assertEqual(result, TestCommon.fake_product_response)