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

Python formatter.wiki_to_html函数代码示例

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

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



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

示例1: render_admin_panel

    def render_admin_panel(self, req, cat, page, path_info):
        """ main request handler
        """
        if TESTER_PERMISSION in req.perm:
            #template data
            data = dict()
            data["info"] = req.args.get("info", "")
            data["warning"] = req.args.get("warning", "")
            data["error"] = req.args.get("error", "")
            data["display_status"] = get_display_states(self)
            data["id"] = req.args.get("path_info", None)
            data["page"] = 'TestManager_accordion.html'

            data["url"] = req.abs_href + req.path_info
            # get the testcase

            data['priorities'] = self.get_priorities()
            data['default_priority'] = self.get_default_priority()
            if data["id"]:
                try:
                    testcase = models.TestCaseQuery(
                        self.env,
                        tcid=data['id']
                    ).execute()[0]
                    for action in testcase.actions:
                        action.color = {
                            "style": ("background:%s"
                                      % get_status_color(action.status))
                        }
                    data["TestCaseTitle"] = testcase.title.strip('=')
                    data["TestCaseDescription"] = testcase.description
                    data["TestCaseActions"] = testcase.actions
                    data["revision"] = testcase.revision
                    data["title"] = '(%s) ' % testcase.tcid + testcase.wiki
                    # XXX: we have to fix this in 1.0 because
                    #      wiki_to_html is deprecated
                    for action in testcase.actions:
                        action.description = wiki_to_html(
                            action.description, self.env, req)
                        action.expected_result = wiki_to_html(
                            "''Result:''[[BR]]" + action.expected_result,
                            self.env, req)
                        for comment in action.comments:
                            comment["text"] = wiki_to_html(
                                comment["text"], self.env, req)
                    if req.authname != testcase.tester:
                        # assigned to someone else
                        # but can be done by mr urlaubsvertretung
                        data["warning"] = 'this testcase %s %s' % (
                            'has been assigned to',
                            testcase.tester)
                except TracError:
                    # not found
                    data["error"] = '%s %s %s' % ('the requested testcase ',
                                                  'could not be found or has',
                                                  'been erased')
            return data["page"], data
开发者ID:InQuant,项目名称:TracTestManager,代码行数:57,代码来源:TestManager.py


示例2: get_timeline_events

    def get_timeline_events(self, req, start, stop, filters):
        # timeline动作的输入
        if 'wiki' in filters:
            wiki = WikiSystem(self.env)
            format = req.args.get('format')
            href = format == 'rss' and req.abs_href or req.href
            db = self.env.get_db_cnx()
            cursor = db.cursor()
            cursor.execute("SELECT time,name,comment,author,version "
                           "FROM wiki WHERE time>=%s AND time<=%s",
                           (start, stop))
            for t,name,comment,author,version in cursor:
                title = Markup('<em>%s</em> '+ u"编辑者 %s",
                               wiki.format_page_name(name), author)
                diff_link = html.A(u'变化', href=href.wiki(name, action='diff',
                                                          version=version))
                if format == 'rss':
                    comment = wiki_to_html(comment or '--', self.env, req, db,
                                           absurls=True)
                else:
                    comment = wiki_to_oneliner(comment, self.env, db,
                                               shorten=True)
                if version > 1:
                    comment = Markup('%s (%s)', comment, diff_link)
                yield 'wiki', href.wiki(name), title, t, author, comment

            # Attachments
            att = AttachmentModule(self.env)
            for event in att.get_timeline_events(req, db, 'wiki', format,
                                                 start, stop,
                                                 lambda id: html.EM(id)):
                yield event
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:32,代码来源:web_ui.py


示例3: _wikitext_to_html

    def _wikitext_to_html(self, req, wikitext):

        # htmldoc doesn't support utf-8, we need to use some other input encoding
        codepage = self.env.config.get('trac', 'charset', 'iso-8859-1')
        base_dir = self.env.config.get('wikitopdf', 'base_dir')

        # modify wiki text
        for r in EXCLUDE_RES:
                wikitext = r.sub('', wikitext)
            
        # convert wiki text to html...
        page = wiki_to_html(wikitext, self.env, req).encode(codepage, 'replace')

        # .. and clean up html
        imgpos = page.find('<img')
        while imgpos != -1:
                addrpos = page.find('src=', imgpos)
                base_dir = base_dir.encode('ascii')
                page = page[:addrpos+5] + base_dir + page[addrpos+5:]
                imgpos = page.find('<img', addrpos)

        page = page.replace('attachment', 'attachments')
        page = page.replace('?format=raw','')
        page = page.replace('<pre class="wiki">', '<table align="center" width="95%" border="1" bordercolor="#d7d7d7"><tr>'
                                                + '<td bgcolor="#f7f7f7"><pre class="wiki">')
        page = page.replace('</pre>', '</pre></td></tr></table>')
        page = page.replace('<table class="wiki">', '<table class="wiki" border="1" width="100%">')

        self.log.debug('WikitoPDF => Page text is: %r', page)
        return page
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:30,代码来源:wikitopdf.py


示例4: expand_macro

    def expand_macro(self, formatter, name, args):
        req = formatter.req
        add_stylesheet(req, 'hacks/css/trachacks.css')

        tag_system = TagSystem(self.env)
        releases = natural_sort([r.id for r, _ in
                                 tag_system.query(req, 'realm:wiki release')])

        def link(resource):
            return render_resource_link(self.env, formatter.context,
                                        resource, 'compact')

        dl = builder.dl(class_='tracreleasesmacro')
        for release in releases:
            page = WikiPage(self.env, release)
            match = self.title_extract.search(page.text)
            if match:
                rel_title = '%s' % match.group(1).strip()
            else:
                rel_title = '%s' % release

            dl(builder.dt(link(Resource('wiki', release))))
            dl(builder.dd(wiki_to_html(rel_title, self.env, req)))

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


示例5: __process_div_projects_milestones

    def __process_div_projects_milestones(self,milestones,div_milestones_array, req):
        project = self._map_milestones_to_projects(milestones)
        hide = smp_settings(req, 'roadmap', 'hide')
        show_proj_descr = False
        if hide is None or 'projectdescription' not in hide:
            show_proj_descr = True

        div_projects_milestones = ''
        
        for a in sorted(project.keys()):
            if(a == "--None Project--"):
                div_project = '<br><div id="project"><fieldset><legend><h2>No Project</h2></legend>'
            else:
                project_info = self.__SmpModel.get_project_info(a)
                div_project = '<br><div id="project"><fieldset><legend><b>Project </b> <em style="font-size: 12pt; color: black;">%s</em></legend>' % a
                if project_info and show_proj_descr:
                    div_project = div_project + '<div class="description" xml:space="preserve">'
                    if project_info[2]:
                        div_project = div_project + '%s<br/><br/>' % project_info[2]
                    
                    div_project = div_project + '%s</div>' % wiki_to_html(project_info[3], self.env, req)

            div_milestone = ''
            
            if len(project[a]) > 0:
                for b in project[a]:
                    mi = '<em>%s</em>' % b
                    for i in range(len(div_milestones_array)):
                        if(div_milestones_array[i].find(mi)>0):
                            div_milestone = div_milestone + div_milestones_array[i]
                div_project = div_project + to_unicode(div_milestone) + '</fieldset></div>'
                div_projects_milestones = to_unicode(div_projects_milestones + div_project)

        stream_div_projects_milestones = HTML(div_projects_milestones)
        return stream_div_projects_milestones
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:35,代码来源:roadmap.py


示例6: convert_content

 def convert_content(self, req, input_type, source, output_type):
     hfile, hfilename = mkstemp("tracpdf")
     # htmldoc doesn't support utf-8, we need to use some other input encoding
     codepage = self.env.config.get("trac", "charset", "iso-8859-1")
     self.env.log.debug("HTML output for PageToPDF in charset %s" % codepage)
     page = wiki_to_html(source, self.env, req).encode(codepage, "replace")
     page = re.sub(
         '<img src="(?!\w+://)', '<img src="%s://%s:%d' % (req.scheme, req.server_name, req.server_port), page
     )
     meta = ('<meta http-equiv="Content-Type" content="text/html; charset=%s"/>' % codepage).encode(codepage)
     os.write(hfile, "<html><head>" + meta + "</head><body>" + page + "</body></html>")
     os.close(hfile)
     pfile, pfilename = mkstemp("tracpdf")
     os.close(pfile)
     os.environ["HTMLDOC_NOCGI"] = "yes"
     htmldoc_args = {
         "webpage": None,
         "format": "pdf14",
         "left": "1.5cm",
         "right": "1.5cm",
         "top": "1.5cm",
         "bottom": "1.5cm",
         "charset": codepage,
     }
     htmldoc_args.update(dict(self.env.config.options("pagetopdf")))
     args_string = " ".join(["--%s %s" % (arg, value or "") for arg, value in htmldoc_args.iteritems()])
     self.env.log.debug(args_string)
     os.system("htmldoc %s %s -f %s" % (args_string, hfilename, pfilename))
     out = open(pfilename, "rb").read()
     os.unlink(pfilename)
     os.unlink(hfilename)
     return (out, "application/pdf")
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:32,代码来源:pagetopdf.py


示例7: expand_macro

    def expand_macro(self, formatter, name, content):
        req = formatter.req
        args, kwargs = parse_args(content)
        args += [None, None]
        path, limit, rev = args[:3]
        limit = kwargs.pop('limit', limit)
        rev = kwargs.pop('rev', rev)

        if 'CHANGESET_VIEW' not in req.perm:
            return Markup('<i>Changelog not available</i>')

        repo = self.env.get_repository(req.authname)

        if rev is None:
            rev = repo.get_youngest_rev()
        rev = repo.normalize_rev(rev)
        path = repo.normalize_path(path)
        if limit is None:
            limit = 5
        else:
            limit = int(limit)
        node = repo.get_node(path, rev)
        out = StringIO()
        out.write('<div class="changelog">\n')
        for npath, nrev, nlog in node.get_history(limit):
            change = repo.get_changeset(nrev)
            datetime = format_datetime(change.date, '%Y/%m/%d %H:%M:%S', req.tz)
            out.write(wiki_to_html("'''[%s] by %s on %s'''\n\n%s" %
                (nrev, change.author, datetime, change.message),
                                   self.env, req));
        out.write('</div>\n')
        return out.getvalue()
开发者ID:lkraav,项目名称:trachacks,代码行数:32,代码来源:ChangeLogMacro.py


示例8: process_admin_request

    def process_admin_request(self, req, cat, page, path_info):
        assert req.perm.has_permission('BLOG_ADMIN')

        add_stylesheet(req, 'blog/css/blog.css')
        add_stylesheet(req, 'common/css/wiki.css')

        req.hdf['blogadmin.page'] = page

        admin_fields = {
                        'date_format'    : '%x %X',
                        'page_format'    : '%Y/%m/%d/%H.%M',
                        'default_tag'    : 'blog', 
                        'post_size'      : 1024,
                        'history_days'   : 30,
                        'new_blog_link'  : 'New Blog Post',
                        'first_week_day' : 'SUNDAY',
                        'mark_updated'   : 'true',
                        'nav_link'       : 'Blog',
                        'nav_bar'        : 'true',
                        'macro_blacklist': '',
                        'rss'            : 'true',
                       }
        if req.method == 'POST':
            if page == 'defaults':
                for field in admin_fields.keys():
                    self._set_field_value(req, field)
                self.env.config.save()
        for field, default in admin_fields.items():
            self._get_field_value(req, field, default)
        req.hdf['blogadmin.docs'] = wiki_to_html(self._get_docs(page),
                                                 self.env, req)
        return 'blog_admin.cs', None
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:32,代码来源:admin.py


示例9: addHref

 def addHref(userProfile):
     userProfile.href=req.href.admin(cat,page,userProfile.id)
     userProfile.role = userProfile.role or "[blank]"
     userProfile.name = userProfile.name or "[blank]"
     userProfile.email = userProfile.email or "[blank]"
     userProfile.bio_html = wiki_to_html(userProfile.bio, self.env, req) or "[blank]"
     return userProfile
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:7,代码来源:admin.py


示例10: expand_macro

	def expand_macro(self, formatter, name, args):
		if args is None:
			return "No diagram text defined!"

		diagramText = str(args).strip()
		
		# First, encode the data.
		data = urllib.urlencode({"message" : diagramText, "style" : self.style, "paginate" : 0, "paper" : "letter", "landscape" : 0, "page" : 1, "format" : "png"})
		# Now get that file-like object again, remembering to mention the data.
		f = urllib.urlopen("http://www.websequencediagrams.com/index.php", data)
		# Read the results back.
		s = f.read()
		f.close()
		
		s = s[1:-1]
		seqargs = s.split(",")
		locargs = seqargs[0].split(":")
		loc = locargs[1].strip()
		loc = loc[1:-1]
		
		s = StringIO()
		s.write("{{{\n")
		s.write("#!html\n")
		s.write("<img src='http://www.websequencediagrams.com/%s'>" % loc)
		s.write("\n}}}\n")
		v = s.getvalue()
		s.close()
		
		return wiki_to_html(v, self.env, formatter.req)
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:29,代码来源:macro.py


示例11: _build_html_changelog

 def _build_html_changelog(self, req, changed_tickets):
     html_changes = None
     if len(changed_tickets) > 0:
         ticket_changes = u''
         for ticket in changed_tickets:
             ticket_changes += u' * #%d %s\n' % (ticket.id, ticket[Key.SUMMARY])
         html_changes = wiki_to_html(ticket_changes, self.env, req)
     return html_changes
开发者ID:djangsters,项目名称:agilo,代码行数:8,代码来源:web_ui.py


示例12: expand_macro

	def expand_macro(self, formatter, name, args):
		if args is None:
			return "No query defined!"

		sql = str(args).strip()

		db = Connection(self.uri)
		try:
			records = db.do(sql)
		finally:
			db.rollback()
			db.close()

		if records:
			headers = []
			fields = [x for x in records[0].keys() if not x.startswith("__") and not x.endswith("__")]
			for field in fields:
				headers.append(Header(field))

			groups = OrderedDict()
			for record in records:
				style = ""

				if record.has_key("__color__"):
					style += "background-color: %s" % record["__color__"]
					record.remove("__color__")
				
				if record.has_key("__group__"):
					group = record["__group__"]
					record.remove("__group__")					
					row = Row([Cell(v) for v in record.values()],
						style=style)
					if not groups.has_key(group):
						groups[group] = []
					groups[group].append(row)
				else:
					row = Row([Cell(v) for v in record.values()],
						style=style)
					if not groups.has_key(None):
						groups[None] = []
					groups[None].append(row)

			s = StringIO()
			for group, rows in groups.iteritems():
				t = Table(headers, rows, cls="wiki")
				t.refresh()
				if group:
					s.write("=== %s ===\n" % group)
				s.write("{{{\n")
				s.write("#!html\n")
				s.write(t.toHTML())
				s.write("\n}}}\n")

			v = s.getvalue()
			s.close()
			return wiki_to_html(v, self.env, formatter.req)
		else:
			return "No results"
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:58,代码来源:macro.py


示例13: process_request

    def process_request(self, req):
        req.hdf['trac.href.blog'] = req.href.blog()

        entries = []
        for page_name in WikiSystem(self.env).get_pages(prefix='Blog'):
            page = WikiPage(self.env, page_name)
            title = page_name
            text = page.text

            match = title_split_match(page.text)
            if match:
                title = match.group(1)
                text = match.group(2)

            comments = text.count('[[SimpleBlogComment(')
            cutoff = text.find('[[SimpleBlogComment(')
            if cutoff >= 0:
                text = text[:cutoff].rstrip()
            description = wiki_to_html(text, self.env, req)

            original = self._get_original_post_info(page_name)
            event = {
                'href': self.env.href.wiki(page_name),
                'title': title,
                'description': description,
                'escaped': Markup.escape(unicode(description)),
                'date': format_datetime(original['time']),
                'rfcdate': http_date(original['time']),
                'author': original['author'],
                'comment': original['comment'],
                'comments': comments,
                }
            if page.version > 1:
                event['updated.version'] = page.version
                event['updated.date'] = format_datetime(page.time)
                event['updated.rfcdate'] = http_date(page.time)
                event['updated.author'] = page.author
                event['updated.comment'] = page.comment
            entries.append((original['time'], event))

        entries.sort()
        entries.reverse()
        max_count = 20
        if len(entries) > max_count:
            entries = entries[:max_count]

        events = []
        for date, event in entries:
            events.append(event)
        req.hdf['blog.events'] = events

        format = req.args.get('format')
        if format == 'rss':
            return 'blog_rss.cs', 'application/rss+xml'

        add_link(req, 'alternate', self.env.href.blog(format='rss'),
                 'RSS Feed', 'application/rss+xml', 'rss')
        return 'blog.cs', None
开发者ID:Adel-Magebinary,项目名称:browsershots,代码行数:58,代码来源:__init__.py


示例14: _render_editor

    def _render_editor(self, req, page, db, preview=False):
        blogtitle = req.args.get('blogtitle')
        titleline = ' '.join(["=", blogtitle, "=\n"])
        if req.args.has_key('text'):
            page.text = req.args.get('text')
        if preview:
            page.readonly = req.args.has_key('readonly')

        author = req.authname
        comment = req.args.get('comment', '')
        editrows = req.args.get('editrows')
        tags = req.args.get('tags')
        req.hdf['tags'] = tags
        if editrows:
            pref = req.session.get('wiki_editrows', '20')
            if editrows != pref:
                req.session['wiki_editrows'] = editrows
        else:
            editrows = req.session.get('wiki_editrows', '20')

        req.hdf['title'] = page.name + ' (edit)'
        info = {
            'title' : blogtitle,
            'pagename': page.name,
            'page_source': page.text,
            'author': author,
            'comment': comment,
            'readonly': page.readonly,
            'edit_rows': editrows,
            'scroll_bar_pos': req.args.get('scroll_bar_pos', '')
        }
        if preview:
            if blogtitle:
                info['page_html'] = wiki_to_html(''.join([titleline, 
                                                 req.args.get('text'), 
                                                 "\n\n",self.variable_substitution(req,self.env.config.get('blog', 'footer', ''))]), 
                                                self.env, req, db)
            else:
                info['page_html'] = wiki_to_html(page.text.join(["\n\n",
                    self.variable_substitution(req,self.env.config.get('blog', 'footer', ''))]), 
                                                  self.env, 
                                                  req, 
                                                  db) 
            info['readonly'] = int(req.args.has_key('readonly'))
        req.hdf['blog'] = info
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:45,代码来源:new_blog.py


示例15: expand_macro

  def expand_macro(self, formatter, names, content):
    if not content:
      edit = ''
      text = "''Gringlet Name Missing''"
      acl = ''
    elif not re.match(r'^[a-zA-Z0-9]+$', content):
      edit = ''
      text = tag.em("Invalid Gringlet Name - only letters and numbers allowed")
      acl = ''
    else:
      db = self.env.get_db_cnx()
      cursor = db.cursor()
      cursor.execute('SELECT text,acl FROM gringotts WHERE name=%s AND version='
                     '(SELECT MAX(version) FROM gringotts WHERE name=%s)',
                     (content, content))

    try:
      text,acl = cursor.fetchone()
      key = str(self.config.get('gringotts', 'key'))
      k = ezPyCrypto.key(key)
      text = wiki_to_html(k.decStringFromAscii(text), self.env, formatter.req)
      edit = 'Edit'
    except:
      edit = 'Create'
      text = tag.em("No Gringlet called \"%s\" found" % content)
      acl = ''
    
    if acl:
      if not validate_acl(formatter.req, acl):
        text = tag.em("You do not have permission to view the \"%s\" Gringlet." % content)
        edit = ''
    
    control = None
    if edit:
      control = tag.div(tag.a(edit, href=(formatter.href.gringotts() + "/" + content + "?action=edit")), class_="gringottcontrol")
    
    
    # Use eight divs for flexible frame styling
    return tag.div(
            tag.div(
             tag.div(
              tag.div(
               tag.div(
                tag.div(
                 tag.div(
                  tag.div(
                   tag.div(text, class_="gringottcontent") + control,
                  class_="gringott"),
                 class_="gringott"),
                class_="gringott"),
               class_="gringott"),
              class_="gringott"),
             class_="gringott"),
            class_="gringott"),
           class_="gringottframe")
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:55,代码来源:wiki.py


示例16: get_macro_descr

 def get_macro_descr():
     for macro_provider in wiki.macro_providers:
         for macro_name in macro_provider.get_macros():
             if content and macro_name != content:
                 continue
             try:
                 descr = macro_provider.get_macro_description(macro_name)
                 descr = wiki_to_html(descr or "", self.env, req)
             except Exception, e:
                 descr = Markup(system_message("Error: Can't get description for macro %s" % macro_name, e))
             yield (macro_name, descr)
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:11,代码来源:macros.py


示例17: wiki2html

 def wiki2html( self, myinput ):
   '''
     transform wiki markup to HTML code
   '''
   if type(myinput) == datetime.date:
     mystring = self.getNormalizedDateStringOfDate(myinput)
   elif type(myinput) == datetime:
     mystring = self.getNormalizedDateTimeStringOfDate(myinput)
   else:
     mystring = myinput
   
   return wiki_to_html(mystring, self.macroenv.tracenv, self.macroenv.tracreq)
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:12,代码来源:pprenderimpl.py


示例18: render_macro

    def render_macro(self, req, name, content):
        # args will be null if the macro is called without parenthesis.
        if not content:
            edit = ''
            text = "''Gringlet Name Missing''"
            acl = ''
        elif not re.match(r'^[a-zA-Z0-9]+$', content):
            edit = ''
            text = "<em>Invalid Gringlet Name - only letters and numbers allowed</em>"
            acl = ''
        else:
            db = self.env.get_db_cnx()
            cursor = db.cursor()
            cursor.execute('SELECT text,acl FROM gringotts WHERE name=%s AND version='
                           '(SELECT MAX(version) FROM gringotts WHERE name=%s)',
                           (content, content))

            try:
                text,acl = cursor.fetchone()
                key = str(self.config.get('gringotts', 'key'))
                k = ezPyCrypto.key(key)
                text = wiki_to_html(k.decStringFromAscii(text), self.env, req)
                edit = 'Edit'
            except:
                edit = 'Create'
                text = "<em>No Gringlet called &quot;%s&quot; found</em>" % content
                acl = ''
                
        if acl:
            if not validate_acl(req, acl):
                text = "<em>You do not have permission to view the &quot;%s&quot; Gringlet.</em>" % content
                edit = ''

        control = ''
        if edit:
            control = ('<div class="gringottcontrol">' + \
                       '<a href="%s/%s">' + edit + '</a>' + \
                       '</div>') % (req.href.gringotts(), content)

            
        # Use eight divs for flexible frame styling
        html = '<div class="gringottframe"><div class="gringott">' + \
               '<div class="gringott"><div class="gringott">' + \
               '<div class="gringott"><div class="gringott">' + \
               '<div class="gringott"><div class="gringott">' + \
               '<div class="gringottcontent">' + \
               text + \
               '</div>' + \
               control + \
               '</div></div></div></div></div></div></div></div>'
        return html
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:51,代码来源:wiki.py


示例19: _process_request

    def _process_request(self, req):
        book, page = self._process_url(req)

        data = {
            'title': self._get_title(),
        }

        # build wiki_index
        if book == 'wiki_index':
            if page:
                text = ''
                if WikiSystem(self.env).has_page(page):
                    text = WikiPage(self.env, page).text
                else:
                    text = 'GTK-Doc index page [wiki:"%s"] does not exist.' % page
                data['wiki_content'] = wiki_to_html(text, self.env, req)
                add_ctxtnav(req, "View %s page" % page, req.href.wiki(page))
                return 'gtkdoc.html', data, 'text/html'
            else:
                raise TracError("Can't read gtkdoc content: %s" % req.path_info)

        # build content
        values = self._get_values(book)
        book_path = values[0]
        book_index = values[1]
        book_encoding = values[2]

        if not page:
            redirect_href = os.path.join(req.href.gtkdoc(), book)
            redirect_href = os.path.join(redirect_href, book_index)
            req.redirect(redirect_href)

        page = page or book_index
        path = os.path.join(book_path, page)

        mimetype, encoding = mimetypes.guess_type(path)
        encoding = encoding or \
                   book_encoding or \
                   self.env.config['trac'].get('default_charset')

        # Genshi can't include an unparsed file
        # data = {'content': path}
        if (mimetype == 'text/html'):
            try:
                content = Markup(to_unicode(file(path).read(), encoding))
            except (IOError, OSError), e:
                self.log.debug("Can't read gtkdoc content: %s" % e)
                raise TracError("Can't read gtkdoc content: %s" % req.path_info)
            data['content'] = content
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:49,代码来源:web_ui.py


示例20: convert_content

    def convert_content(self, req, input_type, source, output_type):
        #extract all data resources
        datadir = resource_filename(__name__, 'data')

        html = wiki_to_html(source, self.env, req)
	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')
	xhtml = parseString(html.encode("utf-8"), **options)

	xhtml2dbXsl = u"""<?xml version="1.0"?>
<xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:import href=\"file:///""" + urllib.pathname2url(resource_filename(__name__, 'data/html2db/html2db.xsl')) + """\" />
  <xsl:output method="xml" indent="no" encoding="utf-8"/>
  <xsl:param name="document-root" select="'chapter'"/>
</xsl:stylesheet>
"""

	normalizedHeadingsXsl = u"""<?xml version="1.0"?>
<xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:import href=\"file:///""" + urllib.pathname2url(resource_filename(__name__, 'data/headingsNormalizer/headingsNormalizer.xsl')) + """\" />
  <xsl:output method="xml" indent="no" encoding="utf-8"/>
  <xsl:param name="defaultTopHeading" select="'""" + req.path_info[6:] + """'"/>
</xsl:stylesheet>
"""

	xhtml_xmldoc = libxml2.parseDoc(str(xhtml))

	normalizedHeadingsXsl_xmldoc = libxml2.parseDoc(normalizedHeadingsXsl)
	normalizedHeadingsXsl_xsldoc = libxslt.parseStylesheetDoc(normalizedHeadingsXsl_xmldoc)
	xhtml2_xmldoc = normalizedHeadingsXsl_xsldoc.applyStylesheet(xhtml_xmldoc, None)

	nhstring = normalizedHeadingsXsl_xsldoc.saveResultToString(xhtml2_xmldoc)

	xhtml2dbXsl_xmldoc = libxml2.parseDoc(xhtml2dbXsl)
	xhtml2dbXsl_xsldoc = libxslt.parseStylesheetDoc(xhtml2dbXsl_xmldoc)
	docbook_xmldoc = xhtml2dbXsl_xsldoc.applyStylesheet(xhtml2_xmldoc, None)

	dbstring = xhtml2dbXsl_xsldoc.saveResultToString(docbook_xmldoc)

	xhtml_xmldoc.freeDoc()
	normalizedHeadingsXsl_xsldoc.freeStylesheet()
	xhtml2dbXsl_xsldoc.freeStylesheet()
	xhtml2_xmldoc.freeDoc()
	docbook_xmldoc.freeDoc()
	return (dbstring, 'text/plain') #application/docbook+xml
开发者ID:filipefigcorreia,项目名称:page2docbookplugin,代码行数:48,代码来源:pagetodocbook.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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