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


Python Reddit.get_authorize_url方法代码示例

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


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

示例1: make_config

# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_authorize_url [as 别名]
def make_config(filename):
    """
    Make a new config file.

    """
    here = os.path.dirname(os.path.abspath(__file__))
    template_file = os.path.join(here, CONFIG_TEMPLATE)

    with open(template_file, 'r') as f:
        config = json.load(f)

    print('Generating a new config, press [Enter] to accept default value.')
    _ask_config(config)

    bot_class = get_bot_class(config['bot_class'])

    r = Reddit('praw/oauth_access_info_setup 1.0')
    r.set_oauth_app_info(**config['oauth_info'])

    url = r.get_authorize_url('uniqueKey', bot_class.get_scope(), True)
    print('Go to this url: =====\n\n{}\n\n====='.format(url))
    code = input('and enter the authorization code: ')
    assert code, "No authorization code supplied."
    access_info = r.get_access_information(code)
    access_info.pop('scope', None)
    config['access_info'] = access_info

    with open(filename, 'w') as f:
        json.dump(config, f, indent=2)

    print('Wrote config {!r}!'.format(filename))
    return config
开发者ID:reddit-bots,项目名称:reddit-bot,代码行数:34,代码来源:main.py

示例2: login

# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_authorize_url [as 别名]
def login():
    next = request.args.get('next')
    from uuid import uuid1
    state = str(uuid1())
    session['oauth_state'] = state
    session['last_path'] = next
    r = Reddit(app.config['REDDIT_USER_AGENT'], handler=handler)
    r.set_oauth_app_info(app.config['REDDIT_CLIENT_ID'], app.config['REDDIT_CLIENT_SECRET'], app.config['REDDIT_REDIRECT_URI'])
    authorize_url = r.get_authorize_url(state,refreshable=True)
    return redirect(authorize_url)
开发者ID:brantonb,项目名称:cbbpoll,代码行数:12,代码来源:views.py

示例3: OAuth2RedditTest

# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_authorize_url [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

示例4: OAuth2RedditTest

# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_authorize_url [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: OAuth2RedditTest

# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_authorize_url [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

示例6: SubRedditStats

# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_authorize_url [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.get_authorize_url方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。