本文整理汇总了Python中praw.Reddit.set_oauth_app_info方法的典型用法代码示例。如果您正苦于以下问题:Python Reddit.set_oauth_app_info方法的具体用法?Python Reddit.set_oauth_app_info怎么用?Python Reddit.set_oauth_app_info使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类praw.Reddit
的用法示例。
在下文中一共展示了Reddit.set_oauth_app_info方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: make_config
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import set_oauth_app_info [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
示例2: authorized
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import set_oauth_app_info [as 别名]
def authorized():
reddit_state = request.args.get('state', '')
reddit_code = request.args.get('code', '')
if not reddit_state or not reddit_code:
return redirect(url_for('index'))
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'])
reddit_info = r.get_access_information(reddit_code)
reddit_user = r.get_me()
next_path = session['last_path']
if reddit_state != session['oauth_state']:
flash("Invalid state given, please try again.", 'danger')
return redirect(next_path or url_for('index'))
user = user_by_nickname(reddit_user.name)
if user is None:
nickname = reddit_user.name
user = User(nickname = nickname, role = 'u',
accessToken = reddit_info['access_token'],
refreshToken = reddit_info['refresh_token'])
else:
user.accessToken = reddit_info['access_token']
user.refreshToken = reddit_info['refresh_token']
db.session.add(user)
db.session.commit()
remember_me = False
if 'remember_me' in session:
remember_me = session['remember_me']
session.pop('remember_me', None)
login_user(user, remember = remember_me)
# update_flair(user)
return redirect(next_path or url_for('index'))
示例3: login
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import set_oauth_app_info [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)
示例4: OAuth2RedditTest
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import set_oauth_app_info [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()
#.........这里部分代码省略.........
示例5: RedditBot
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import set_oauth_app_info [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:
#.........这里部分代码省略.........
示例6: OAuth2RedditTest
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import set_oauth_app_info [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):
#.........这里部分代码省略.........
示例7: get_client
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import set_oauth_app_info [as 别名]
def get_client():
r = Reddit(user_agent=user_agent, site_name=SITE_NAME)
r.set_oauth_app_info(client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI)
return r
示例8: __create_gbobstatusbot_reddit_instance
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import set_oauth_app_info [as 别名]
def __create_gbobstatusbot_reddit_instance(config_obj):
user_agent = config_obj.UserAgent()
r = Reddit(user_agent, disable_update_check=True)
r.set_oauth_app_info(config_obj.ClientID(), config_obj.ClientSecret(), "http://example.org/garbageuri")
return r
示例9: OAuth2RedditTest
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import set_oauth_app_info [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):
#.........这里部分代码省略.........
示例10: SubRedditStats
# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import set_oauth_app_info [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')
#.........这里部分代码省略.........