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

Python chrome.web_context函数代码示例

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

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



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

示例1: __init__

    def __init__(self, title, input, correct, file, line, setup=None,
                 teardown=None, context=None):
        unittest.TestCase.__init__(self, 'test')
        self.title = title
        self.input = input
        self.correct = correct
        self.file = file
        self.line = line
        self._setup = setup
        self._teardown = teardown

        req = Mock(href=Href('/'), abs_href=Href('http://www.example.com/'),
                   chrome={}, session={},
                   authname='anonymous', perm=MockPerm(), tz=utc, args={},
                   locale=locale_en, lc_time=locale_en)
        if context:
            if isinstance(context, tuple):
                context = web_context(req, *context)
        else:
            context = web_context(req, 'wiki', 'WikiStart')
        self.context = context

        all_test_components = [
                HelloWorldMacro, DivHelloWorldMacro, TableHelloWorldMacro,
                DivCodeMacro, DivCodeElementMacro, DivCodeStreamMacro,
                NoneMacro, WikiProcessorSampleMacro, SampleResolver]
        self.env = EnvironmentStub(enable=['trac.*'] + all_test_components)
        # -- macros support
        self.env.path = ''
        # -- intertrac support
        self.env.config.set('intertrac', 'trac.title', "Trac's Trac")
        self.env.config.set('intertrac', 'trac.url',
                            "http://trac.edgewall.org")
        self.env.config.set('intertrac', 't', 'trac')
        self.env.config.set('intertrac', 'th.title', "Trac Hacks")
        self.env.config.set('intertrac', 'th.url',
                            "http://trac-hacks.org")
        self.env.config.set('intertrac', 'th.compat', 'false')
        # -- safe schemes
        self.env.config.set('wiki', 'safe_schemes',
                            'file,ftp,http,https,svn,svn+ssh,'
                            'rfc-2396.compatible,rfc-2396+under_score')

        # TODO: remove the following lines in order to discover
        #       all the places were we should use the req.href
        #       instead of env.href
        self.env.href = req.href
        self.env.abs_href = req.abs_href
开发者ID:exocad,项目名称:exotrac,代码行数:48,代码来源:formatter.py


示例2: main

def main():
    names = sorted(name for name in resource_listdir('trac.wiki',
                                                     'default-pages')
                        if not name.startswith('.'))

    env = EnvironmentStub()
    load_components(env)
    with env.db_transaction:
        for name in names:
            wiki = WikiPage(env, name)
            wiki.text = resource_string('trac.wiki', 'default-pages/' +
                                        name).decode('utf-8')
            if wiki.text:
                wiki.save('trac', '')
            else:
                printout('%s: Skipped empty page' % name)

    req = Mock(href=Href('/'), abs_href=Href('http://trac.edgewall.org/'),
               perm=MockPerm(), chrome={})
    for name in sys.argv[1:]:
        name = os.path.basename(name)
        wiki = WikiPage(env, name)
        if not wiki.exists:
            continue
        context = web_context(req, wiki.resource, absurls=True)
        rst = wiki2rest(env, context, wiki)
        sys.stdout.write(rst)
开发者ID:pkdevbox,项目名称:trac,代码行数:27,代码来源:wiki2rst.py


示例3: process_request

    def process_request(self, req):
        presel = req.args.get('preselected')
        if presel and (presel + '/').startswith(req.href.browser() + '/'):
            req.redirect(presel)

        path = req.args.get('path', '/')
        rev = req.args.get('rev', '')
        if rev.lower() in ('', 'head'):
            rev = None
        format = req.args.get('format')
        order = req.args.get('order', 'name').lower()
        desc = 'desc' in req.args
        xhr = req.get_header('X-Requested-With') == 'XMLHttpRequest'

        rm = RepositoryManager(self.env)
        all_repositories = rm.get_all_repositories()
        reponame, repos, path = rm.get_repository_by_path(path)

        # Repository index
        show_index = not reponame and path == '/'
        if show_index:
            if repos and (as_bool(all_repositories[''].get('hidden'))
                          or not repos.is_viewable(req.perm)):
                repos = None

        if not repos and reponame:
            raise ResourceNotFound(_("Repository '%(repo)s' not found",
                                     repo=reponame))

        if reponame and reponame != repos.reponame: # Redirect alias
            qs = req.query_string
            req.redirect(req.href.browser(repos.reponame or None, path)
                         + ('?' + qs if qs else ''))
        reponame = repos.reponame if repos else None

        # Find node for the requested path/rev
        context = web_context(req)
        node = None
        changeset = None
        display_rev = lambda rev: rev
        if repos:
            try:
                if rev:
                    rev = repos.normalize_rev(rev)
                # If `rev` is `None`, we'll try to reuse `None` consistently,
                # as a special shortcut to the latest revision.
                rev_or_latest = rev or repos.youngest_rev
                node = get_existing_node(req, repos, path, rev_or_latest)
            except NoSuchChangeset, e:
                raise ResourceNotFound(e, _('Invalid changeset number'))
            if node:
                try:
                    # use changeset instance to retrieve branches and tags
                    changeset = repos.get_changeset(node.rev)
                except NoSuchChangeset:
                    pass

            context = context.child(repos.resource.child('source', path,
                                                   version=rev_or_latest))
            display_rev = repos.display_rev
开发者ID:exocad,项目名称:exotrac,代码行数:60,代码来源:browser.py


示例4: main

def main():
    options, args = parse_args()
    names = sorted(name for name in resource_listdir('trac.wiki',
                                                     'default-pages')
                        if not name.startswith('.'))
    if args:
        args = sorted(set(names) & set(map(os.path.basename, args)))
    else:
        args = names

    if options.download:
        download_default_pages(args, options.prefix)

    env = EnvironmentStub()
    load_components(env)
    with env.db_transaction:
        for name in names:
            wiki = WikiPage(env, name)
            wiki.text = resource_string('trac.wiki', 'default-pages/' +
                                        name).decode('utf-8')
            if wiki.text:
                wiki.save('trac', '')
            else:
                printout('%s: Skipped empty page' % name)

    req = Mock(href=Href('/'), abs_href=Href('http://localhost/'),
               perm=MockPerm())
    for name in args:
        wiki = WikiPage(env, name)
        if not wiki.exists:
            continue
        context = web_context(req, wiki.resource)
        out = DummyIO()
        DefaultWikiChecker(env, context, name).format(wiki.text, out)
开发者ID:exocad,项目名称:exotrac,代码行数:34,代码来源:checkwiki.py


示例5: _check_quickjump

 def _check_quickjump(self, req, kwd):
     """Look for search shortcuts"""
     # pylint: disable=maybe-no-member
     noquickjump = int(req.args.get('noquickjump', '0'))
     # Source quickjump   FIXME: delegate to ISearchSource.search_quickjump
     quickjump_href = None
     if kwd[0] == '/':
         quickjump_href = req.href.browser(kwd)
         name = kwd
         description = _('Browse repository path %(path)s', path=kwd)
     else:
         context = web_context(req, 'search')
         link = find_element(extract_link(self.env, context, kwd), 'href')
         if link is not None:
             quickjump_href = link.attrib.get('href')
             name = link.children
             description = link.attrib.get('title', '')
     if quickjump_href:
         # Only automatically redirect to local quickjump links
         base_path = req.base_path.replace('@', '%40')
         redirect_href = quickjump_href.replace('@', '%40')
         if not redirect_href.startswith(base_path or '/'):
             noquickjump = True
         if noquickjump:
             return {'href': quickjump_href, 'name': tag.EM(name),
                     'description': description}
         else:
             req.redirect(quickjump_href)
开发者ID:Stackato-Apps,项目名称:bloodhound,代码行数:28,代码来源:web_ui.py


示例6: _send_cards_and_stacks

 def _send_cards_and_stacks(self, req, cards, stacks, stack_names):
     context = web_context(req, 'cards')
     data = {
         'cards_by_id': serialized_cards_by_id(cards, self.env, context),
         'stacks_by_name': serialized_stacks_by_name(stacks, stack_names),
     }
     self._send_json(req, data)
开发者ID:folpindo,项目名称:psuter-cards-plugin,代码行数:7,代码来源:core.py


示例7: from_request

    def from_request(*args, **kwargs):
        """:deprecated: since 1.0, use `web_context` instead. Will be removed
                        in release 1.3.1.
        """
        from trac.web.chrome import web_context

        return web_context(*args, **kwargs)
开发者ID:pkdevbox,项目名称:trac,代码行数:7,代码来源:api.py


示例8: _render_list

 def _render_list(self, req):
     """products list"""
     products = [p for p in Product.select(self.env)
                 if 'PRODUCT_VIEW' in req.perm(Neighborhood('product',
                                                            p.prefix))]
     data = {'products': products,
             'context': web_context(req, Resource('product', None))}
     return 'product_list.html', data, None
开发者ID:Stackato-Apps,项目名称:bloodhound,代码行数:8,代码来源:web_ui.py


示例9: setUp

 def setUp(self):
     self.env = EnvironmentStub(enable=[Chrome, PygmentsRenderer])
     self.pygments = Mimeview(self.env).renderers[0]
     self.req = Mock(base_path='', chrome={}, args={},
                     abs_href=Href('/'), href=Href('/'),
                     session={}, perm=None, authname=None, tz=None)
     self.context = web_context(self.req)
     pygments_html = open(os.path.join(os.path.split(__file__)[0],
                                    'pygments.html'))
     self.pygments_html = Stream(list(HTMLParser(pygments_html, encoding='utf-8')))
开发者ID:exocad,项目名称:exotrac,代码行数:10,代码来源:pygments.py


示例10: _render_list

 def _render_list(self, req):
     """products list"""
     products = [p for p in Product.select(self.env)
                 if 'PRODUCT_VIEW' in req.perm(Neighborhood('product',
                                                            p.prefix))]
     map(lambda p: setattr(p, 'href', resolve_product_href(
         lookup_product_env(self.env, p.prefix), self.env)), products)
     data = {'products': products,
             'context': web_context(req, Resource('product', None))}
     return 'product_list.html', data, None
开发者ID:thimalk,项目名称:bloodhound,代码行数:10,代码来源:web_ui.py


示例11: setUp

 def setUp(self):
     env = EnvironmentStub(enable=[Chrome, PatchRenderer])
     req = Mock(base_path='', chrome={'static_hash': None}, args={},
                session={}, abs_href=Href('/'), href=Href('/'), locale='',
                perm=MockPerm(), authname=None, tz=None)
     self.context = web_context(req)
     self.patch = Mimeview(env).renderers[0]
     patch_html = open(os.path.join(os.path.split(__file__)[0],
                                    'patch.html'))
     self.patch_html = Stream(list(HTMLParser(patch_html, encoding='utf-8')))
开发者ID:moreati,项目名称:trac-gitsvn,代码行数:10,代码来源:patch.py


示例12: post_process_request

    def post_process_request(self, req, template, data, content_type):
        if not req or not template or not isinstance(data, dict):
            return template, data, content_type

        model = None
        resource = None
        attachments = None

        if template in ('wiki_view.html', 'wiki_edit.html'):
            model = data.get('page')
        elif template == 'ticket.html':
            model = data.get('ticket')
        elif template in ('milestone_view.html', 'milestone_edit.html'):
            model = data.get('milestone')
        elif template == 'attachment.html':
            attachments = data.get('attachments')
            if attachments:
                resource = attachments['parent']

        if not resource and model and model.exists:
            resource = model.resource
        if not resource:
            return template, data, content_type
        if not attachments:
            attachments = data.get('attachments')
        if not attachments and model and resource:
            context = web_context(req, resource)
            attachments = AttachmentModule(self.env).attachment_data(context)
            data['attachments'] = attachments

        if template in ('wiki_edit.html', 'milestone_edit.html'):
            self._add_overlayview(req)
        add_stylesheet(req, 'tracdragdrop/tracdragdrop.css')
        if hasattr(req, 'locale'):
            locale = str(req.locale)
            if locale in self.messages_files:
                add_script(req, 'tracdragdrop/messages/%s.js' % locale)
        add_script(req, 'common/js/folding.js')
        add_script(req, 'tracdragdrop/tracdragdrop.js')
        script_data = {
            '_tracdragdrop': {
                'base_url': req.href().rstrip('/') + '/',
                'new_url': req.href('tracdragdrop', 'new', resource.realm,
                                    resource.id),
                'can_create': attachments.get('can_create') or False,
                'max_size': AttachmentModule(self.env).max_size,
            },
            'form_token': req.form_token,
        }
        if add_script_data:
            add_script_data(req, script_data)
        else:
            setattr(req, '_tracdragdrop_data', script_data)

        return template, data, content_type
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:55,代码来源:web_ui.py


示例13: test_template_data

    def test_template_data(self):
        req = Mock(href=self.env.href, perm=MockPerm(), authname="anonymous", tz=None, locale=None)
        context = web_context(req, "query")

        query = Query.from_string(self.env, "owner=$USER&order=id")
        tickets = query.execute(req)
        data = query.template_data(context, tickets, req=req)
        self.assertEqual(["anonymous"], data["clauses"][0]["owner"]["values"])

        query = Query.from_string(self.env, "owner=$USER&order=id")
        tickets = query.execute(req)
        data = query.template_data(context, tickets)
        self.assertEqual(["$USER"], data["clauses"][0]["owner"]["values"])
开发者ID:dafrito,项目名称:trac-mirror,代码行数:13,代码来源:query.py


示例14: _render_editor

    def _render_editor(self, req, product):
        """common processing for creating rendering the edit page"""
        if product._exists:
            req.perm(product.resource).require('PRODUCT_MODIFY')
        else:
            req.perm(product.resource).require('PRODUCT_CREATE')

        chrome = Chrome(self.env)
        chrome.add_jquery_ui(req)
        chrome.add_wiki_toolbars(req)
        data = {'product': product,
                'context': web_context(req, product.resource)}
        return 'product_edit.html', data, None
开发者ID:thimalk,项目名称:bloodhound,代码行数:13,代码来源:web_ui.py


示例15: test_template_data

    def test_template_data(self):
        req = Mock(href=self.env.href, perm=MockPerm(), authname='anonymous',
                   tz=None, locale=None)
        context = web_context(req, 'query')

        query = Query.from_string(self.env, 'owner=$USER&order=id')
        tickets = query.execute(req)
        data = query.template_data(context, tickets, req=req)
        self.assertEqual(['anonymous'], data['clauses'][0]['owner']['values'])

        query = Query.from_string(self.env, 'owner=$USER&order=id')
        tickets = query.execute(req)
        data = query.template_data(context, tickets)
        self.assertEqual(['$USER'], data['clauses'][0]['owner']['values'])
开发者ID:moreati,项目名称:trac-gitsvn,代码行数:14,代码来源:query.py


示例16: process_request

    def process_request(self, req):
        """process request handler"""

        req.perm.require('PRODUCT_VIEW')
        pid = req.args.get('productid', None)
        if pid:
            req.perm('product', pid).require('PRODUCT_VIEW')

        try:
            product = Product(self.env, {'prefix': pid})
        except ResourceNotFound:
            product = Product(self.env)

        path_info = req.args.get('pathinfo')
        if path_info and path_info != '/':
            if not product._exists:
                # bh:ticket:561 - Display product list and warning message
                if pid:
                    add_warning(req, _("Product %(pid)s not found", pid=pid))
                return self._render_list(req)
            else:
                raise HTTPNotFound(
                    _('Unable to render product page. Wrong setup?'))

        if pid:
            add_link(req, 'up', req.href.products(), _('Products'))

        action = req.args.get('action', 'view')
        if req.method == 'POST':
            if 'cancel' in req.args:
                req.redirect(req.href.products(product.prefix))
            elif action == 'edit':
                return self._do_save(req, product)
            elif action == 'delete':
                raise TracError(_('Product removal is not allowed!'))
        elif action in ('new', 'edit'):
            return self._render_editor(req, product)
        elif action == 'delete':
            raise TracError(_('Product removal is not allowed!'))

        if not product._exists:
            if pid:
                # bh:ticket:561 - Display product list and warning message
                add_warning(req, _("Product %(pid)s not found", pid=pid))
            return self._render_list(req)

        data = {'product': product,
                'context': web_context(req, product.resource)}
        return 'product_view.html', data, None
开发者ID:thimalk,项目名称:bloodhound,代码行数:49,代码来源:web_ui.py


示例17: process_request

 def process_request(self, req):
     link = req.args.get('link', '')
     parts = link.split(':', 1)
     if len(parts) > 1:
         resolver, target = parts
         if target[:1] + target[-1:] not in ('""', "''"):
             link = '%s:"%s"' % (resolver, target)
     from trac.web.chrome import web_context
     link_frag = extract_link(self.env, web_context(req), link)
     if isinstance(link_frag, (Element, Fragment)):
         elt = find_element(link_frag, 'href')
         if elt is None: # most probably no permissions to view
             raise PermissionError(_("Can't view %(link)s:", link=link))
         href = elt.attrib.get('href')
     else:
         href = req.href(link.rstrip(':'))
     req.redirect(href)
开发者ID:moreati,项目名称:trac-gitsvn,代码行数:17,代码来源:intertrac.py


示例18: _wiki_view

    def _wiki_view(self, req, stream):
        add_stylesheet(req, 'tags/css/tractags.css')
        tags = self._page_tags(req)
        if not tags:
            return stream
        li = []
        for tag_ in tags:
            resource = Resource('tag', tag_)
            anchor = render_resource_link(self.env,
                                          web_context(req, resource),
                                          resource)
            anchor = anchor(rel='tag')
            li.append(tag.li(anchor, ' '))

        # TRANSLATOR: Header label text for tag list at wiki page bottom.
        insert = tag.ul(class_='tags')(tag.li(_("Tags"), class_='header'), li)
        return stream | (Transformer('//div[contains(@class,"wikipage")]')
                         .after(insert))
开发者ID:t-kenji,项目名称:trac-tags-plugin,代码行数:18,代码来源:wiki.py


示例19: test_timeline_events

    def test_timeline_events(self):
        """Regression test for #11288"""
        tktmod = web_ui.TicketModule(self.env)
        now = datetime.now(utc)
        start = now - timedelta(hours=1)
        stop = now + timedelta(hours=1)
        events = tktmod.get_timeline_events(self.req, start, stop,
                                            ['ticket_details'])
        self.assertEqual(True, all(ev[0] != 'batchmodify' for ev in events))

        ids = []
        for i in xrange(20):
            ticket = Ticket(self.env)
            ticket['summary'] = 'Ticket %d' % i
            ids.append(ticket.insert())
        ids.sort()
        new_values = {'summary': 'batch updated ticket',
                      'owner': 'ticket11288', 'reporter': 'ticket11288'}
        batch = BatchModifyModule(self.env)
        batch._save_ticket_changes(self.req, ids, new_values, '', 'leave')
        # shuffle ticket_change records
        with self.env.db_transaction as db:
            rows = db('SELECT * FROM ticket_change')
            db.execute('DELETE FROM ticket_change')
            rows = rows[0::4] + rows[1::4] + rows[2::4] + rows[3::4]
            db.executemany('INSERT INTO ticket_change VALUES (%s)' %
                           ','.join(('%s',) * len(rows[0])),
                           rows)

        events = tktmod.get_timeline_events(self.req, start, stop,
                                            ['ticket_details'])
        events = [ev for ev in events if ev[0] == 'batchmodify']
        self.assertEqual(1, len(events))
        batch_ev = events[0]
        self.assertEqual('anonymous', batch_ev[2])
        self.assertEqual(ids, sorted(batch_ev[3][0]))
        self.assertEqual('updated', batch_ev[3][1])

        context = web_context(self.req)
        self.assertEqual(
            self.req.href.query(id=','.join(str(t) for t in ids)),
            tktmod.render_timeline_event(context, 'url', batch_ev))
开发者ID:pkdevbox,项目名称:trac,代码行数:42,代码来源:batch.py


示例20: _insert_crashdump_data

    def _insert_crashdump_data(self, req, crashobj, data, author_id, field_changes):
        """Insert crashobj data into the template `data`"""
        replyto = req.args.get('replyto')
        data['replyto'] = replyto
        data['version'] = crashobj.resource.version
        data['description_change'] = None
        data['author_id'] = author_id

        if crashobj.resource.version is not None:
            crashobj.values.update(values)

        context = web_context(req, crashobj.resource)

        # Display the owner and reporter links when not obfuscated
        chrome = Chrome(self.env)
        for user in 'reporter', 'owner':
            if chrome.format_author(req, crashobj[user]) == crashobj[user]:
                data['%s_link' % user] = self._query_link(req, user,
                                                          crashobj[user])
        data['context'] = context
开发者ID:aroth-arsoft,项目名称:trac-crashdump,代码行数:20,代码来源:web_ui.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python chrome.Chrome类代码示例发布时间:2022-05-27
下一篇:
Python chrome.add_warning函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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