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

Python chrome.Chrome类代码示例

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

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



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


示例16: expand_macro

    def expand_macro(self, formatter, name, content):
        req = formatter.req
        stats_provider, kwargs = 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, max=0)
        try:
            constraints = query.constraints[0]
        except IndexError:
            constraints = query.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)
        return chrome.render_template(req, 'progressmeter.html', stats_data,
                                      fragment=True)
开发者ID:pombredanne,项目名称:trac-progressmetermacro,代码行数:25,代码来源:macro.py


示例17: filter_stream

    def filter_stream(self, req, method, filename, stream, data):
        """Return a filtered Genshi event stream, or the original unfiltered
        stream if no match.

        `req` is the current request object, `method` is the Genshi render
        method (xml, xhtml or text), `filename` is the filename of the template
        to be rendered, `stream` is the event stream and `data` is the data for
        the current template.

        See the Genshi documentation for more information.
        """
        if filename == "query.html" and self.inject_query:
            self.geoticket()  # sanity check
            chrome = Chrome(self.env)
            variables = ("center_location", "radius")
            _data = dict([(i, data.get(i)) for i in variables])

            # georegions
            _data["geo_column_label"] = None
            _data["regions"] = None
            if self.env.is_component_enabled(GeoRegions):
                georegions = GeoRegions(self.env)
                if georegions.enabled():
                    regions = georegions.regions()
                    if regions:
                        column, regions = regions
                        _data["geo_column_label"] = column
                        _data["regions"] = regions
                        _data["region"] = req.args.get("region")

            template = chrome.load_template("geoquery.html")
            stream |= Transformer("//fieldset[@id='columns']").after(template.generate(**_data))

        return stream
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:34,代码来源:query.py


示例18: render_property_diff

    def render_property_diff(self, req, ticket, field, old, new,
                              resource_new=None):
        "Version for Trac 0.11"
        rendered = None
        # per type special rendering of diffs
        type_ = None
        for f in ticket.fields:
            if f['name'] == field:
                type_ = f['type']
                break
        if type_ == 'checkbox':
            rendered = new == '1' and "set" or "unset"
        elif type_ == 'textarea':
            if not resource_new:
                rendered = _('modified')
            else:
                href = get_resource_url(self.env, resource_new, req.href,
                                        action='diff')
                rendered = tag('modified (', tag.a('diff', href=href), ')')

        # per name special rendering of diffs
        old_list, new_list = None, None
        render_elt = lambda x: x
        sep = ', '
        if field == 'cc':
            chrome = Chrome(self.env)
            old_list, new_list = chrome.cc_list(old), chrome.cc_list(new)
            if not (Chrome(self.env).show_email_addresses or
                    'EMAIL_VIEW' in req.perm(resource_new or ticket.resource)):
                render_elt = obfuscate_email_address
        elif field == 'keywords':
            old_list, new_list = (old or '').split(), new.split()
            sep = ' '
        if (old_list, new_list) != (None, None):
            added = [tag.em(render_elt(x)) for x in new_list
                     if x not in old_list]
            remvd = [tag.em(render_elt(x)) for x in old_list
                     if x not in new_list]
            added = added and tag(separated(added, sep), " added")
            remvd = remvd and tag(separated(remvd, sep), " removed")
            if added or remvd:
                rendered = tag(added, added and remvd and '; ', remvd)
                return rendered
        if field in ('reporter', 'owner'):
            if not (Chrome(self.env).show_email_addresses or
                    'EMAIL_VIEW' in req.perm(resource_new or ticket.resource)):
                old = obfuscate_email_address(old)
                new = obfuscate_email_address(new)
        # Added by MS
        if field == 'attachment':
            rendered = tag(tag.em(new), " added")
        # changed 'if' to 'elif':
        elif old and not new:
            rendered = tag(tag.em(old), " deleted")
        elif new and not old:
            rendered = tag("set to ", tag.em(new))
        elif old and new:
            rendered = tag("changed from ", tag.em(old),
                            " to ", tag.em(new))
        return rendered
开发者ID:gaod,项目名称:trac-watchlistplugin,代码行数:60,代码来源:__init__.py


示例19: _create_page_param

    def _create_page_param(self, req, page_param):
        # page_param['workflow_config']
        
        # sort config for display
        section = self.config['ticket-workflow']
        name_list = []
        for (name, value) in section.options():
            name_list.append(name)
        name_list.sort()

        # create config data for display
        ret_val = ''
        for name in name_list:
            ret_val += name + '=' + section.get(name) + '\n'
        
        page_param['workflow_config'] = ret_val
        
        # page_param['workflow_default_config']
        
        # localization
        locale = LocaleUtil().get_locale(req)
        if (locale == 'ja'):
            init_file = 'trac_jp.ini'
        else:
            init_file = 'trac.ini'
        
        # read defalut config
        template = Chrome(self.env).load_template(init_file, 'text')
        stream = template.generate()
        default_config = stream.render('text', encoding=None)
        
        page_param['workflow_default_config'] = default_config
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:32,代码来源:workfloweditor_admin.py


示例20: matches

    def matches(self, event):
        if event.realm != 'ticket':
            return
        if event.category not in ('created', 'changed', 'attachment added',
                                  'attachment deleted'):
            return

        # CC field is stored as comma-separated string. Parse to set.
        chrome = Chrome(self.env)
        to_set = lambda cc: set(chrome.cc_list(cc))
        cc_set = to_set(event.target['cc'] or '')

        # Harvest previous CC field
        if 'fields' in event.changes and 'cc' in event.changes['fields']:
            cc_set.update(to_set(event.changes['fields']['cc']['old']))

        matcher = RecipientMatcher(self.env)
        klass = self.__class__.__name__
        sids = set()
        for cc in cc_set:
            recipient = matcher.match_recipient(cc)
            if not recipient:
                continue
            sid, auth, addr = recipient

            # Default subscription
            for s in self.default_subscriptions():
                yield (s[0], s[1], sid, auth, addr, s[2], s[3], s[4])
            if sid:
                sids.add((sid,auth))

        for s in Subscription.find_by_sids_and_class(self.env, sids, klass):
            yield s.subscription_tuple()
开发者ID:pkdevbox,项目名称:trac,代码行数:33,代码来源:notification.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python session.Session类代码示例发布时间:2022-05-27
下一篇:
Python chrome.web_context函数代码示例发布时间: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