当前位置: 首页>>代码示例>>Python>>正文


Python Reddit.set_access_credentials方法代码示例

本文整理汇总了Python中praw.Reddit.set_access_credentials方法的典型用法代码示例。如果您正苦于以下问题:Python Reddit.set_access_credentials方法的具体用法?Python Reddit.set_access_credentials怎么用?Python Reddit.set_access_credentials使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在praw.Reddit的用法示例。


在下文中一共展示了Reddit.set_access_credentials方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: OAuth2RedditTest

# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import set_access_credentials [as 别名]
class OAuth2RedditTest(PRAWTest):
    def setUp(self):
        self.configure()
        self.r = Reddit(USER_AGENT, site_name='reddit_oauth_test',
                        disable_update_check=True)

    def test_authorize_url(self):
        self.r.set_oauth_app_info(None, None, None)
        self.assertRaises(errors.OAuthAppRequired, self.r.get_authorize_url,
                          'dummy_state')
        self.r.set_oauth_app_info(self.r.config.client_id,
                                  self.r.config.client_secret,
                                  self.r.config.redirect_uri)
        url, params = self.r.get_authorize_url('...').split('?', 1)
        self.assertTrue('api/v1/authorize/' in url)
        params = dict(x.split('=', 1) for x in params.split('&'))
        expected = {'client_id': self.r.config.client_id,
                    'duration': 'temporary',
                    'redirect_uri': ('https%3A%2F%2F127.0.0.1%3A65010%2F'
                                     'authorize_callback'),
                    'response_type': 'code', 'scope': 'identity',
                    'state': '...'}
        self.assertEqual(expected, params)

    @betamax()
    def test_get_access_information(self):
        # If this test fails, the following URL will need to be visted in order
        # to obtain a new code to pass to `get_access_information`:
        # self.r.get_authorize_url('...')
        token = self.r.get_access_information('MQALrr1di8GzcnT8szbTWhLcBUQ')
        expected = {'access_token': self.r.access_token,
                    'refresh_token': None,
                    'scope': set(('identity',))}
        self.assertEqual(expected, token)
        self.assertEqual('PyAPITestUser2', text_type(self.r.user))

    @betamax()
    def test_get_access_information_with_invalid_code(self):
        self.assertRaises(errors.OAuthInvalidGrant,
                          self.r.get_access_information, 'invalid_code')

    def test_invalid_app_access_token(self):
        self.r.clear_authentication()
        self.r.set_oauth_app_info(None, None, None)
        self.assertRaises(errors.OAuthAppRequired,
                          self.r.get_access_information, 'dummy_code')

    def test_invalid_app_authorize_url(self):
        self.r.clear_authentication()
        self.r.set_oauth_app_info(None, None, None)
        self.assertRaises(errors.OAuthAppRequired,
                          self.r.get_authorize_url, 'dummy_state')

    @betamax()
    def test_invalid_set_access_credentials(self):
        self.assertRaises(errors.OAuthInvalidToken,
                          self.r.set_access_credentials,
                          set(('identity',)), 'dummy_access_token')

    def test_oauth_scope_required(self):
        self.r.set_oauth_app_info('dummy_client', 'dummy_secret', 'dummy_url')
        self.r.set_access_credentials(set('dummy_scope',), 'dummy_token')
        self.assertRaises(errors.OAuthScopeRequired, self.r.get_me)

    @betamax()
    def test_scope_edit(self):
        self.r.refresh_access_information(self.refresh_token['edit'])
        submission = Submission.from_id(self.r, self.submission_edit_id)
        self.assertEqual(submission, submission.edit('Edited text'))

    @betamax()
    def test_scope_history(self):
        self.r.refresh_access_information(self.refresh_token['history'])
        self.assertTrue(list(self.r.get_redditor(self.un).get_upvoted()))

    @betamax()
    def test_scope_identity(self):
        self.r.refresh_access_information(self.refresh_token['identity'])
        self.assertEqual(self.un, self.r.get_me().name)

    @betamax()
    def test_scope_modconfig(self):
        self.r.refresh_access_information(self.refresh_token['modconfig'])
        self.r.get_subreddit(self.sr).set_settings('foobar')
        retval = self.r.get_subreddit(self.sr).get_stylesheet()
        self.assertTrue('images' in retval)

    @betamax()
    def test_scope_modflair(self):
        self.r.refresh_access_information(self.refresh_token['modflair'])
        self.r.get_subreddit(self.sr).set_flair(self.un, 'foobar')

    @betamax()
    def test_scope_modlog(self):
        num = 50
        self.r.refresh_access_information(self.refresh_token['modlog'])
        result = self.r.get_subreddit(self.sr).get_mod_log(limit=num)
        self.assertEqual(num, len(list(result)))

    @betamax()
#.........这里部分代码省略.........
开发者ID:andrewalexander,项目名称:praw,代码行数:103,代码来源:test_oauth2_reddit.py

示例2: RedditBot

# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import set_access_credentials [as 别名]
class RedditBot(_RedditBotBase):
    """
    Basic extendable Reddit bot.

    Provides means to loop over a list of whitelisted subreddits.

    """
    VERSION = (0, 0, 0)  # override this
    USER_AGENT = '{name} v{version} (by /u/{admin})'

    # if loop() returns this the bot will refresh its settings
    BOT_SHOULD_REFRESH = 'BOT_SHOULD_REFRESH'

    def __init__(self, config):
        """
        Initialize the bot with a dict of configuration values.

        """
        self._setup(config)
        self._login(config)

        self.subreddits = self._get_subreddits()
        self.blocked_users = self._get_blocked_users()

    def _setup(self, config):
        try:
            admins = config['admins']
            if isinstance(admins, list):
                self.admins = admins
            else:
                self.admins = list(map(str.strip, admins.split(',')))

            self.settings = DEFAULT_SETTINGS.copy()
            self.settings.update(config.get('settings', {}))
        except KeyError as e:
            import sys
            sys.stderr.write('error: missing {} in configuration'.format(e))
            sys.exit(2)

    def _login(self, config):
        logger.info('Attempting to login using OAuth2')

        for attr in ['client_id', 'client_secret', 'redirect_uri']:
            assert attr in config['oauth_info'], 'Missing `{}` in oauth_info'.format(attr)

        self.r = Reddit('OAuth Login v1.0')
        self.r.set_oauth_app_info(**config['oauth_info'])

        for attr in ['access_token', 'refresh_token']:
            assert attr in config['access_info'], 'Missing `{}` in access_info'.format(attr)
        access_info = config['access_info']
        access_info['scope'] = self.__class__.get_scope()
        self.r.set_access_credentials(**access_info)
        self.bot_name = self.r.user.name
        self.admins.append(self.bot_name)
        user_agent = self.USER_AGENT.format(
            name=self.bot_name,
            admin=self.admins[0],
            version='.'.join(map(str, self.VERSION))
        )
        logger.debug('User-Agent: {!r}'.format(user_agent))
        self.r.http.headers['User-Agent'] = user_agent
        logger.info('Logged in as {}'.format(self.bot_name))

    @classmethod
    def get_scope(cls):
        """Basic permission scope for RedditReplyBot operations."""
        return super(RedditBot, cls).get_scope() | {
            'identity',
            'subscribe',
            'mysubreddits',
        }

    def run_forever(self):
        self.bot_start()
        try:
            while True:
                self.do_loop()
                self.refresh()
        except Exception as e:
            self.bot_error(e)
            raise
        finally:
            self.bot_stop()

    def refresh(self):
        logger.info('Refreshing settings')
        self.subreddits = self._get_subreddits()
        self.blocked_users = self._get_blocked_users()

    def do_loop(self):
        for subreddit in cycle(self.subreddits):
            try:
                if self.loop(subreddit) == self.BOT_SHOULD_REFRESH:
                    break
            except Forbidden as e:
                logger.error('Forbidden in {}! Removing from whitelist.'.format(subreddit))
                self.remove_subreddits(subreddit)
                break
            except RateLimitExceeded as e:
#.........这里部分代码省略.........
开发者ID:reddit-bots,项目名称:reddit-bot,代码行数:103,代码来源:base.py

示例3: OAuth2RedditTest

# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import set_access_credentials [as 别名]
class OAuth2RedditTest(PRAWTest):
    def setUp(self):
        self.configure()
        self.r = Reddit(USER_AGENT, site_name="reddit_oauth_test", disable_update_check=True)

    def test_authorize_url(self):
        self.r.set_oauth_app_info(None, None, None)
        self.assertRaises(errors.OAuthAppRequired, self.r.get_authorize_url, "dummy_state")
        self.r.set_oauth_app_info(self.r.config.client_id, self.r.config.client_secret, self.r.config.redirect_uri)
        url, params = self.r.get_authorize_url("...").split("?", 1)
        self.assertTrue("api/v1/authorize/" in url)
        params = dict(x.split("=", 1) for x in params.split("&"))
        expected = {
            "client_id": self.r.config.client_id,
            "duration": "temporary",
            "redirect_uri": ("https%3A%2F%2F127.0.0.1%3A65010%2F" "authorize_callback"),
            "response_type": "code",
            "scope": "identity",
            "state": "...",
        }
        self.assertEqual(expected, params)

    # @betamax() is currently broken for this test
    def test_auto_refresh_token(self):
        self.r.refresh_access_information(self.refresh_token["identity"])
        old_token = self.r.access_token

        self.r.access_token += "x"  # break the token
        self.r.user.refresh()
        current_token = self.r.access_token
        self.assertNotEqual(old_token, current_token)

        self.r.user.refresh()
        self.assertEqual(current_token, self.r.access_token)

    @betamax()
    def test_get_access_information(self):
        # If this test fails, the following URL will need to be visted in order
        # to obtain a new code to pass to `get_access_information`:
        # self.r.get_authorize_url('...')
        token = self.r.get_access_information("MQALrr1di8GzcnT8szbTWhLcBUQ")
        expected = {"access_token": self.r.access_token, "refresh_token": None, "scope": set(("identity",))}
        self.assertEqual(expected, token)
        self.assertEqual("PyAPITestUser2", text_type(self.r.user))

    @betamax()
    def test_get_access_information_with_invalid_code(self):
        self.assertRaises(errors.OAuthInvalidGrant, self.r.get_access_information, "invalid_code")

    def test_invalid_app_access_token(self):
        self.r.clear_authentication()
        self.r.set_oauth_app_info(None, None, None)
        self.assertRaises(errors.OAuthAppRequired, self.r.get_access_information, "dummy_code")

    def test_invalid_app_authorize_url(self):
        self.r.clear_authentication()
        self.r.set_oauth_app_info(None, None, None)
        self.assertRaises(errors.OAuthAppRequired, self.r.get_authorize_url, "dummy_state")

    @betamax()
    def test_invalid_set_access_credentials(self):
        self.assertRaises(
            errors.OAuthInvalidToken, self.r.set_access_credentials, set(("identity",)), "dummy_access_token"
        )

    def test_oauth_scope_required(self):
        self.r.set_oauth_app_info("dummy_client", "dummy_secret", "dummy_url")
        self.r.set_access_credentials(set("dummy_scope"), "dummy_token")
        self.assertRaises(errors.OAuthScopeRequired, self.r.get_me)

    @betamax()
    def test_scope_edit(self):
        self.r.refresh_access_information(self.refresh_token["edit"])
        submission = Submission.from_id(self.r, self.submission_edit_id)
        self.assertEqual(submission, submission.edit("Edited text"))

    @betamax()
    def test_scope_history(self):
        self.r.refresh_access_information(self.refresh_token["history"])
        self.assertTrue(list(self.r.get_redditor(self.un).get_upvoted()))

    @betamax()
    def test_scope_identity(self):
        self.r.refresh_access_information(self.refresh_token["identity"])
        self.assertEqual(self.un, self.r.get_me().name)

    @betamax()
    def test_scope_modconfig(self):
        self.r.refresh_access_information(self.refresh_token["modconfig"])
        self.r.get_subreddit(self.sr).set_settings("foobar")
        retval = self.r.get_subreddit(self.sr).get_stylesheet()
        self.assertTrue("images" in retval)

    @betamax()
    def test_scope_modflair(self):
        self.r.refresh_access_information(self.refresh_token["modflair"])
        self.r.get_subreddit(self.sr).set_flair(self.un, "foobar")

    @betamax()
    def test_scope_modlog(self):
#.........这里部分代码省略.........
开发者ID:andresrestrepo,项目名称:praw,代码行数:103,代码来源:test_oauth2_reddit.py

示例4: OAuth2RedditTest

# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import set_access_credentials [as 别名]
class OAuth2RedditTest(PRAWTest):
    def setUp(self):
        self.configure()
        self.r = Reddit(USER_AGENT, site_name='reddit_oauth_test',
                        disable_update_check=True)

    def test_authorize_url(self):
        self.r.set_oauth_app_info(None, None, None)
        self.assertRaises(errors.OAuthAppRequired, self.r.get_authorize_url,
                          'dummy_state')
        self.r.set_oauth_app_info(self.r.config.client_id,
                                  self.r.config.client_secret,
                                  self.r.config.redirect_uri)
        url, params = self.r.get_authorize_url('...').split('?', 1)
        self.assertTrue('api/v1/authorize/' in url)
        params = dict(x.split('=', 1) for x in params.split('&'))
        expected = {'client_id': self.r.config.client_id,
                    'duration': 'temporary',
                    'redirect_uri': ('https%3A%2F%2F127.0.0.1%3A65010%2F'
                                     'authorize_callback'),
                    'response_type': 'code', 'scope': 'identity',
                    'state': '...'}
        self.assertEqual(expected, params)

    # @betamax() is currently broken for this test because the cassettes
    # are caching too aggressively and not performing a token refresh.
    def test_auto_refresh_token(self):
        self.r.refresh_access_information(self.refresh_token['identity'])
        old_token = self.r.access_token

        self.r.access_token += 'x'  # break the token
        self.r.user.refresh()
        current_token = self.r.access_token
        self.assertNotEqual(old_token, current_token)

        self.r.user.refresh()
        self.assertEqual(current_token, self.r.access_token)

    @betamax()
    def test_get_access_information(self):
        # If this test fails, the following URL will need to be visted in order
        # to obtain a new code to pass to `get_access_information`:
        # self.r.get_authorize_url('...')
        token = self.r.get_access_information('MQALrr1di8GzcnT8szbTWhLcBUQ')
        expected = {'access_token': self.r.access_token,
                    'refresh_token': None,
                    'scope': set(('identity',))}
        self.assertEqual(expected, token)
        self.assertEqual('PyAPITestUser2', text_type(self.r.user))

    @betamax()
    def test_get_access_information_with_invalid_code(self):
        self.assertRaises(errors.OAuthInvalidGrant,
                          self.r.get_access_information, 'invalid_code')

    def test_invalid_app_access_token(self):
        self.r.clear_authentication()
        self.r.set_oauth_app_info(None, None, None)
        self.assertRaises(errors.OAuthAppRequired,
                          self.r.get_access_information, 'dummy_code')

    def test_invalid_app_authorize_url(self):
        self.r.clear_authentication()
        self.r.set_oauth_app_info(None, None, None)
        self.assertRaises(errors.OAuthAppRequired,
                          self.r.get_authorize_url, 'dummy_state')

    @betamax()
    def test_invalid_set_access_credentials(self):
        self.assertRaises(errors.OAuthInvalidToken,
                          self.r.set_access_credentials,
                          set(('identity',)), 'dummy_access_token')

    def test_oauth_scope_required(self):
        self.r.set_oauth_app_info('dummy_client', 'dummy_secret', 'dummy_url')
        self.r.set_access_credentials(set('dummy_scope',), 'dummy_token')
        self.assertRaises(errors.OAuthScopeRequired, self.r.get_me)

    def test_raise_client_exception(self):
        def raise_client_exception(*args):
            raise errors.ClientException(*args)

        self.assertRaises(errors.ClientException, raise_client_exception)
        self.assertRaises(errors.ClientException, raise_client_exception,
                          'test')

        ce_message = errors.ClientException('Test')
        ce_no_message = errors.ClientException()
        self.assertEqual(ce_message.message, str(ce_message))
        self.assertEqual(ce_no_message.message, str(ce_no_message))

    def test_raise_http_exception(self):
        def raise_http_exception():
            raise errors.HTTPException('fakeraw')

        self.assertRaises(errors.HTTPException, raise_http_exception)
        http_exception = errors.HTTPException('fakeraw')
        self.assertEqual(http_exception.message, str(http_exception))

    def test_raise_oauth_exception(self):
#.........这里部分代码省略.........
开发者ID:JamieMagee,项目名称:praw,代码行数:103,代码来源:test_oauth2_reddit.py

示例5: SubRedditStats

# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import set_access_credentials [as 别名]
class SubRedditStats(object):

    """Contain all the functionality of the subreddit_stats command."""

    post_prefix = tt('Subreddit Stats:')
    post_header = tt('---\n###{0}\n')
    post_footer = tt('>Generated with [BBoe](/u/bboe)\'s [Subreddit Stats]'
                     '(https://github.com/praw-dev/prawtools)  \n{0}'
                     'SRS Marker: {1}')
    re_marker = re.compile(r'SRS Marker: (\d+)')

    @staticmethod
    def _previous_max(submission):
        try:
            val = SubRedditStats.re_marker.findall(submission.selftext)[-1]
            return float(val)
        except (IndexError, TypeError):
            print('End marker not found in previous submission. Aborting')
            sys.exit(1)

    @staticmethod
    def _permalink(permalink):
        tokens = permalink.split('/')
        if tokens[8] == '':  # submission
            return tt('/comments/{0}/_/').format(tokens[6])
        else:  # comment
            return tt('/comments/{0}/_/{1}?context=1').format(tokens[6],
                                                              tokens[8])

    @staticmethod
    def _pts(points):
        return '1 pt' if points == 1 else '{0} pts'.format(points)

    @staticmethod
    def _user(user):
        if user is None:
            return '_deleted_'
        elif isinstance(user, Redditor):
            user = str(user)
        return tt('[{0}](/user/{1})').format(user.replace('_', r'\_'), user)

    @staticmethod
    def _submit(func, *args, **kwargs):
        def sleep(sleep_time):
            print('\tSleeping for {0} seconds'.format(sleep_time))
            time.sleep(sleep_time)

        while True:
            try:
                return func(*args, **kwargs)
            except RateLimitExceeded as error:
                sleep(error.sleep_time)
            except ExceptionList as exception_list:
                for error in exception_list.errors:
                    if isinstance(error, RateLimitExceeded):
                        sleep(error.sleep_time)
                        break
                else:
                    raise

    def __init__(self, subreddit, site, verbosity, distinguished):
        """Initialize the SubRedditStats instance with config options."""
        self.reddit = Reddit(str(self), site, disable_update_check=True)
        self.subreddit = self.reddit.get_subreddit(subreddit)
        self.verbosity = verbosity
        self.distinguished = distinguished
        self.submissions = []
        self.comments = []
        self.submitters = defaultdict(list)
        self.commenters = defaultdict(list)
        self.min_date = 0
        self.max_date = time.time() - DAYS_IN_SECONDS * 3
        self.prev_srs = None

    def login(self, id, secret):
        """Login and provide debugging output if so wanted."""
        if self.verbosity > 0:
            print('Logging in using OAuth...')
        if self.verbosity > 1:
            print('Client ID: ' + id)
        self.reddit.set_oauth_app_info(client_id=id, client_secret=secret,
                                       redirect_uri='http://127.0.0.1:65010/authorize_callback')
        url = self.reddit.get_authorize_url('srs', ['identity', 'read', 'submit'], True)
        webbrowser.open(url)
        sys.stdout.write('Code: ')
        sys.stdout.flush()
        code = sys.stdin.readline().strip()
        access_info = self.reddit.get_access_information(code)
        self.reddit.set_access_credentials(**access_info)
        print("Logged in as " + self.reddit.get_me().name + '.')

    def msg(self, msg, level, overwrite=False):
        """Output a messaage to the screen if the verbosity is sufficient."""
        if self.verbosity and self.verbosity >= level:
            sys.stdout.write(msg)
            if overwrite:
                sys.stdout.write('\r')
                sys.stdout.flush()
            else:
                sys.stdout.write('\n')
#.........这里部分代码省略.........
开发者ID:wtchen,项目名称:prawtools,代码行数:103,代码来源:stats.py


注:本文中的praw.Reddit.set_access_credentials方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。