• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python models.Subreddit类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中r2.models.Subreddit的典型用法代码示例。如果您正苦于以下问题:Python Subreddit类的具体用法?Python Subreddit怎么用?Python Subreddit使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



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

示例1: __init__

    def __init__(self):
        Wrapped.__init__(self)

        my_reddits = []
        sr_ids = Subreddit.user_subreddits(c.user if c.user_is_loggedin else None)
        if sr_ids:
            my_reddits = Subreddit._byID(sr_ids, True,
                                         return_dict = False)
            my_reddits.sort(key = lambda sr: sr.name.lower())

        drop_down_buttons = []    
        for sr in my_reddits:
            drop_down_buttons.append(SubredditButton(sr))

        #leaving the 'home' option out for now
        #drop_down_buttons.insert(0, NamedButton('home', sr_path = False,
        #                                        css_class = 'top-option',
        #                                        dest = '/'))
        drop_down_buttons.append(NamedButton('edit', sr_path = False,
                                             css_class = 'bottom-option',
                                             dest = '/reddits/'))
        self.sr_dropdown = SubredditMenu(drop_down_buttons,
                                         title = _('my reddits'),
                                         type = 'srdrop')

    
        pop_reddits = Subreddit.default_srs(c.content_langs, limit = 30)        
        buttons = [SubredditButton(sr) for sr in c.recent_reddits]
        for sr in pop_reddits:
            if sr not in c.recent_reddits:
                buttons.append(SubredditButton(sr))
    
        self.sr_bar = NavMenu(buttons, type='flatlist', separator = '-',
                                        _id = 'sr-bar')
开发者ID:vin,项目名称:reddit,代码行数:34,代码来源:pages.py


示例2: new_promotion

def new_promotion(title, url, selftext, user, ip):
    """
    Creates a new promotion with the provided title, etc, and sets it
    status to be 'unpaid'.
    """
    sr = Subreddit._byID(Subreddit.get_promote_srid())
    l = Link._submit(title, url, user, sr, ip)
    l.promoted = True
    l.disable_comments = False
    l.sendreplies = True
    PromotionLog.add(l, 'promotion created')

    if url == 'self':
        l.url = l.make_permalink_slow()
        l.is_self = True
        l.selftext = selftext

    l._commit()

    update_promote_status(l, PROMOTE_STATUS.unpaid)

    # the user has posted a promotion, so enable the promote menu unless
    # they have already opted out
    if user.pref_show_promote is not False:
        user.pref_show_promote = True
        user._commit()

    # notify of new promo
    emailer.new_promo(l)
    return l
开发者ID:APerson241,项目名称:reddit,代码行数:30,代码来源:promote.py


示例3: new_promotion

def new_promotion(is_self, title, content, author, ip):
    """
    Creates a new promotion with the provided title, etc, and sets it
    status to be 'unpaid'.
    """
    sr = Subreddit._byID(Subreddit.get_promote_srid())
    l = Link._submit(
        is_self=is_self,
        title=title,
        content=content,
        author=author,
        sr=sr,
        ip=ip,
    )

    l.promoted = True
    l.disable_comments = False
    l.sendreplies = True
    PromotionLog.add(l, 'promotion created')

    update_promote_status(l, PROMOTE_STATUS.unpaid)

    # the user has posted a promotion, so enable the promote menu unless
    # they have already opted out
    if author.pref_show_promote is not False:
        author.pref_show_promote = True
        author._commit()

    # notify of new promo
    emailer.new_promo(l)
    return l
开发者ID:pra85,项目名称:reddit,代码行数:31,代码来源:promote.py


示例4: get_subreddit

    def get_subreddit(self):
        """checks if the current url refers to a subreddit and returns
        that subreddit object.  The cases here are:

          * the hostname is unset or is g.domain, in which case it
            looks for /r/XXXX or /subreddits.  The default in this case
            is Default.
          * the hostname is a cname to a known subreddit.

        On failure to find a subreddit, returns None.
        """
        from pylons import g
        from r2.models import Subreddit, Sub, NotFound, DefaultSR
        try:
            if (not self.hostname or
                    is_subdomain(self.hostname, g.domain) or
                    self.hostname.startswith(g.domain)):
                if self.path.startswith('/r/'):
                    return Subreddit._by_name(self.path.split('/')[2])
                elif self.path.startswith(('/subreddits/', '/reddits/')):
                    return Sub
                else:
                    return DefaultSR()
            elif self.hostname:
                return Subreddit._by_domain(self.hostname)
        except NotFound:
            pass
        return None
开发者ID:HerculesCE,项目名称:reddit,代码行数:28,代码来源:utils.py


示例5: new_report

def new_report(thing):
    if isinstance(thing, Link):
        sr = Subreddit._byID(thing.sr_id)
        add_queries([get_reported_links(sr)], insert_items = thing)
    elif isinstance(thing, Comment):
        sr = Subreddit._byID(thing.sr_id)
        add_queries([get_reported_comments(sr)], insert_items = thing)
开发者ID:rram,项目名称:reddit,代码行数:7,代码来源:queries.py


示例6: backfill

def backfill(after=None):
    q = Subreddit._query(sort=asc('_date'))
    if after:
        sr = Subreddit._by_name(after)
        q = q._after(sr)

    for sr in fetch_things2(q):
        backfill_sr(sr)
开发者ID:0xcd03,项目名称:reddit,代码行数:8,代码来源:modaction_by_srandmod.py


示例7: get_test_user

 def get_test_user(self):
     account = Account._byID(1, data=True)
     if not account.email:
         account.email = '[email protected]'
         account._commit()
     c.content_langs = ['en']
     Subreddit.subscribe_defaults(account)
     return account
开发者ID:caseypatrickdriscoll,项目名称:reddit,代码行数:8,代码来源:summary_email_test.py


示例8: srids_from_site

def srids_from_site(user, site):
    if not isinstance(site, FakeSubreddit):
        srids = {site._id}
    elif isinstance(site, MultiReddit):
        srids = set(site.sr_ids)
    elif user and not isinstance(user, FakeAccount):
        srids = set(Subreddit.user_subreddits(user, ids=True) + [""])
    else:
        srids = set(Subreddit.user_subreddits(None, ids=True) + [""])
    return srids
开发者ID:AD42,项目名称:reddit,代码行数:10,代码来源:promote.py


示例9: ensure_subreddit

def ensure_subreddit(name, author):
    """Look up or create a subreddit and return it."""
    try:
        sr = Subreddit._by_name(name)
        print ">> found /r/{}".format(name)
        return sr
    except NotFound:
        print ">> creating /r/{}".format(name)
        sr = Subreddit._new(name=name, title="/r/{}".format(name), author_id=author._id, lang="en", ip="127.0.0.1")
        sr._commit()
        return sr
开发者ID:karthikv,项目名称:reddit,代码行数:11,代码来源:inject_test_data.py


示例10: set_subreddit

def set_subreddit():
    #the r parameter gets added by javascript for POST requests so we
    #can reference c.site in api.py
    sr_name = request.environ.get("subreddit", request.POST.get('r'))
    domain = request.environ.get("domain")

    can_stale = request.method.upper() in ('GET', 'HEAD')

    c.site = Frontpage
    if not sr_name:
        #check for cnames
        cname = request.environ.get('legacy-cname')
        if cname:
            sr = Subreddit._by_domain(cname) or Frontpage
            domain = g.domain
            if g.domain_prefix:
                domain = ".".join((g.domain_prefix, domain))
            redirect_to('http://%s%s' % (domain, sr.path), _code=301)
    elif sr_name == 'r':
        #reddits
        c.site = Sub
    elif '+' in sr_name:
        sr_names = sr_name.split('+')
        srs = set(Subreddit._by_name(sr_names, stale=can_stale).values())
        if All in srs:
            c.site = All
        elif Friends in srs:
            c.site = Friends
        else:
            srs = [sr for sr in srs if not isinstance(sr, FakeSubreddit)]
            if len(srs) == 0:
                c.site = MultiReddit([], sr_name)
            elif len(srs) == 1:
                c.site = srs.pop()
            else:
                sr_ids = [sr._id for sr in srs]
                c.site = MultiReddit(sr_ids, sr_name)
    else:
        try:
            c.site = Subreddit._by_name(sr_name, stale=can_stale)
        except NotFound:
            sr_name = chksrname(sr_name)
            if sr_name:
                redirect_to("/reddits/search?q=%s" % sr_name)
            elif not c.error_page and not request.path.startswith("/api/login/") :
                abort(404)

    #if we didn't find a subreddit, check for a domain listing
    if not sr_name and isinstance(c.site, DefaultSR) and domain:
        c.site = DomainSR(domain)

    if isinstance(c.site, FakeSubreddit):
        c.default_sr = True
开发者ID:alexvermeer,项目名称:reddit,代码行数:53,代码来源:reddit_base.py


示例11: srnames_from_site

def srnames_from_site(user, site):
    if not isinstance(site, FakeSubreddit):
        srnames = {site.name}
    elif isinstance(site, MultiReddit):
        srnames = {sr.name for sr in site.srs}
    elif user and not isinstance(user, FakeAccount):
        srnames = {sr.name for sr in Subreddit.user_subreddits(user, ids=False)}
        srnames.add(Frontpage.name)
    else:
        srnames = {sr.name for sr in Subreddit.user_subreddits(None, ids=False)}
        srnames.add(Frontpage.name)
    return srnames
开发者ID:APerson241,项目名称:reddit,代码行数:12,代码来源:promote.py


示例12: subs_contribs

def subs_contribs(sr_name = 'betateam'):
    """Convert all subscribers of a given subreddit to
       contributors. Useful for forming opt-in beta teams"""
    from r2.models import Subreddit, SRMember

    sr = Subreddit._by_name(sr_name)
    q = SRMember._query(SRMember.c._thing1_id == sr._id)

    for rel in rels:
        if rel._name == 'subscriber':
            sr.add_contributor(rel._thing2)
            Subreddit.special_reddits(rel._thing2, 'contributor', _update=True)
开发者ID:Anenome,项目名称:reddit,代码行数:12,代码来源:cmd_utils.py


示例13: get_promotion_list

def get_promotion_list(user, site):
    if not isinstance(site, FakeSubreddit):
        srids = set([site._id])
    elif isinstance(site, MultiReddit):
        srids = set(site.sr_ids)
    elif user and not isinstance(user, FakeAccount):
        srids = set(Subreddit.reverse_subscriber_ids(user) + [""])
    else:
        srids = set(Subreddit.user_subreddits(None, ids=True) + [""])

    tuples = get_promotion_list_cached(srids)
    return [PromoTuple(*t) for t in tuples]
开发者ID:caseypatrickdriscoll,项目名称:reddit,代码行数:12,代码来源:promote.py


示例14: get_promotion_list

def get_promotion_list(user, site):
    # site is specified, pick an ad from that site
    if not isinstance(site, FakeSubreddit):
        srids = set([site._id])
    elif isinstance(site, MultiReddit):
        srids = set(site.sr_ids)
    # site is Fake, user is not.  Pick based on their subscriptions.
    elif user and not isinstance(user, FakeAccount):
        srids = set(Subreddit.reverse_subscriber_ids(user) + [""])
    # both site and user are "fake" -- get the default subscription list
    else:
        srids = set(Subreddit.user_subreddits(None, True) + [""])

    return get_promotions_cached(srids)
开发者ID:cooiky,项目名称:reddit,代码行数:14,代码来源:promote.py


示例15: assign_trial

def assign_trial(account, ip, slash16):
    from r2.models import Jury, Subreddit, Trial
    from r2.lib.db import queries

    defendants_voted_upon = []
    defendants_assigned_to = []
    for jury in Jury.by_account(account):
        defendants_assigned_to.append(jury._thing2_id)
        if jury._name != '0':
            defendants_voted_upon.append(jury._thing2_id)

    subscribed_sr_ids = Subreddit.user_subreddits(account, ids=True, limit=None)

    # Pull defendants, except ones which already have lots of juryvotes
    defs = Trial.all_defendants(quench=True)

    # Filter out defendants outside this user's subscribed SRs
    defs = filter (lambda d: d.sr_id in subscribed_sr_ids, defs)

    # Dictionary of sr_id => SR for all defendants' SRs
    srs = Subreddit._byID(set([ d.sr_id for d in defs ]))

    # Dictionary of sr_id => eligibility bool
    submit_srs = {}
    for sr_id, sr in srs.iteritems():
        submit_srs[sr_id] = sr.can_submit(account) and not sr._spam

    # Filter out defendants with ineligible SRs
    defs = filter (lambda d: submit_srs.get(d.sr_id), defs)

    likes = queries.get_likes(account, defs)

    if not g.debug:
        # Filter out things that the user has upvoted or downvoted
        defs = filter (lambda d: likes.get((account, d)) is None, defs)

    # Prefer oldest trials
    defs.sort(key=lambda x: x._date)

    for defendant in defs:
        sr = srs[defendant.sr_id]

        if voir_dire(account, ip, slash16, defendants_voted_upon, defendant, sr):
            if defendant._id not in defendants_assigned_to:
                j = Jury._new(account, defendant)

            return defendant

    return None
开发者ID:XieConnect,项目名称:reddit,代码行数:49,代码来源:trial_utils.py


示例16: run

 def run(self, path):
     if not self.required and not path:
         return
     adhoc_multi_rx = is_adhoc_multi_rx.match(path)
     if is_multi_rx.match(path):
         return VMultiByPath(self.param, kinds=("m")).run(path)
     elif adhoc_multi_rx:
         sr_strings = adhoc_multi_rx.groups()[0].split("+")
         srs = Subreddit._by_name(sr_strings, stale=True).values()
         return MultiReddit(path, srs)
     else:
         try:
             return Subreddit._by_name(path)
         except NotFound:
             self.set_error(errors.INVALID_SITE_PATH)
开发者ID:KeyserSosa,项目名称:reddit-plugin-adzerk,代码行数:15,代码来源:validator.py


示例17: get_predicted_pageviews

def get_predicted_pageviews(srs, start, end):
    srs, is_single = tup(srs, ret_is_single=True)
    sr_names = [sr.name for sr in srs]

    # default subreddits require a different inventory factor
    content_langs = [g.site_lang]
    default_srids = Subreddit.top_lang_srs(content_langs,
                                           limit=g.num_default_reddits,
                                           filter_allow_top=True, over18=False,
                                           ids=True)

    # prediction does not vary by date
    daily_inventory = PromoMetrics.get(MIN_DAILY_CASS_KEY, sr_names=sr_names)
    dates = get_date_range(start, end)
    ret = {}
    for sr in srs:
        if not isinstance(sr, FakeSubreddit) and sr._id in default_srids:
            factor = DEFAULT_INVENTORY_FACTOR
        else:
            factor = INVENTORY_FACTOR
        sr_daily_inventory = daily_inventory.get(sr.name, 0) * factor
        sr_daily_inventory = int(sr_daily_inventory)
        ret[sr.name] = dict.fromkeys(dates, sr_daily_inventory)

    if is_single:
        return ret[srs[0].name]
    else:
        return ret
开发者ID:SDGXDX,项目名称:reddit,代码行数:28,代码来源:inventory.py


示例18: POST_report

    def POST_report(self, form, jquery, report_type):
        """Report the thread for violating the rules of reddit."""
        if form.has_errors("type", errors.INVALID_OPTION):
            return

        if c.user._spam or c.user.ignorereports:
            return

        already_reported = LiveUpdateReportsByAccount.get_report(
            c.user, c.liveupdate_event)
        if already_reported:
            self.abort403()

        LiveUpdateReportsByAccount.create(
            c.user, c.liveupdate_event, type=report_type)
        queries.report_event(c.liveupdate_event)

        try:
            default_subreddit = Subreddit._by_name(g.default_sr)
        except NotFound:
            pass
        else:
            not_yet_reported = g.cache.add(
                "lu_reported_" + str(c.liveupdate_event._id), 1, time=3600)
            if not_yet_reported:
                send_system_message(
                    default_subreddit,
                    subject="live thread reported",
                    body=REPORTED_MESSAGE % {
                        "title": c.liveupdate_event.title,
                        "url": "/live/" + c.liveupdate_event._id,
                        "reason": pages.REPORT_TYPES[report_type],
                    },
                )
开发者ID:Safturento,项目名称:reddit-plugin-liveupdate,代码行数:34,代码来源:controllers.py


示例19: get_adzerk_promo

def get_adzerk_promo(user, site):
    srids = promote.has_live_promos(user, site)
    if not srids:
        return

    if '' in srids:
        srnames = [Frontpage.name]
        srids.remove('')
    else:
        srnames = []

    srs = Subreddit._byID(srids, data=True, return_dict=False)
    srnames.extend([sr.name for sr in srs])
    response = adzerk_request(srnames)

    if not response:
        return

    promo_tuples = [promote.PromoTuple(response.link, 1., response.campaign)]
    builder = CampaignBuilder(promo_tuples,
                              keep_fn=organic.keep_fresh_links)
    promoted_links = builder.get_items()[0]
    if promoted_links:
        w = promoted_links[0]
        w.adserver_imp_pixel = response.imp_pixel
        w.adserver_click_url = response.click_url
        return w
开发者ID:bsimpson63,项目名称:reddit-plugin-adzerkpromo,代码行数:27,代码来源:adzerkpromo.py


示例20: filter_links

def filter_links(links, filter_spam = False, multiple = True):
    # run the list through a builder to remove any that the user
    # isn't allowed to see
    from pylons import c
    from r2.models import IDBuilder, Link, Subreddit, NotFound
    links = IDBuilder([link._fullname for link in links],
                      skip = False).get_items()[0]
    if not links:
        return

    if filter_spam:
        # first, try to remove any spam
        links_nonspam = [ link for link in links
                          if not link._spam ]
        if links_nonspam:
            links = links_nonspam

    # if it occurs in one or more of their subscriptions, show them
    # that one first
    subs = set(Subreddit.user_subreddits(c.user, limit = None))
    def cmp_links(a, b):
        if a.sr_id in subs and b.sr_id not in subs:
            return -1
        elif a.sr_id not in subs and b.sr_id in subs:
            return 1
        else:
            return cmp(b._hot, a._hot)
    links = sorted(links, cmp = cmp_links)

    # among those, show them the hottest one
    return links if multiple else links[0]
开发者ID:9peppe,项目名称:reddit,代码行数:31,代码来源:utils.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python models.Thing类代码示例发布时间:2022-05-26
下一篇:
Python models.Report类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap