当前位置: 首页>>代码示例>>Python>>正文


Python chrome.Chrome类代码示例

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


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

示例1: filter_stream

 def filter_stream(self, req, method, filename, stream, data):
     if req.get_header("X-Moz") == "prefetch":
         return stream
     if filename == "ticket.html":
         if not self.check_permissions(req):
             return stream
         chrome = Chrome(self.env)
         filter = Transformer('//fieldset[@id="properties"]')
         # add a hidden div to hold the ticket_fields input
         snippet = tag.div(style="display:none;")
         snippet = tag.input(type="hidden", id="field-ticket_fields", name="field_ticket_fields", value=','.join(data['ticket_fields']))
         stream = stream | filter.after(snippet)
         if req.path_info != '/newticket':
             # insert the ticket field groups after the standard trac 'Change Properties' field group
             stream = stream | filter.after(chrome.render_template(req, 'ticket_fields_datatable.html', data, fragment=True))
     elif filename == "admin_enums.html":
         if not self.check_permissions(req) or not req.args.get('path_info'):
             return stream
         for k,v in {'cat_id':'ticket', 'panel_id':'type'}.iteritems():
             if k not in req.args or req.args.get(k) != v:
                 return stream
         if 'ticket_fields' in data:
             chrome = Chrome(self.env)
             filter = Transformer('//div[@class="buttons"]')
             # add a hidden div to hold the ticket_fields input
             snippet = tag.div(style="display:none;")
             snippet = tag.input(type="hidden", id="field-ticket_fields", name="field_ticket_fields", value=','.join(data['ticket_fields']))
             stream = stream | filter.before(snippet)
             stream = stream | filter.before(chrome.render_template(req, 'ticket_fields_datatable.html', data, fragment=True))
     return stream
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:30,代码来源:web_ui.py

示例2: process_request

    def process_request(self, req):
        if req.is_xhr and req.method == 'POST' and 'save_prefs' in req.args:
            self._do_save_xhr(req)

        panels, providers = self._get_panels(req)
        if not panels:
            raise HTTPNotFound(_("No preference panels available"))

        panels = []
        child_panels = {}
        providers = {}
        for provider in self.panel_providers:
            for panel in provider.get_preference_panels(req) or []:
                if len(panel) == 3:
                    name, label, parent = panel
                    child_panels.setdefault(parent, []).append((name, label))
                else:
                    name = panel[0]
                    panels.append(panel)
                providers[name] = provider
        panels = sorted(panels)

        panel_id = req.args.get('panel_id')
        if panel_id is None:
            panel_id = panels[1][0] \
                       if len(panels) > 1 and panels[0][0] == 'advanced' \
                       else panels[0][0]
        chosen_provider = providers.get(panel_id)
        if not chosen_provider:
            raise HTTPNotFound(_("Unknown preference panel '%(panel)s'",
                                 panel=panel_id))

        session_data = {
            'session': req.session,
            'settings': {'session': req.session,  # Compat: remove in 1.3.1
                         'session_id': req.session.sid},
        }

        # Render child preference panels.
        chrome = Chrome(self.env)
        children = []
        if child_panels.get(panel_id):
            for name, label in child_panels[panel_id]:
                ctemplate, cdata = provider.render_preference_panel(req, name)
                cdata.update(session_data)
                rendered = chrome.render_template(req, ctemplate, cdata,
                                                  fragment=True)
                children.append((name, label, rendered))

        template, data = \
            chosen_provider.render_preference_panel(req, panel_id)
        data.update(session_data)
        data.update({
            'active_panel': panel_id,
            'panels': panels,
            'children': children,
        })

        add_stylesheet(req, 'common/css/prefs.css')
        return template, data, None
开发者ID:pkdevbox,项目名称:trac,代码行数:60,代码来源:web_ui.py

示例3: _do_deploy

    def _do_deploy(self, dest):
        target = os.path.normpath(dest)
        chrome_target = os.path.join(target, "htdocs")
        script_target = os.path.join(target, "cgi-bin")

        # Copy static content
        makedirs(target, overwrite=True)
        makedirs(chrome_target, overwrite=True)
        from trac.web.chrome import Chrome

        printout(_("Copying resources from:"))
        for provider in Chrome(self.env).template_providers:
            paths = list(provider.get_htdocs_dirs() or [])
            if not len(paths):
                continue
            printout("  %s.%s" % (provider.__module__, provider.__class__.__name__))
            for key, root in paths:
                if not root:
                    continue
                source = os.path.normpath(root)
                printout("   ", source)
                if os.path.exists(source):
                    dest = os.path.join(chrome_target, key)
                    copytree(source, dest, overwrite=True)

        # Create and copy scripts
        makedirs(script_target, overwrite=True)
        printout(_("Creating scripts."))
        data = {"env": self.env, "executable": sys.executable}
        for script in ("cgi", "fcgi", "wsgi"):
            dest = os.path.join(script_target, "trac." + script)
            template = Chrome(self.env).load_template("deploy_trac." + script, "text")
            stream = template.generate(**data)
            with open(dest, "w") as out:
                stream.render("text", out=out, encoding="utf-8")
开发者ID:spsoft-RockWang,项目名称:project-_trac,代码行数:35,代码来源:env.py

示例4: expand_macro

    def expand_macro(self, formatter, name, content, args=None):
        """
        Returns the outcome from macro.
        """
        req = formatter.req
        userstore = get_userstore()
        user = userstore.getUser(req.authname)
        msgsrv = self.env[MessageService]

        # Parse optional arguments
        if args is None:
            args = parse_args(content)
            if len(args) > 1:
                args = args[1]

        data = {
            'groups': msgsrv.get_messages_grouped_by(user.id)
        }

        # FIXME: Temporary fix for IE8 + jQuery 1.4.4 + Transparency combination
        agent = req.get_header('user-agent')
        if agent and 'MSIE 8.0' not in agent:
            add_script(req, 'multiproject/js/transparency.js')

        add_script(req, 'multiproject/js/multiproject.js')
        add_script(req, 'multiproject/js/messages_group_macro.js')

        chrome = Chrome(self.env)
        return chrome.render_template(req, 'multiproject_messages_group_macro.html', data, fragment=True)
开发者ID:juhamust,项目名称:multiproject,代码行数:29,代码来源:ui.py

示例5: filter_stream

    def filter_stream(self, req, method, filename, stream, data):
        chrome = Chrome(self.env)

        if req.path_info.startswith('/milestone') \
            and req.args.get('action') in ['edit', 'new'] \
            and 'max_level' not in data:
            milestone = data.get('milestone')
            levels = IttecoMilestoneAdminPanel(self.env).milestone_levels
            mydata ={'structured_milestones':StructuredMilestone.select(self.env),
                  'max_level':  levels and len(levels)-1 or 0,
                  'milestone_name' : milestone and milestone.parent or None,
                  'field_name' : 'parent'}
            stream |=Transformer('//*[@id="edit"]/fieldset').append(
                chrome.render_template(req, 'itteco_milestones_dd.html', mydata, fragment=True))
            
        if 'ticket' in data:
            tkt = data['ticket']
            mydata ={
                'structured_milestones':StructuredMilestone.select(self.env),
                'milestone_name': data['ticket']['milestone'],
                'field_name' : 'field_milestone',
                'hide_completed' : not ( tkt.exists and 'TICKET_ADMIN' in req.perm(tkt.resource))
            }
            req.chrome.setdefault('ctxtnav',[]).insert(
                -1, 
                tag.a(
                    _('Go To Whiteboard'), 
                    href=req.href.whiteboard('team_tasks', data['ticket']['milestone'] or 'none')
                )
            )
            stream |=Transformer('//*[@id="field-milestone"]').replace(
                chrome.render_template(req, 'itteco_milestones_dd.html', mydata, fragment=True))
        return stream
开发者ID:esogs,项目名称:IttecoTracPlugin,代码行数:33,代码来源:web_ui.py

示例6: process_request

    def process_request(self, req):
        req.perm.assert_permission('STRACTISTICS_VIEW')
        add_stylesheet(req, 'hw/css/stractistics.css')
        
        #Reading options from trac.ini
        config = util.read_config_options(self.env.config)
        
        #Patch for Trac 0.11
        if trac.__version__.find('0.11') != -1:
            chrome = Chrome(self.env)
            chrome.populate_hdf(req)
                
        #Populating our context navigation bar.
        strac_ref = req.href.stractistics()
        links = []
        for elem in self.sections:
            links.append((elem[0], "/".join([strac_ref, elem[1]])))
        req.hdf['section_links'] = links
        
        db = self.env.get_db_cnx()
        module = req.args.get('module', None)
        if module is not None and module == 'user_reports':
            template, content_type = user_reports.user_reports(req, 
                                                               config, 
                                                               db)
        else:
            template, content_type = global_reports.global_reports(req, 
                                                                   config, 
                                                                   db)
        return template, content_type

    
                
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:30,代码来源:web_ui.py

示例7: get_diffs

def get_diffs(self, req, title, old_text, new_text):
    diff_style, diff_options, diff_data = get_diff_options(req)
    diff_context = 3
    for option in diff_options:
        if option.startswith('-U'):
            diff_context = int(option[2:])
            break
    if diff_context < 0:
        diff_context = None
    diffs = diff_blocks(old_text.splitlines(), new_text.splitlines(), context=diff_context,
                        tabwidth=2,
                        ignore_blank_lines=True,
                        ignore_case=True,
                        ignore_space_changes=True)
    
    chrome = Chrome(self.env)
    loader = TemplateLoader(chrome.get_all_templates_dirs())
    tmpl = loader.load('diff_div.html')
    
    changes=[{'diffs': diffs, 'props': [],
              'title': title,
              'new': {'path':"", 'rev':'', 'shortrev': '', 'href':''},
              'old': {'path':"", 'rev':'', 'shortrev': '', 'href': ''}}]

    data = chrome.populate_data(req,
                                { 'changes':changes , 'no_id':True, 'diff':diff_data,
                                  'longcol': '', 'shortcol': ''})
    diff_data['style']='sidebyside';
    data.update({ 'changes':changes , 'no_id':True, 'diff':diff_data,
                  'longcol': '', 'shortcol': ''})
    stream = tmpl.generate(**data)
    return stream.render()
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:32,代码来源:api.py

示例8: expand_macro

    def expand_macro(self, formatter, name, content):
        req = formatter.req
        stats_provider, kwargs, preview = self._parse_macro_content(content, req)

        # Create & execute the query string
        qstr = '&'.join(['%s=%s' % item
                               for item in kwargs.iteritems()])
        query = Query.from_string(self.env, qstr)
        try:
            # XXX: simplification, may cause problems with more complex queries
            constraints = query.constraints[0]
        except IndexError:
            constraints = {}

        # Calculate stats
        qres = query.execute(req)
        tickets = apply_ticket_permissions(self.env, req, qres)

        stats = get_ticket_stats(stats_provider, tickets)
        stats_data = query_stats_data(req, stats, constraints)

        # ... and finally display them
        add_stylesheet(req, 'common/css/roadmap.css')
        chrome = Chrome(self.env)
        stats_data.update({'preview': preview})     # displaying a preview?
        return chrome.render_template(req, 'progressmeter.html', stats_data,
                                      fragment=True)
开发者ID:andrejtokarcik,项目名称:trac-progressmetermacro,代码行数:27,代码来源:macro.py

示例9: expand_macro

    def expand_macro(self, formatter, name, content, args=None):
        """
        Returns the outcome from macro.
        """
        req = formatter.context.req

        # Check permissions
        if 'TIMELINE_VIEW' not in req.perm:
            # Return default content / instructions
            return tag.div(
                tag.h2(_('Project team'), **{'class': 'title'}),
                tag.p(_('Project team cannot be found or no permission to follow it')),
                **{'class': 'watch'}
            )

        # Load project info from optional project argument. Defaults to current env
        project = Project.get(self.env)
        team, members = self._get_team_info(project)

        # Return rendered HTML with JS attached to it
        data = {
            'project_id': project.id,
            'env_name': self.env.project_identifier,
            'project_name': self.env.project_identifier,  # TODO: redundant
            'team': team,
            'members': members
        }

        # NOTE: Use fragment to not to recreate chrome (add_script does not work) and run post processing manually
        chrome = Chrome(self.env)
        stream = chrome.render_template(req, 'multiproject_team.html', data, fragment=True)
        if req.form_token:
            stream |= chrome._add_form_token(req.form_token)

        return stream
开发者ID:alvabai,项目名称:trac-multiproject,代码行数:35,代码来源:team.py

示例10: expand_macro

    def expand_macro(self, formatter, name, content):
        req = formatter.req

        # Parse arguments
        args, kwargs = parse_args(content, strict=False)
        assert not args and not ('status' in kwargs or 'format' in kwargs), \
          "Invalid input!"
        # hack the `format` kwarg in order to display all-tickets stats
        # when no kwargs are supplied
        kwargs['format'] = 'count'

        # special case for values equal to 'self': replace with current
        # ticket number, if available
        for key in kwargs.keys():
            if kwargs[key] == 'self':
                current_ticket = self._this_ticket(req)
                if current_ticket: kwargs[key] = current_ticket

        # Create & execute the query string
        qstr = '&'.join(['%s=%s' % item
                                for item in kwargs.iteritems()])
        query = Query.from_string(self.env, qstr, max=0)

        # Calculate stats
        qres = query.execute(req)
        tickets = apply_ticket_permissions(self.env, req, qres)

        stats = get_ticket_stats(self.stats_provider, tickets)
        stats_data = query_stats_data(req, stats, query.constraints)

        # ... and finally display them
        add_stylesheet(req, 'common/css/roadmap.css')
        chrome = Chrome(self.env)
        return chrome.render_template(req, 'progressmeter.html', stats_data,
                                      fragment=True)
开发者ID:pombredanne,项目名称:trac-progressmetermacro,代码行数:35,代码来源:macro.py

示例11: expand_macro

    def expand_macro(self, formatter, name, content):
        
        data=dict(user_profiles=[], user_profile_fields={})
        rendered_result=""
        content_args={}
        layout_args={}
        user_profile_templates=[]     
        
        # collecting arguments
        if content:    
            for i, macro_args in enumerate( content.split('|') ):
                if i == 0:
                    content_args = MacroArguments( macro_args )
                    continue
                if i == 1: 
                    layout_args = MacroArguments( macro_args )
                    break
            
            # extracting userProfile attrs 
            if len(content_args)>0:
                user_profile_templates.append(User(**content_args))
                
            if len(content_args.get_list_args())>0:
                for list_item in content_args.get_list_args():
                    user_profile_templates.append(User( **MacroArguments(list_item[1:len(list_item)-1])))
        
        # adding profiles fields description 
        data['user_profile_fields'].update(UserProfileManager(self.env).get_user_profile_fields(ignore_internal=True))

        # removing picture_href
        data['user_profile_fields'].pop('picture_href')
        
        
        def inline_wiki_to_html(text):
            return wiki_to_html(text, self.env, formatter.req)
        data['wiki_to_html'] = inline_wiki_to_html
        
        # grabbing users
        if len(user_profile_templates)>0:
            data['user_profiles'] = UserManager(self.env).search_users(user_profile_templates)
        else:
            data['user_profiles'] = UserManager(self.env).get_active_users()
        
        data['cells']=list(self._get_cells(data['user_profiles']))
        
        # add stylesheet&script
        add_stylesheet(formatter.req,'tracusermanager/css/macros_um_profile.css')
        add_script(formatter.req,'tracusermanager/js/macros_um_profile.js')
        
        # render template
        template = Chrome(self.env).load_template('macro_um_profile.html',method='xhtml')
        data = Chrome(self.env).populate_data(formatter.req, {'users':data})

        rendered_result = template.generate(**data)

        # wrap everything 
        if len(layout_args)>0:
            rendered_result= html.div(rendered_result, **layout_args)

        return rendered_result
开发者ID:okamototk,项目名称:kanonconductor,代码行数:60,代码来源:macros.py

示例12: _render_editor

    def _render_editor(self, req, milestone):
        # Suggest a default due time of 18:00 in the user's timezone
        now = datetime.now(req.tz)
        default_due = datetime(now.year, now.month, now.day, 18)
        if now.hour > 18:
            default_due += timedelta(days=1)
        default_due = to_datetime(default_due, req.tz)

        data = {
            'milestone': milestone,
            'datetime_hint': get_datetime_format_hint(req.lc_time),
            'default_due': default_due,
            'milestone_groups': [],
        }

        if milestone.exists:
            req.perm(milestone.resource).require('MILESTONE_MODIFY')
            milestones = [m for m in Milestone.select(self.env)
                          if m.name != milestone.name
                          and 'MILESTONE_VIEW' in req.perm(m.resource)]
            data['milestone_groups'] = group_milestones(milestones,
                'TICKET_ADMIN' in req.perm)
        else:
            req.perm(milestone.resource).require('MILESTONE_CREATE')

        chrome = Chrome(self.env)
        chrome.add_jquery_ui(req)
        chrome.add_wiki_toolbars(req)
        return 'milestone_edit.html', data, None
开发者ID:nextview,项目名称:medicticket,代码行数:29,代码来源:roadmap.py

示例13: ChromeTestCase2

class ChromeTestCase2(unittest.TestCase):

    def setUp(self):
        self.env = EnvironmentStub(path=tempfile.mkdtemp())
        self.chrome = Chrome(self.env)

    def tearDown(self):
        shutil.rmtree(self.env.path)

    def test_malicious_filename_raises(self):
        req = Request(path_info='/chrome/site/../conf/trac.ini')
        self.assertTrue(self.chrome.match_request(req))
        self.assertRaises(TracError, self.chrome.process_request, req)

    def test_empty_shared_htdocs_dir_raises_file_not_found(self):
        req = Request(path_info='/chrome/shared/trac_logo.png')
        self.assertEqual('', self.chrome.shared_htdocs_dir)
        self.assertTrue(self.chrome.match_request(req))
        from trac.web.api import HTTPNotFound
        self.assertRaises(HTTPNotFound, self.chrome.process_request, req)

    def test_shared_htdocs_dir_file_is_found(self):
        from trac.web.api import RequestDone
        def send_file(path, mimetype):
            raise RequestDone
        req = Request(path_info='/chrome/shared/trac_logo.png',
                      send_file=send_file)
        shared_htdocs_dir = os.path.join(self.env.path, 'chrome', 'shared')
        os.makedirs(shared_htdocs_dir)
        create_file(os.path.join(shared_htdocs_dir, 'trac_logo.png'))
        self.env.config.set('inherit', 'htdocs_dir', shared_htdocs_dir)
        self.assertTrue(self.chrome.match_request(req))
        self.assertRaises(RequestDone, self.chrome.process_request, req)
开发者ID:exocad,项目名称:exotrac,代码行数:33,代码来源:chrome.py

示例14: expand_macro

 def expand_macro(self, formatter, name, args):
     req = formatter.req
     chrome = Chrome(self.env)
     report = ReportModule(self.env)
     
     comma_splitter = re.compile(r'(?<!\\),')
     kwargs = {}
     for arg in comma_splitter.split(args):
         arg = arg.replace(r'\,', ',')
         m = re.match(r'\s*[^=]+=', arg)
         if m:
             kw = arg[:m.end() - 1].strip()
             value = arg[m.end():]
             if re.match(r'^\$[A-Z]*$', value):
                value = req.args.get(value[1:])
             kwargs[kw] = value if value!= None else ''
         else:
             if re.match(r'^\$[A-Z]*$', arg):
                arg = req.args.get(arg[1:])
             id = int(arg)
     
     req.args = kwargs
     req.args['page'] = '1'
     template, data, content_type = report._render_view(req, id)
     add_stylesheet(req, 'common/css/report.css')
     
     fullpath = ''
     if pkg_resources.resource_exists('wikireport', 'WikiReport.html'):
         fullpath = pkg_resources.resource_filename('wikireport', 'WikiReport.html')
     else:
         filepath = os.path.dirname(os.path.abspath( __file__ ))
         fullpath = os.path.join(filepath, 'WikiReport.html')
 
     return chrome.render_template(req, fullpath, data, None, fragment=True)
开发者ID:trac-hacks,项目名称:WikiReportMacro,代码行数:34,代码来源:WikiReport.py

示例15: test_icon_links

    def test_icon_links(self):
        req = Request(abs_href=Href('http://example.org/trac.cgi'),
                      href=Href('/trac.cgi'), base_path='/trac.cgi',
                      path_info='',
                      add_redirect_listener=lambda listener: None)
        chrome = Chrome(self.env)

        # No icon set in config, so no icon links
        self.env.config.set('project', 'icon', '')
        links = chrome.prepare_request(req)['links']
        assert 'icon' not in links
        assert 'shortcut icon' not in links

        # Relative URL for icon config option
        self.env.config.set('project', 'icon', 'foo.ico')
        links = chrome.prepare_request(req)['links']
        self.assertEqual('/trac.cgi/chrome/common/foo.ico',
                         links['icon'][0]['href'])
        self.assertEqual('/trac.cgi/chrome/common/foo.ico',
                         links['shortcut icon'][0]['href'])

        # URL relative to the server root for icon config option
        self.env.config.set('project', 'icon', '/favicon.ico')
        links = chrome.prepare_request(req)['links']
        self.assertEqual('/favicon.ico', links['icon'][0]['href'])
        self.assertEqual('/favicon.ico', links['shortcut icon'][0]['href'])

        # Absolute URL for icon config option
        self.env.config.set('project', 'icon', 'http://example.com/favicon.ico')
        links = chrome.prepare_request(req)['links']
        self.assertEqual('http://example.com/favicon.ico',
                         links['icon'][0]['href'])
        self.assertEqual('http://example.com/favicon.ico',
                         links['shortcut icon'][0]['href'])
开发者ID:dafrito,项目名称:trac-mirror,代码行数:34,代码来源:chrome.py


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