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

Python template_helpers.add_sr函数代码示例

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

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



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

示例1: GET_s

    def GET_s(self, urloid):
        """/s/http://..., show a given URL with the toolbar. if it's
           submitted, redirect to /tb/$id36"""
        force_html()
        path = demangle_url(request.fullpath)

        if not path:
            # it was malformed
            self.abort404()

        # if the domain is shame-banned, bail out.
        if is_shamed_domain(path)[0]:
            self.abort404()

        listing = hot_links_by_url_listing(path, sr=c.site, num=1)
        link = listing.things[0] if listing.things else None

        if link:
            # we were able to find it, let's send them to the
            # toolbar (if enabled) or comments (if not)
            return self.redirect(add_sr("/tb/" + link._id36))
        else:
            # It hasn't been submitted yet. Give them a chance to
            qs = utils.query_string({"url": path})
            return self.redirect(add_sr("/submit" + qs))
开发者ID:pra85,项目名称:reddit,代码行数:25,代码来源:toolbar.py


示例2: __init__

 def __init__(self, *args, **kwargs):
     self.base_url = add_sr(
         "/live/" + c.liveupdate_event._id,
         force_hostname=True,
         force_https=c.secure,
     )
     super(LiveUpdateEventEmbed, self).__init__(*args, **kwargs)
开发者ID:reddit,项目名称:reddit-plugin-liveupdate,代码行数:7,代码来源:pages.py


示例3: GET_wiki_discussions

 def GET_wiki_discussions(self, page, num, after, reverse, count):
     page_url = add_sr("%s/%s" % (c.wiki_base_url, page.name))
     builder = url_links_builder(page_url, num=num, after=after,
                                 reverse=reverse, count=count)
     listing = LinkListing(builder).listing()
     return WikiDiscussions(listing, page=page.name,
                            may_revise=this_may_revise(page)).render()
开发者ID:aldarund,项目名称:reddit,代码行数:7,代码来源:wiki.py


示例4: url_links_builder

def url_links_builder(url, exclude=None, num=None, after=None, reverse=None,
                      count=None):
    from r2.lib.template_helpers import add_sr
    from r2.models import IDBuilder, Link, NotFound
    from operator import attrgetter

    if url.startswith('/'):
        url = add_sr(url, force_hostname=True)

    try:
        links = Link._by_url(url, None)
    except NotFound:
        links = []

    links = [ link for link in links
                   if link._fullname != exclude ]
    links.sort(key=attrgetter('num_comments'), reverse=True)

    # don't show removed links in duplicates unless admin or mod
    # or unless it's your own post
    def include_link(link):
        return (not link._spam or
                (c.user_is_loggedin and
                    (link.author_id == c.user._id or
                        c.user_is_admin or
                        link.subreddit.is_moderator(c.user))))

    builder = IDBuilder([link._fullname for link in links], skip=True,
                        keep_fn=include_link, num=num, after=after,
                        reverse=reverse, count=count)

    return builder
开发者ID:HerculesCE,项目名称:reddit,代码行数:32,代码来源:utils.py


示例5: GET_s

    def GET_s(self, urloid):
        """/s/http://..., show a given URL with the toolbar. if it's
           submitted, redirect to /tb/$id36"""
        force_html()
        path = demangle_url(request.fullpath)

        if not path:
            # it was malformed
            self.abort404()

        # if the domain is shame-banned, bail out.
        if is_shamed_domain(path)[0]:
            self.abort404()

        listing = hot_links_by_url_listing(path, sr=c.site, num=1)
        link = listing.things[0] if listing.things else None

        if c.cname and not c.authorized_cname:
            # In this case, we make some bad guesses caused by the
            # cname frame on unauthorised cnames. 
            # 1. User types http://foo.com/http://myurl?cheese=brie
            #    (where foo.com is an unauthorised cname)
            # 2. We generate a frame that points to
            #    http://www.reddit.com/r/foo/http://myurl?cnameframe=0.12345&cheese=brie
            # 3. Because we accept everything after the /r/foo/, and
            #    we've now parsed, modified, and reconstituted that
            #    URL to add cnameframe, we really can't make any good
            #    assumptions about what we've done to a potentially
            #    already broken URL, and we can't assume that we've
            #    rebuilt it in the way that it was originally
            #    submitted (if it was)
            # We could try to work around this with more guesses (by
            # having demangle_url try to remove that param, hoping
            # that it's not already a malformed URL, and that we
            # haven't re-ordered the GET params, removed
            # double-slashes, etc), but for now, we'll just refuse to
            # do this operation
            return self.abort404()

        if link:
            # we were able to find it, let's send them to the
            # toolbar (if enabled) or comments (if not)
            return self.redirect(add_sr("/tb/" + link._id36))
        else:
            # It hasn't been submitted yet. Give them a chance to
            qs = utils.query_string({"url": path})
            return self.redirect(add_sr("/submit?" + qs))
开发者ID:Acceto,项目名称:reddit,代码行数:47,代码来源:toolbar.py


示例6: update_creative

def update_creative(link, az_advertiser):
    """Add/update a reddit link as an Adzerk Creative"""
    if getattr(link, 'external_creative_id', None) is not None:
        az_creative = adzerk_api.Creative.get(link.external_creative_id)
    else:
        az_creative = None

    title = link._fullname
    url = add_sr(link.url, sr_path=False) if link.is_self else link.url

    # protocols are case sensitive (lower) in adzerk.
    # can cause double protocols:
    # http://Http://www.example.com
    url = re.sub(r"^(https?)", lambda m: m.group(0).lower(), url, flags=re.I)

    # as long as there are no 3rd party trackers for the link
    # it's DNT compliant.
    DNT_compliant = (not (hasattr(link, 'third_party_tracking_url') or
        hasattr(link, 'third_party_tracking_url_2')))

    d = {
        'Body': title,
        'ScriptBody': render_link(link),
        'AdTypeId': LEADERBOARD_AD_TYPE,
        'Alt': '',
        'Url': url,
        'IsHTMLJS': True,
        'IsSync': False,
        'IsDeleted': False,
        'IsActive': not link._deleted,
        'IsNoTrack': DNT_compliant,
    }

    if az_creative:
        changed = update_changed(az_creative, **d)
        change_strs = make_change_strings(changed)
        if change_strs:
            log_text = 'updated %s: ' % az_creative + ', '.join(change_strs)
        else:
            log_text = None
    else:
        d.update({
            'AdvertiserId': az_advertiser.Id,
            'Title': title,
        })
        try:
            az_creative = adzerk_api.Creative.create(**d)
        except:
            raise ValueError(d)

        link.external_creative_id = az_creative.Id
        link._commit()
        log_text = 'created %s' % az_creative

    if log_text:
        PromotionLog.add(link, log_text)
        g.log.info(log_text)

    return az_creative
开发者ID:nramadas,项目名称:reddit-plugin-adzerk,代码行数:59,代码来源:adzerkpromote.py


示例7: GET_wiki_discussions

 def GET_wiki_discussions(self, page, num, after, reverse, count):
     page_url = add_sr("%s/%s" % (c.wiki_base_url, page.name))
     links = url_links(page_url)
     builder = IDBuilder([ link._fullname for link in links ],
                         num = num, after = after, reverse = reverse,
                         count = count, skip = False)
     listing = LinkListing(builder).listing()
     return WikiDiscussions(listing).render()
开发者ID:etel,项目名称:reddit,代码行数:8,代码来源:wiki.py


示例8: _get_related_link_ids

    def _get_related_link_ids(cls, event_id):
        url = add_sr("/live/%s" % event_id, sr_path=False, force_hostname=True)

        try:
            links = tup(Link._by_url(url, sr=None))
        except NotFound:
            links = []

        return [link._id for link in links]
开发者ID:Web5design,项目名称:reddit-plugin-liveupdate,代码行数:9,代码来源:pages.py


示例9: __init__

    def __init__(self):
        links = self.get_links(c.liveupdate_event._id)
        self.more_links = len(links) > self.max_links
        self.links = links[:self.max_links]
        self.submit_url = "/submit?" + urllib.urlencode({
            "url": add_sr("/live/" + c.liveupdate_event._id,
                          sr_path=False, force_hostname=True),
            "title": c.liveupdate_event.title,
        })

        Templated.__init__(self)
开发者ID:Web5design,项目名称:reddit-plugin-liveupdate,代码行数:11,代码来源:pages.py


示例10: GET_s

    def GET_s(self, rest):
        """/s/http://..., show a given URL with the toolbar. if it's
           submitted, redirect to /tb/$id36"""
        force_html()
        path = demangle_url(request.fullpath)

        if not path:
            # it was malformed
            self.abort404()

        # if the domain is shame-banned, bail out.
        if is_shamed_domain(path)[0]:
            self.abort404()

        listing = hot_links_by_url_listing(path, sr=c.site, num=1)
        link = listing.things[0] if listing.things else None

        if c.cname and not c.authorized_cname:
            # In this case, we make some bad guesses caused by the
            # cname frame on unauthorised cnames. 
            # 1. User types http://foo.com/http://myurl?cheese=brie
            #    (where foo.com is an unauthorised cname)
            # 2. We generate a frame that points to
            #    http://www.reddit.com/r/foo/http://myurl?cnameframe=0.12345&cheese=brie
            # 3. Because we accept everything after the /r/foo/, and
            #    we've now parsed, modified, and reconstituted that
            #    URL to add cnameframe, we really can't make any good
            #    assumptions about what we've done to a potentially
            #    already broken URL, and we can't assume that we've
            #    rebuilt it in the way that it was originally
            #    submitted (if it was)
            # We could try to work around this with more guesses (by
            # having demangle_url try to remove that param, hoping
            # that it's not already a malformed URL, and that we
            # haven't re-ordered the GET params, removed
            # double-slashes, etc), but for now, we'll just refuse to
            # do this operation
            return self.abort404()

        if link:
            # we were able to find it, let's send them to the
            # link-id-based URL so that their URL is reusable
            return self.redirect(add_sr("/tb/" + link._id36))

        title = utils.domain(path)
        res = Frame(
            title=title,
            url=match_current_reddit_subdomain(path),
        )

        # we don't want clients to think that this URL is actually a
        # valid URL for search-indexing or the like
        request.environ['usable_error_content'] = spaceCompress(res.render())
        abort(404)
开发者ID:ChooseGoose,项目名称:reddit,代码行数:54,代码来源:toolbar.py


示例11: valid_feed

def valid_feed(name, feedhash, path):
    if name and feedhash and path:
        from r2.lib.template_helpers import add_sr
        path = add_sr(path)
        try:
            user = Account._by_name(name)
            if (user.pref_private_feeds and
                constant_time_compare(feedhash, make_feedhash(user, path))):
                return user
        except NotFound:
            pass
开发者ID:XPRIYA,项目名称:HMWK2PartB,代码行数:11,代码来源:account.py


示例12: intermediate_redirect

 def intermediate_redirect(cls, form_path):
     """
     Generates a /login or /over18 redirect from the current
     fullpath, after having properly reformated the path via
     format_output_url.  The reformatted original url is encoded
     and added as the "dest" parameter of the new url.
     """
     from r2.lib.template_helpers import add_sr
     dest = cls.format_output_url(request.fullpath)
     path = add_sr(form_path + query_string({"dest": dest}))
     return cls.redirect(path)
开发者ID:Craigus,项目名称:lesswrong,代码行数:11,代码来源:base.py


示例13: intermediate_redirect

    def intermediate_redirect(cls, form_path, sr_path=True, fullpath=None):
        """
        Generates a /login or /over18 redirect from the specified or current
        fullpath, after having properly reformated the path via
        format_output_url.  The reformatted original url is encoded
        and added as the "dest" parameter of the new url.
        """
        from r2.lib.template_helpers import add_sr
        params = dict(dest=cls.format_output_url(fullpath or request.fullurl))
        if c.extension == "widget" and request.GET.get("callback"):
            params['callback'] = request.GET.get("callback")

        path = add_sr(cls.format_output_url(form_path) +
                      query_string(params), sr_path=sr_path)
        abort(302, location=path)
开发者ID:GodOfConquest,项目名称:reddit,代码行数:15,代码来源:base.py


示例14: intermediate_redirect

    def intermediate_redirect(cls, form_path):
        """
        Generates a /login or /over18 redirect from the current
        fullpath, after having properly reformated the path via
        format_output_url.  The reformatted original url is encoded
        and added as the "dest" parameter of the new url.
        """
        from r2.lib.template_helpers import add_sr

        params = dict(dest=cls.format_output_url(request.fullpath))
        if c.extension == "widget" and request.GET.get("callback"):
            params["callback"] = request.GET.get("callback")

        path = add_sr(cls.format_output_url(form_path) + query_string(params))
        return cls.redirect(path)
开发者ID:ketralnis,项目名称:reddit,代码行数:15,代码来源:base.py


示例15: GET_urloid

    def GET_urloid(self, urloid):
        # they got here from "/http://..."
        path = demangle_url(request.fullpath)

        if not path:
            # malformed URL
            self.abort404()

        redir_path = add_sr("/s/" + path)
        force_html()

        # Redirect to http://reddit.com/s/http://google.com
        # rather than http://reddit.com/s/http:/google.com
        redir_path = self.slash_fixer.sub(r'\1///', redir_path, 1)
        #                               ^^^
        # 3=2 when it comes to self.redirect()
        return self.redirect(redir_path)
开发者ID:AD42,项目名称:reddit,代码行数:17,代码来源:toolbar.py


示例16: url_links_builder

def url_links_builder(url, exclude=None, num=None, after=None, reverse=None, count=None, public_srs_only=False):
    from r2.lib.template_helpers import add_sr
    from r2.models import IDBuilder, Link, NotFound, Subreddit
    from operator import attrgetter

    if url.startswith("/"):
        url = add_sr(url, force_hostname=True)

    try:
        links = Link._by_url(url, None)
    except NotFound:
        links = []

    links = [link for link in links if link._fullname != exclude]

    if public_srs_only and not c.user_is_admin:
        subreddits = Subreddit._byID([link.sr_id for link in links], data=True)
        links = [link for link in links if subreddits[link.sr_id].type != "private"]

    links.sort(key=attrgetter("num_comments"), reverse=True)

    # don't show removed links in duplicates unless admin or mod
    # or unless it's your own post
    def include_link(link):
        return not link._spam or (
            c.user_is_loggedin
            and (link.author_id == c.user._id or c.user_is_admin or link.subreddit.is_moderator(c.user))
        )

    builder = IDBuilder(
        [link._fullname for link in links],
        skip=True,
        keep_fn=include_link,
        num=num,
        after=after,
        reverse=reverse,
        count=count,
    )

    return builder
开发者ID:rlofblad,项目名称:reddit,代码行数:40,代码来源:utils.py


示例17: GET_goto

 def GET_goto(self, link1, link2):
     """Support old /goto?id= urls. deprecated"""
     link = link2 if link2 else link1
     if link:
         return self.redirect(add_sr("/tb/" + link._id36))
     return self.abort404()
开发者ID:AD42,项目名称:reddit,代码行数:6,代码来源:toolbar.py


示例18: GET_linkoid

 def GET_linkoid(self, link):
     if not link:
         return self.abort404()
     return self.redirect(add_sr("/tb/" + link._id36))
开发者ID:AD42,项目名称:reddit,代码行数:4,代码来源:toolbar.py


示例19: GET_listing

    def GET_listing(self, **env):
        if request.params.get("sort") == "rising":
            return self.redirect(add_sr("/rising"))

        return ListingController.GET_listing(self, **env)
开发者ID:vladimirus,项目名称:reddit,代码行数:5,代码来源:listingcontroller.py


示例20: pre

    def pre(self):
        c.response_wrappers = []
        MinimalController.pre(self)

        set_cnameframe()

        # populate c.cookies unless we're on the unsafe media_domain
        if request.host != g.media_domain or g.media_domain == g.domain:
            try:
                for k,v in request.cookies.iteritems():
                    # minimalcontroller can still set cookies
                    if k not in c.cookies:
                        # we can unquote even if it's not quoted
                        c.cookies[k] = Cookie(value=unquote(v), dirty=False)
            except CookieError:
                #pylons or one of the associated retarded libraries
                #can't handle broken cookies
                request.environ['HTTP_COOKIE'] = ''

        c.firsttime = firsttime()

        # the user could have been logged in via one of the feeds 
        maybe_admin = False

        # no logins for RSS feed unless valid_feed has already been called
        if not c.user:
            if c.extension != "rss":
                session_cookie = c.cookies.get(g.login_cookie)
                if session_cookie:
                    c.user = valid_cookie(session_cookie.value)
                    if c.user:
                        c.user_is_loggedin = True

                admin_cookie = c.cookies.get(g.admin_cookie)
                if c.user_is_loggedin and admin_cookie:
                    maybe_admin, first_login = valid_admin_cookie(admin_cookie.value)

                    if maybe_admin:
                        self.enable_admin_mode(c.user, first_login=first_login)
                    else:
                        self.disable_admin_mode(c.user)

            if not c.user:
                c.user = UnloggedUser(get_browser_langs())
                # patch for fixing mangled language preferences
                if (not isinstance(c.user.pref_lang, basestring) or
                    not all(isinstance(x, basestring)
                            for x in c.user.pref_content_langs)):
                    c.user.pref_lang = g.lang
                    c.user.pref_content_langs = [g.lang]
                    c.user._commit()
        if c.user_is_loggedin:
            if not c.user._loaded:
                c.user._load()
            c.modhash = c.user.modhash()
            if request.method.upper() == 'GET':
                read_mod_cookie()
            if hasattr(c.user, 'msgtime') and c.user.msgtime:
                c.have_messages = c.user.msgtime
            c.show_mod_mail = Subreddit.reverse_moderator_ids(c.user)
            c.have_mod_messages = getattr(c.user, "modmsgtime", False)
            c.user_is_admin = maybe_admin and c.user.name in g.admins
            c.user_special_distinguish = c.user.special_distinguish()
            c.user_is_sponsor = c.user_is_admin or c.user.name in g.sponsors
            if request.path != '/validuser' and not g.disallow_db_writes:
                c.user.update_last_visit(c.start_time)

        c.over18 = over18()

        #set_browser_langs()
        set_host_lang()
        set_iface_lang()
        set_content_lang()
        set_recent_clicks()
        # used for HTML-lite templates
        set_colors()

        # set some environmental variables in case we hit an abort
        if not isinstance(c.site, FakeSubreddit):
            request.environ['REDDIT_NAME'] = c.site.name

        # random reddit trickery -- have to do this after the content lang is set
        if c.site == Random:
            c.site = Subreddit.random_reddit()
            redirect_to("/" + c.site.path.strip('/') + request.path)
        elif c.site == RandomNSFW:
            c.site = Subreddit.random_reddit(over18 = True)
            redirect_to("/" + c.site.path.strip('/') + request.path)
        
        if not request.path.startswith("/api/login/"):
            # is the subreddit banned?
            if c.site.spammy() and not c.user_is_admin and not c.error_page:
                ban_info = getattr(c.site, "ban_info", {})
                if "message" in ban_info:
                    message = ban_info['message']
                else:
                    sitelink = url_escape(add_sr("/"))
                    subject = ("/r/%s has been incorrectly banned" %
                                   c.site.name)
                    link = ("/r/redditrequest/submit?url=%s&title=%s" %
#.........这里部分代码省略.........
开发者ID:blitz80690,项目名称:reddit,代码行数:101,代码来源:reddit_base.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python template_helpers.get_domain函数代码示例发布时间:2022-05-26
下一篇:
Python template_helpers.add_attr函数代码示例发布时间: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