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


Python Context.from_request方法代码示例

本文整理汇总了Python中trac.mimeview.api.Context.from_request方法的典型用法代码示例。如果您正苦于以下问题:Python Context.from_request方法的具体用法?Python Context.from_request怎么用?Python Context.from_request使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在trac.mimeview.api.Context的用法示例。


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

示例1: template_data

# 需要导入模块: from trac.mimeview.api import Context [as 别名]
# 或者: from trac.mimeview.api.Context import from_request [as 别名]
 def template_data(self, req, query, kwargs=None):
     db = self.env.get_read_db()
     tickets = query.execute(req, db)
     filtered_tickets = [ticket for ticket in tickets if 'TICKET_VIEW' in req.perm(Ticket(self.env, int(ticket['id'])).resource)]
     context = Context.from_request(req, 'query')
     return query.template_data(context, filtered_tickets, None,
                                datetime.now(req.tz), req)
开发者ID:KKBOX,项目名称:trac-ticket-calendar-plugin,代码行数:9,代码来源:web_ui.py

示例2: process_request

# 需要导入模块: from trac.mimeview.api import Context [as 别名]
# 或者: from trac.mimeview.api.Context import from_request [as 别名]
 def process_request(self, req):
     page_name = req.args.get('page_name', '')
     if page_name == '':
         page_name = 'index'
     
     # Add breadcrumb
     package_name, filename = self._get_package_and_filename(page_name)
     index_file = filename[:-len('.txt')] + '/index.txt'
     
     if not self._resource_exists(package_name, filename):
         # check if it is a folder, then match with index
         if self._resource_exists(package_name, index_file):
             filename = index_file
         else:
             error_msg = _('Page %(page_name)s not found', page_name=page_name)
             raise ResourceNotFound(error_msg)
     
     utf8_string = resource_string(package_name, filename)
     help_contents = utf8_string.decode('UTF-8')
     # add navigation bar
     self._set_prev_next(req)
     
     data = dict(context=Context.from_request(req), contents=help_contents,
                 page_name=page_name)
     return ('agilo_help.html', data, 'text/html')
开发者ID:djangsters,项目名称:agilo,代码行数:27,代码来源:web_ui.py

示例3: get_list_pages

# 需要导入模块: from trac.mimeview.api import Context [as 别名]
# 或者: from trac.mimeview.api.Context import from_request [as 别名]
def get_list_pages(request, dbp, obj, resource):
    require_permission(request.req, resource, dbp.env)

    artifact_id = request.req.args.get('artifact', None)
    if artifact_id is None:
        raise Exception("No artifact was specified.")
    dbp.load_artifact(artifact_id)
    artifact = dbp.pool.get_item(artifact_id)

    results = []
    for pagename, page_version_id, ref_count in dbp.get_wiki_page_ref_counts(artifact):
        page = WikiPage(dbp.env, pagename)

        results.append(
            {'href': get_resource_url(dbp.env, page.resource, request.req.href),
             'title': pagename,
             'date': user_time(request.req, format_datetime, page.time),
             'author': page.author,
             'excerpt': shorten_result(page.text)}
        )

    data = {
        'context': Context.from_request(request.req, resource),
        'artifact': artifact,
        'results': results,
    }
    return 'list_pages.html', data, None
开发者ID:filipefigcorreia,项目名称:TracAdaptiveSoftwareArtifacts,代码行数:29,代码来源:views.py

示例4: _convert_query

# 需要导入模块: from trac.mimeview.api import Context [as 别名]
# 或者: from trac.mimeview.api.Context import from_request [as 别名]
    def _convert_query(self, req, query, sheet_query=True,
                       sheet_history=False):
        # no paginator
        query.max = 0
        query.has_more_pages = False
        query.offset = 0

        # extract all fields except custom fields
        cols = ['id']
        cols.extend(f['name'] for f in query.fields if not f.get('custom'))
        cols.extend(name for name in ('time', 'changetime')
                         if name not in cols)
        query.cols = cols

        if hasattr(self.env, 'get_read_db'):
            db = self.env.get_read_db()
        else:
            db = self.env.get_db_cnx()
        tickets = query.execute(req, db)
        # add custom fields to avoid error to join many tables
        custom_fields = [f['name'] for f in query.fields if f.get('custom')]
        self._fill_custom_fields(tickets, custom_fields, db)

        context = Context.from_request(req, 'query', absurls=True)
        cols.extend([name for name in custom_fields if name not in cols])
        data = query.template_data(context, tickets)

        book = Workbook(encoding='utf-8', style_compression=1)
        if sheet_query:
            self._create_sheet_query(req, context, data, book)
        if sheet_history:
            self._create_sheet_history(req, context, data, book)
        return get_workbook_content(book), 'application/vnd.ms-excel'
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:35,代码来源:ticket.py

示例5: _do_ticket

# 需要导入模块: from trac.mimeview.api import Context [as 别名]
# 或者: from trac.mimeview.api.Context import from_request [as 别名]
 def _do_ticket(self, req, template, data, content_type):
     if 'ticket' in data and 'linked_tickets' in data:
         ticket = data['ticket']
         context = Context.from_request(req, ticket.resource)
         
         # Add name:#n links to link fields of Ticket instance when
         # flowing from storage to browser
         if req.method == 'GET':
             RemoteLinksProvider(self.env).augment_ticket(ticket)
         
         # Rerender link fields
         for field in data['fields']:
             if field['type'] == 'link':
                 name = field['name']
                 field['rendered'] = format_to_oneliner(self.env, context,
                                                        ticket[name])
         
         # Add RemoteTicket objects for linked issues table, and pass list
         # of rejects that could not be retrieved
         linked_tickets, linked_rejects = self._remote_tickets(ticket,
                                                               context)
         data['linked_tickets'].extend(linked_tickets)
         data['linked_rejects'].extend(linked_rejects)
     
     # Provide list of remote sites if newlinked form options are present
     if 'newlinked_options' in data:
         remote_sites = RemoteTicketSystem(self.env).get_remote_tracs()
         data['remote_sites'] = remote_sites
     
     return (template, data, content_type)
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:32,代码来源:web_ui.py

示例6: process_request

# 需要导入模块: from trac.mimeview.api import Context [as 别名]
# 或者: from trac.mimeview.api.Context import from_request [as 别名]
 def process_request(self, req):
     # Allow all POST requests (with a valid __FORM_TOKEN, ensuring that
     # the client has at least some permission). Additionally, allow GET
     # requests from TRAC_ADMIN for testing purposes.
     if req.method != 'POST':
         req.perm.require('TRAC_ADMIN')
     realm = req.args.get('realm', 'wiki')
     id = req.args.get('id')
     version = req.args.get('version')
     if version is not None:
         try:
             version = int(version)
         except ValueError:
             version = None
     text = req.args.get('text', '')
     flavor = req.args.get('flavor')
     options = {}
     if 'escape_newlines' in req.args:
         options['escape_newlines'] = bool(int(req.args['escape_newlines']
                                               or 0))
     if 'shorten' in req.args:
         options['shorten'] = bool(int(req.args['shorten'] or 0))
     
     resource = Resource(realm, id=id, version=version)
     context = Context.from_request(req, resource)
     rendered = format_to(self.env, flavor, context, text, **options)
     req.send(rendered.encode('utf-8'))
开发者ID:wiraqutra,项目名称:photrackjp,代码行数:29,代码来源:web_api.py

示例7: get_edit_artifact

# 需要导入模块: from trac.mimeview.api import Context [as 别名]
# 或者: from trac.mimeview.api.Context import from_request [as 别名]
def get_edit_artifact(request, dbp, obj, resource):
    require_permission(request.req, resource, dbp.env, operation="MODIFY")

    assert(isinstance(obj, Instance)) # otherwise, we're trying to edit something that is not an artifact

    aa_attributes = [name for name, val in obj.get_values()]
    attr_suggestions = [attr.name for attr in obj.get_attributes() if not attr.name in aa_attributes]

    values = []
    for name,val in obj.get_values():
        if type(val) is list:
            for v in val:
                values.append((str(uuid.uuid4()), name, v))
        else:
            values.append((str(uuid.uuid4()), name, val))

    # track access
    dbp.track_it("artifact", obj.get_id(), "edit", request.req.authname, str(datetime.now()))

    data = {
        'context': Context.from_request(request.req, resource),
        'spec_name': obj.__class__.get_name() if not obj.__class__ == Instance else "",
        'artifact': obj,
        'artifact_values': values,
        'attr_suggestions' : attr_suggestions,
        'default': obj.str_attr,
        'url_path': request.req.href.customartifacts('artifact', obj.get_id()),
        }
    return 'edit_artifact_%s.html' % (request.get_format(),), data, None
开发者ID:filipefigcorreia,项目名称:TracAdaptiveSoftwareArtifacts,代码行数:31,代码来源:views.py

示例8: pre_process_request

# 需要导入模块: from trac.mimeview.api import Context [as 别名]
# 或者: from trac.mimeview.api.Context import from_request [as 别名]
    def pre_process_request(self, req, handler):
        if req.path_info.startswith('/wiki'):
            if req.method == 'POST' and req.args.get('action','view') == 'view':
                post_handler = None
                for poster in self.macro_posters:
                    if not hasattr(poster, 'match_macro_post'): continue
                    rv = poster.match_macro_post(req)
                    if isinstance(rv, (str, unicode)):
                        rv = rv in req.args.keys()
                    if rv:
                        post_handler = poster
                        break
                if post_handler:
                    post_handler.process_macro_post(req)
                else:
                    # Silly stuff here
                    self.log.debug('MacroPostModule: Unclaimed POST, scanning page %s', req.path_info[6:])
                    page = WikiPage(self.env, req.path_info[6:])
                    matches = self.macro_re.findall(page.text) + self.proc_re.findall(page.text)
                    for name in matches:
                        self.log.debug('MacroPostModule: Found macro "%s"', name)
                        resource = Resource('wiki', name)
                        context = Context.from_request(req, resource)
                        wp = WikiProcessor(Formatter(self.env, context), name)
                        if wp.macro_provider is None:
                            self.log.debug('MacroPostModule: Invalid name!!! How did that happen')
                            continue
                        if hasattr(wp.macro_provider, 'process_macro_post') and \
                           not hasattr(wp.macro_provider, 'match_macro_post'):
                            wp.macro_provider.process_macro_post(req)
                req.environ['REQUEST_METHOD'] = 'GET' # Revert back to a GET

        return handler
开发者ID:okamototk,项目名称:kanonconductor,代码行数:35,代码来源:web_ui.py

示例9: process_request

# 需要导入模块: from trac.mimeview.api import Context [as 别名]
# 或者: from trac.mimeview.api.Context import from_request [as 别名]
 def process_request(self, req):
     # Allow all POST requests (with a valid __FORM_TOKEN, ensuring that
     # the client has at least some permission). Additionally, allow GET
     # requests from TRAC_ADMIN for testing purposes.
     if req.method != 'POST':
         req.perm.require('TRAC_ADMIN')
         
     # @todo: Embed "tips" within the rendered output for the editor
     # (recognize TracLinks, table-stuff, macros, processors)
     # @todo: Save the content in server-side user-specific field for recovery
     
     realm = req.args.get('realm', 'wiki')
     id = req.args.get('id')
     version = req.args.get('version')
     if version is not None:
         try:
             version = int(version)
         except ValueError:
             version = None
     text = req.args.get('text', '')
     flavor = req.args.get('flavor')
     options = {}
     if 'escape_newlines' in req.args:
         options['escape_newlines'] = bool(int(req.args['escape_newlines']
                                               or 0))
     if 'shorten' in req.args:
         options['shorten'] = bool(int(req.args['shorten'] or 0))
     
     resource = Resource(realm, id=id, version=version)
     context = Context.from_request(req, resource)
     rendered = format_to(self.env, flavor, context, text, **options)
     req.send(rendered.encode('utf-8'))
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:34,代码来源:__init__.py

示例10: expand_macro

# 需要导入模块: from trac.mimeview.api import Context [as 别名]
# 或者: from trac.mimeview.api.Context import from_request [as 别名]
    def expand_macro(self, formatter, name, content):
        # Example: [[ASA(42)]]
        args, kw = parse_args(content)
        args = [arg.strip() for arg in args]
        if not args or not args[0].isdigit():
            raise TracError('Custom artifact id not specified')
        args, kw = parse_args(content)
        if not args or not args[0].isdigit():
            raise TracError('Custom artifact id not specified')
        artifact_id = int(args[0])
        dbp = DBPool(self.env, InstancePool())
        try:
            dbp.load_artifact(id=artifact_id)
        except ValueError:
            return system_message("Custom Artifact not found", "No custom artifact was found for id '{0}'.".format(artifact_id))
        artifact = dbp.pool.get_item(id=artifact_id)
        artifact_url = formatter.req.href.customartifacts('artifact/{0}'.format(artifact.get_id()))
        res = Core._get_resource(artifact) if not artifact in (Entity, Instance, None) and not type(artifact)==unicode else None
        spec_name, spec_url, values = _get_artifact_details(artifact, formatter.req)

        tpl='view_artifact_dialog.html'
        data = {
            'context': Context.from_request(formatter.req, res),
            'spec_name': spec_name,
            'spec_url': spec_url,
            'artifact': artifact,
            'artifact_url': artifact_url,
            'artifacts_values': values,
        }
        return Chrome(self.env).render_template(formatter.req, tpl, data, None, fragment=True)
开发者ID:filipefigcorreia,项目名称:TracAdaptiveSoftwareArtifacts,代码行数:32,代码来源:__init__.py

示例11: wiki_to_html

# 需要导入模块: from trac.mimeview.api import Context [as 别名]
# 或者: from trac.mimeview.api.Context import from_request [as 别名]
    def wiki_to_html(self, wikitext, req):
        self.env.log.debug('start function wiki_to_html') # pylint: disable-msg=E1101

        # Remove some macros (TOC is better handled in ODT itself)
        for macro in self.remove_macros:
            wikitext = re.sub('\[\[%s(\([^)]*\))?\]\]' % macro, "", wikitext)

        # Now convert wiki to HTML
        out = StringIO()
        context = Context.from_request(req, absurls=True)
        Formatter(self.env, # pylint: disable-msg=E1101
                  context('wiki', self.page_name)).format(wikitext, out)
        html = Markup(out.getvalue())
        html = html.encode("utf-8", 'replace')

        # Clean up the HTML
        html = re.sub('<span class="icon">.</span>', '', html) # Remove external link icon
        tidy_options = dict(output_xhtml=1, add_xml_decl=1, indent=1,
                            tidy_mark=0, input_encoding='utf8',
                            output_encoding='utf8', doctype='auto',
                            wrap=0, char_encoding='utf8')
        html = tidy.parseString(html, **tidy_options)
        # Replace nbsp with entity:
        # http://www.mail-archive.com/[email protected]/msg03670.html
        html = str(html).replace("&nbsp;", "&#160;")
        # Tidy creates newlines after <pre> (by indenting)
        html = re.sub('<pre([^>]*)>\n', '<pre\\1>', html)
        return html
开发者ID:xfguo,项目名称:odtexportplugin,代码行数:30,代码来源:odtexport.py

示例12: _handle_builder

# 需要导入模块: from trac.mimeview.api import Context [as 别名]
# 或者: from trac.mimeview.api.Context import from_request [as 别名]
 def _handle_builder(self, req):
     m = self.BUILDER_RE.match(req.path_info)
     try:
         builder = m.group(1) or None
     except Exception as e:
         builder = None
     master = BuildBotSystem(self.buildbot_url)
     if builder is None:
         data = {'names': master.getAllBuilders()}
         return 'bbw_allbuilders.html', data, 'text/html'
     else:
         class Foo:
             pass
         b = Foo()
         b.name = str(builder)
         b.current = 'CURRENT-TEXT'
         b.recent = []
         b.slaves = []
         data = {'builder': b}
         try:
             master = BuildBotSystem(self.buildbot_url)
             data = {'builder': master.getBuilder(builder)}
         except Exception as e:
             print('Error fetching builder stats', e)
         data['context'] = Context.from_request(req, ('buildbot', builder))
         return 'bbw_builder.html', data, 'text/html'
开发者ID:rapyuta,项目名称:buildbot,代码行数:28,代码来源:web_ui.py

示例13: setup_widget

# 需要导入模块: from trac.mimeview.api import Context [as 别名]
# 或者: from trac.mimeview.api.Context import from_request [as 别名]
    def setup_widget(self, widgetns):
      r"""(Insert | update) the IWidgetProvider in the global 
      namespace.

      @param widgetns             widget name.
      @throws RuntimeError        if a widget with requested name cannot 
                                  be found.
      """
      globs = self.globalns
      globs['ctx'] = Context.from_request(globs['req'])
      globs['auth_ctx'] = Context.from_request(globs['auth_req'])
      for wp in self.dbsys.providers :
        if widgetns in set(wp.get_widgets()) :
          globs['widget'] = wp
          break
      else :
        raise InvalidIdentifier('Cannot load widget provider for %s' % widgetns)
开发者ID:Stackato-Apps,项目名称:bloodhound,代码行数:19,代码来源:__init__.py

示例14: setUp

# 需要导入模块: from trac.mimeview.api import Context [as 别名]
# 或者: from trac.mimeview.api.Context import from_request [as 别名]
 def setUp(self):
     """ Set up the testing environment. """
     self.env = EnvironmentStub(enable=[CodeExample])
     self.req = Mock(base_path='', chrome={}, args={},
                     abs_href=Href('/'), href=Href('/'),
                     session={}, perm=[], authname=None,
                     tz=None, locale='utf-8')
     self.context = Context.from_request(self.req)
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:10,代码来源:test_all.py

示例15: _get_welcome_page

# 需要导入模块: from trac.mimeview.api import Context [as 别名]
# 或者: from trac.mimeview.api.Context import from_request [as 别名]
 def _get_welcome_page(self, req):
     rendered_page = None
     wiki_welcome = WikiPage(self.env, 'WelcomePage')
     if wiki_welcome:
         context = Context.from_request(req, wiki_welcome.resource)
         wiki_renderer = WikiTextRenderer(self.env)
         rendered_page = wiki_renderer.render(context, 'text/x-trac-wiki', wiki_welcome.text)
     return rendered_page
开发者ID:alvabai,项目名称:trac-multiproject,代码行数:10,代码来源:welcome.py


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