本文整理匯總了Python中reddit.Reddit.get_subreddit方法的典型用法代碼示例。如果您正苦於以下問題:Python Reddit.get_subreddit方法的具體用法?Python Reddit.get_subreddit怎麽用?Python Reddit.get_subreddit使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類reddit.Reddit
的用法示例。
在下文中一共展示了Reddit.get_subreddit方法的3個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_report
# 需要導入模塊: from reddit import Reddit [as 別名]
# 或者: from reddit.Reddit import get_subreddit [as 別名]
def test_report(self):
# login as new user to report submission
oth = Reddit(USER_AGENT)
oth.login('PyApiTestUser3', '1111')
subreddit = oth.get_subreddit(self.sr)
submission = None
for submission in subreddit.get_new_by_date():
if not submission.hidden:
break
if not submission or submission.hidden:
self.fail('Could not find a non-reported submission.')
submission.report()
# check if submission was reported
for report in self.r.get_subreddit(self.sr).get_reports():
if report.id == submission.id:
break
else:
self.fail('Could not find reported submission.')
示例2: ModUtils
# 需要導入模塊: from reddit import Reddit [as 別名]
# 或者: from reddit.Reddit import get_subreddit [as 別名]
class ModUtils(object):
VERSION = '0.1.dev'
def __init__(self, subreddit, site=None, verbose=None):
self.reddit = Reddit(str(self), site)
self.sub = self.reddit.get_subreddit(subreddit)
self.verbose = verbose
self._current_flair = None
def __str__(self):
return 'BBoe\'s ModUtils %s' % self.VERSION
def add_users(self, category):
mapping = {'banned': 'ban',
'contributors': 'make_contributor',
'moderators': 'make_moderator'}
if category not in mapping:
print '%r is not a valid option for --add' % category
return
func = getattr(self.sub, mapping[category])
print 'Enter user names (any separation should suffice):'
data = sys.stdin.read().strip()
for name in re.split('[^A-Za-z_]+', data):
func(name)
print 'Added %r to %s' % (name, category)
def current_flair(self):
if self._current_flair is None:
self._current_flair = []
if self.verbose:
print 'Fetching flair list for %s' % self.sub
for flair in self.sub.flair_list():
self._current_flair.append(flair)
yield flair
else:
for item in self._current_flair:
yield item
def flair_template_sync(self, editable, limit, # pylint: disable-msg=R0912
static, sort, use_css, use_text):
# Parameter verification
if not use_text and not use_css:
raise Exception('At least one of use_text or use_css must be True')
sorts = ('alpha', 'size')
if sort not in sorts:
raise Exception('Sort must be one of: %s' % ', '.join(sorts))
# Build current flair list along with static values
if static:
counter = dict((x, limit) for x in static)
else:
counter = {}
if self.verbose:
sys.stdout.write('Retrieving current flair')
sys.stdout.flush()
for flair in self.current_flair():
if self.verbose:
sys.stdout.write('.')
sys.stdout.flush()
if use_text and use_css:
key = (flair['flair_text'], flair['flair_css_class'])
elif use_text:
key = flair['flair_text']
else:
key = flair['flair_css_class']
if key in counter:
counter[key] += 1
else:
counter[key] = 1
if self.verbose:
print
# Sort flair list items according to the specified sort
if sort == 'alpha':
items = sorted(counter.items())
else:
items = sorted(counter.items(), key=lambda x: x[1], reverse=True)
# Clear current templates and store flair according to the sort
if self.verbose:
print 'Clearing current flair templates'
self.sub.clear_flair_templates()
for key, count in items:
if not key or count < limit:
continue
if use_text and use_css:
text, css = key
elif use_text:
text, css = key, ''
else:
text, css = '', key
if self.verbose:
print 'Adding template: text: "%s" css: "%s"' % (text, css)
self.sub.add_flair_template(text, css, editable)
def login(self, user, pswd):
if self.verbose:
print 'Logging in'
#.........這裏部分代碼省略.........
示例3: SubRedditStats
# 需要導入模塊: from reddit import Reddit [as 別名]
# 或者: from reddit.Reddit import get_subreddit [as 別名]
class SubRedditStats(object):
VERSION = '0.2.0'
post_prefix = 'Subreddit Stats:'
post_header = '---\n###%s\n'
post_footer = ('>Generated with [BBoe](/user/bboe)\'s [Subreddit Stats]'
'(https://github.com/bboe/subreddit_stats) \n%s'
'SRS Marker: %d')
re_marker = re.compile('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 '/comments/%s/_/' % (tokens[6])
else: # comment
return '/comments/%s/_/%s?context=1' % (tokens[6], tokens[8])
@staticmethod
def _user(user):
return '[%s](/user/%s)' % (user.replace('_', '\_'), user)
def __init__(self, subreddit, site, verbosity):
self.reddit = Reddit(str(self), site)
self.subreddit = self.reddit.get_subreddit(subreddit)
self.verbosity = verbosity
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
# Config
self.reddit.config.comment_limit = -1 # Fetch max comments possible
self.reddit.config.comment_sort = 'top'
def __str__(self):
return 'BBoe\'s SubRedditStats %s' % self.VERSION
def login(self, user, pswd):
if self.verbosity > 0:
print 'Logging in'
self.reddit.login(user, pswd)
def msg(self, msg, level, overwrite=False):
if self.verbosity >= level:
sys.stdout.write(msg)
if overwrite:
sys.stdout.write('\r')
sys.stdout.flush()
else:
sys.stdout.write('\n')
def prev_stat(self, prev_url):
submission = self.reddit.get_submission(prev_url)
self.min_date = self._previous_max(submission)
self.prev_srs = prev_url
def fetch_recent_submissions(self, max_duration, after, exclude_self,
since_last=True):
'''Fetches recent submissions in subreddit with boundaries.
Does not include posts within the last three days as their scores may
not be representative.
Keyword arguments:
max_duration -- When set, specifies the number of days to include
after -- When set, fetch all submission after this submission id.
exclude_self -- When true, don't include self posts.
since_last -- When true use info from last submission to determine the
stop point
'''
if max_duration:
self.min_date = self.max_date - DAYS_IN_SECONDS * max_duration
url_data = {'after': after} if after else None
self.msg('DEBUG: Fetching submissions', 1)
for submission in self.subreddit.get_new_by_date(limit=None,
url_data=url_data):
if submission.created_utc > self.max_date:
continue
if submission.created_utc <= self.min_date:
break
if (since_last and str(submission.author) == str(self.reddit.user)
and submission.title.startswith(self.post_prefix)):
# Use info in this post to update the min_date
# And don't include this post
self.msg('Found previous: %s' % submission.title, 2)
if self.prev_srs == None: # Only use the most recent
self.min_date = max(self.min_date,
self._previous_max(submission))
#.........這裏部分代碼省略.........