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

Python api.TagEngine类代码示例

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

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



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

示例1: set_password

    def set_password(self, user, password):
        import re

        if len(user) < 3:
            raise TracError("user name must be at least 3 characters long")
        if not re.match(r"^\w+$", user):
            raise TracError("user name must consist only of alpha-numeric characters")
        if user not in self.get_users():
            from trac.wiki.model import WikiPage

            db = self.env.get_db_cnx()
            page = WikiPage(self.env, user, db=db)
            # User creation with existing page
            if page.exists:
                raise TracError('wiki page "%s" already exists' % user)
            else:
                from tractags.api import TagEngine

                tagspace = TagEngine(self.env).tagspace.wiki

                tagspace.add_tags(None, user, ["user"])
                page.text = """= %(user)s =\n\n[[ListTagged(%(user)s)]]\n\n[[TagIt(user)]]""" % {"user": user}
                page.save(user, "New user %s registered" % user, None)
                self.env.log.debug("New user %s registered" % user)
        HtPasswdStore.set_password(self, user, password)
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:25,代码来源:trachacks.py


示例2: process_request

    def process_request(self, req):
        from tractags.api import TagEngine
        from trac.web.chrome import add_stylesheet

        add_stylesheet(req, 'tags/css/tractags.css')

        pagename = req.args.get('page', 'WikiStart')
        action = req.args.get('action', 'view')

        engine = TagEngine(self.env)
        wikitags = engine.tagspace.wiki
        tags = list(wikitags.get_tags([pagename]))
        tags.sort()

        if action == 'edit':
            req.hdf['tags'] = req.args.get('tags', ', '.join(tags))
        elif action == 'view':
            hdf_tags = []
            for tag in tags:
                href, title = engine.get_tag_link(tag)
                hdf_tags.append({'name': tag,
                                 'href': href,
                                 'title': title})
            req.hdf['tags'] = hdf_tags
        result = WikiModule.process_request(self, req)
        if result is None:
            return None
        if result[0] == 'wiki.cs':
            return 'tagswiki.cs', None
        return result
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:30,代码来源:web_ui.py


示例3: render_listtags

    def render_listtags(self, req, *tags, **kwargs):
        """ List tags. For backwards compatibility, can accept a list of tags.
            This will simply call ListTagged. Optional keyword arguments are
            tagspace=wiki, tagspaces=(wiki, ticket, ...) and shownames=true. """
        if tags:
            # Backwards compatibility
            return self.render_listtagged(req, *tags, **kwargs)

        page = self._current_page(req)
        engine = TagEngine(self.env)

        showpages = kwargs.get('showpages', None) or kwargs.get('shownames', 'false')

        if 'tagspace' in kwargs:
            tagspaces = [kwargs['tagspace']]
        else:
            tagspaces = kwargs.get('tagspaces', []) or \
                        list(TagEngine(self.env).tagspaces)

        out = StringIO()
        out.write('<ul class="listtags">\n')
        tag_details = {}
        for tag, names in sorted(engine.get_tags(tagspaces=tagspaces, detailed=True).iteritems()):
            href, title = engine.get_tag_link(tag)
            htitle = wiki_to_oneliner(title, self.env)
            out.write('<li><a href="%s" title="%s">%s</a> %s <span class="tagcount">(%i)</span>' % (href, title, tag, htitle, len(names)))
            if showpages == 'true':
                out.write('\n')
                out.write(self.render_listtagged(req, tag, tagspaces=tagspaces))
                out.write('</li>\n')

        out.write('</ul>\n')

        return out.getvalue()
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:34,代码来源:macros.py


示例4: _update_tags

    def _update_tags(self, req, page):
        newtags = set([t.strip() for t in
                      _tag_split.split(req.args.get('tags')) if t.strip()])
        wikitags = TagEngine(self.env).tagspace.wiki
        oldtags = wikitags.get_tags([page.name])

        if oldtags != newtags:
            wikitags.replace_tags(req, page.name, newtags)
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:8,代码来源:web_ui.py


示例5: _page_titles

 def _page_titles(self, pages):
     """ Extract page titles, if possible. """
     titles = {}
     tagspace = TagEngine(self.env).tagspace.wiki
     for pagename in pages:
         href, link, title = tagspace.name_details(pagename)
         titles[pagename] = title
     return titles
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:8,代码来源:macros.py


示例6: render_listtagged

    def render_listtagged(self, req, *tags, **kwargs):
        """ List tagged objects. Optionally accepts a list of tags to match
            against.  The special tag '''. (dot)''' inserts the current Wiki page name.

            `[[ListTagged(<tag>, ...)]]`

            ||'''Argument'''||'''Description'''||
            ||`tagspace=<tagspace>`||Specify the tagspace the macro should operate on.||
            ||`tagspaces=(<tagspace>,...)`||Specify a set of tagspaces the macro should operate on.||
            ||`operation=intersection|union`||The set operation to perform on the discovered objects.||
            ||`showheadings=true|false`||List objects under the tagspace they occur in.||
        """

        if 'tagspace' in kwargs:
            tagspaces = [kwargs.get('tagspace', None)]
        else:
            tagspaces = kwargs.get('tagspaces', '') or \
                        list(TagEngine(self.env).tagspaces)
        showheadings = kwargs.get('showheadings', 'false')
        operation = kwargs.get('operation', 'intersection')
        if operation not in ('union', 'intersection'):
            raise TracError("Invalid tag set operation '%s'" % operation)

        engine = TagEngine(self.env)
        page_name = req.hdf.get('wiki.page_name')
        if page_name:
            tags = [tag == '.' and page_name or tag for tag in tags]

        taginfo = {}
        out = StringIO()
        out.write('<ul class="listtagged">')
        # Cull empty names
        tagged_names = [(tagspace, names) for tagspace, names in
                        engine.get_tagged_names(tags=tags, tagspaces=tagspaces,
                            operation=operation, detailed=True).iteritems()
                        if names]
        for tagspace, tagspace_names in sorted(tagged_names):
            if showheadings == 'true':
                out.write('<lh>%s tags</lh>' % tagspace)
            for name, tags in sorted(tagspace_names.iteritems()):
                if tagspace == 'wiki' and unicode(name).startswith('tags/'): continue
                tags = sorted(tags)
                taginfo = self._tag_details(taginfo, tags)
                href, link, title = engine.name_details(tagspace, name)
                htitle = wiki_to_oneliner(title, self.env)
                name_tags = ['<a href="%s" title="%s">%s</a>'
                              % (taginfo[tag][0], taginfo[tag][1], tag)
                              for tag in tags]
                if not name_tags:
                    name_tags = ''
                else:
                    name_tags = ' (' + ', '.join(sorted(name_tags)) + ')'
                out.write('<li>%s %s%s</li>\n' %
                          (link, htitle, name_tags))
        out.write('</ul>')

        return out.getvalue()
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:57,代码来源:macros.py


示例7: render_tagcloud

    def render_tagcloud(self, req, smallest=10, biggest=20, tagspace=None, tagspaces=[]):
        """ Display a summary of all tags, with the font size reflecting the
            number of pages the tag applies to. Font size ranges from 10 to 22
            pixels, but this can be overridden by the smallest=n and biggest=n
            macro parameters. By default, all tagspaces are displayed, but this
            can be overridden with tagspaces=(wiki, ticket) or tagspace=wiki."""
        smallest = int(smallest)
        biggest = int(biggest)
        engine = TagEngine(self.env)
        # Get wiki tagspace
        if tagspace:
            tagspaces = [tagspace]
        else:
            tagspaces = tagspaces or engine.tagspaces
        cloud = {}

        for tag, names in engine.get_tags(tagspaces=tagspaces, detailed=True).iteritems():
            cloud[tag] = len(names)

        tags = cloud.keys()

        # No tags?
        if not tags: return ''

        # by_count maps tag counts to an index in the set of counts
        by_count = list(set(cloud.values()))
        by_count.sort()
        by_count = dict([(c, float(i)) for i, c in enumerate(by_count)])

        taginfo = self._tag_details({}, tags)
        tags.sort()
        rlen = float(biggest - smallest)
        tlen = float(len(by_count))
        scale = 1.0
        if tlen:
            scale = rlen / tlen
        out = StringIO()
        out.write('<ul class="tagcloud">\n')
        last = tags[-1]
        for tag in tags:
            if tag == last:
                cls = ' class="last"'
            else:
                cls = ''
            out.write('<li%s><a rel="tag" title="%s" style="font-size: %ipx" href="%s">%s</a> <span class="tagcount">(%i)</span></li>\n' % (
                       cls,
                       taginfo[tag][1],
                       smallest + int(by_count[cloud[tag]] * scale),
                       taginfo[tag][0],
                       tag,
                       cloud[tag]))
        out.write('</ul>\n')
        return out.getvalue()
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:53,代码来源:macros.py


示例8: getDetails

    def getDetails(self, req, hack):
        """ Fetch hack details. Returns dict with name, dependencies and
            description. """
        from tractags.api import TagEngine

        wikitags = TagEngine(self.env).tagspace.wiki
        tags = wikitags.get_tags(hack)
        types = self.getTypes()
        hacks = wikitags.get_tagged_names(types)

        dependencies = hacks.intersection(tags)
        href, htmllink, description = wikitags.name_details(hack)
        return {"name": hack, "dependencies": tuple(dependencies), "description": description}
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:13,代码来源:trachacks.py


示例9: render_listtagged

    def render_listtagged(self, req, *tags, **kwargs):
        """ List tagged objects. Takes a list of tags to match against.
            The special tag '.' inserts the current Wiki page name.

            Optional keyword arguments are tagspace=wiki,
            tagspaces=(wiki, title, ...) and showheadings=true.

            By default displays the intersection of objects matching each tag.
            By passing operation=union this can be modified to display
            the union of objects matching each tag.
        """

        if 'tagspace' in kwargs:
            tagspaces = [kwargs.get('tagspace', None)]
        else:
            tagspaces = kwargs.get('tagspaces', '') or \
                        list(TagEngine(self.env).tagspaces)
        showheadings = kwargs.get('showheadings', 'false')
        operation = kwargs.get('operation', 'intersection')
        if operation not in ('union', 'intersection'):
            raise TracError("Invalid tag set operation '%s'" % operation)

        engine = TagEngine(self.env)
        page_name = req.hdf.get('wiki.page_name')
        if page_name:
            tags = [tag == '.' and page_name or tag for tag in tags]

        taginfo = {}
        out = StringIO()
        out.write('<ul class="listtagged">')
        for tagspace, tagspace_names in sorted(engine.get_tagged_names(tags=tags, tagspaces=tagspaces, operation=operation, detailed=True).iteritems()):
            if showheadings == 'true':
                out.write('<lh>%s tags</lh>' % tagspace)
            for name, tags in sorted(tagspace_names.iteritems()):
                if tagspace == 'wiki' and unicode(name).startswith('tags/'): continue
                tags = sorted(tags)
                taginfo = self._tag_details(taginfo, tags)
                href, link, title = engine.name_details(tagspace, name)
                htitle = wiki_to_oneliner(title, self.env)
                name_tags = ['<a href="%s" title="%s">%s</a>'
                              % (taginfo[tag][0], taginfo[tag][1], tag)
                              for tag in tags]
                if not name_tags:
                    name_tags = ''
                else:
                    name_tags = ' (' + ', '.join(sorted(name_tags)) + ')'
                out.write('<li>%s %s%s</li>\n' %
                          (link, htitle, name_tags))
        out.write('</ul>')

        return out.getvalue()
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:51,代码来源:macros.py


示例10: getNames

 def getNames(self, req, tagname):
     """ Returns all pages with tagname """
     engine = TagEngine(self.env)
     try:
         tagspaces = list()
         tagspaces.append(self.tagsystem.tagspace)
         tags = list()
         tags.append (tagname)
         names = engine.get_tagged_names(tags=tags,tagspaces=tagspaces)
         self.env.log.debug("getNames found %s for tagname %s"%(names, tagname))
         return list(names[self.tagsystem.tagspace])
     except Exception, e:
         self.env.log.debug('Error in getNames(%s): %s\n' % (tagname, str(e)))
         return None
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:14,代码来源:tractagsxmlrpc.py


示例11: download_deleted

    def download_deleted(self, download):
        tags = TagEngine(self.env).tagspace.downloads

        # Prepare tag names.
        self._resolve_ids(download)
        tag_names = [download['author'], download['component'],
          download['version'], download['architecture'],
          download['platform'], download['type']]
        if download['tags']:
            tag_names.extend(download['tags'].split(' '))

        # Add tags to download.
        self.log.debug(tag_names)
        tags.remove_tags(None, download['id'], list(sets.Set(tag_names)))
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:14,代码来源:tags.py


示例12: _wiki_view

    def _wiki_view(self, req, stream):
        tags = self._page_tags(req)
        if not tags:
            return stream
        engine = TagEngine(self.env)
        add_stylesheet(req, 'tags/css/tractags.css')
        li = []
        for tag in tags:
            href, title = engine.get_tag_link(tag)
            li.append(T.li(T.a(title=title, href=href)(tag), ' '))

        insert = T.ul(class_='tags')(T.lh('Tags'), li)

        return stream | Transformer('//div[@class="buttons"]').before(insert)
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:14,代码来源:web_ui.py


示例13: _do_save

    def _do_save(self, req, db, page):
        # This method is overridden so the user doesn't get "Page not modified"
        # exceptions when updating tags but not wiki content.
        from tractags.api import TagEngine
        if 'tags' in req.args:
            newtags = set([t.strip() for t in
                          _tag_split.split(req.args.get('tags')) if t.strip()])
            wikitags = TagEngine(self.env).tagspace.wiki
            oldtags = wikitags.get_tags([page.name])

            if oldtags != newtags:
                wikitags.replace_tags(req, page.name, newtags)
                # No changes, just redirect
                if req.args.get('text') == page.text:
                    req.redirect(self.env.href.wiki(page.name))
                    return
        return WikiModule._do_save(self, req, db, page)
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:17,代码来源:web_ui.py


示例14: _prepare_wiki

    def _prepare_wiki(self, req):
        from tractags.api import TagEngine
        page = req.path_info[6:] or 'WikiStart'
        engine = TagEngine(self.env)
        wikitags = engine.tagspace.wiki
        tags = list(wikitags.get_tags(page))
        tags.sort()

        action = req.args.get('action', 'view')
        if action == 'edit':
            req.hdf['tags'] = req.args.get('tags', ', '.join(tags))
        elif action == 'view':
            hdf_tags = []
            for tag in tags:
                href, title = engine.get_tag_link(tag)
                hdf_tags.append({'name': tag,
                                 'href': href,
                                 'title': title})
            req.hdf['tags'] = hdf_tags
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:19,代码来源:web_ui.py


示例15: getHacks

    def getHacks(self, req, release, type):
        """ Fetch a list of hacks for Trac release, of type. """
        from trac.versioncontrol.api import Node
        from tractags.api import TagEngine

        repo = self.env.get_repository(req.authname)
        wikitags = TagEngine(self.env).tagspace.wiki
        repo_rev = repo.get_youngest_rev()
        releases = wikitags.get_tagged_names([release])
        types = wikitags.get_tagged_names([type])
        for plugin in releases.intersection(types):
            if plugin.startswith("tags/"):
                continue
            path = "%s/%s" % (plugin.lower(), release)
            rev = 0
            if repo.has_node(str(path), repo_rev):
                node = repo.get_node(path)
                rev = node.rev
            yield (plugin, rev)
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:19,代码来源:trachacks.py


示例16: setUp

 def setUp(self):
     self.env = EnvironmentStub(default_data=True)
     self.env.path = '/'
     self.tag_engine = TagEngine(self.env)
     self.tag_engine.upgrade_environment(self.env.get_db_cnx())
     # Insert some test tickets
     from trac.ticket.model import Ticket
     for id in (1, 2, 3):
         ticket = Ticket(self.env)
         ticket['summary'] = 'Test ticket %i' % id
         ticket['description'] = 'Test ticket %i description' % id
         ticket.insert()
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:12,代码来源:test.py


示例17: render_listtags

    def render_listtags(self, req, *tags, **kwargs):
        """ List all tags.

            ||'''Argument'''||'''Description'''||
            ||`tagspace=<tagspace>`||Specify the tagspace the macro should operate on.||
            ||`tagspaces=(<tagspace>,...)`||Specify a set of tagspaces the macro should operate on.||
            ||`shownames=true|false`||Whether to show the objects that tags appear on ''(long)''.||
            """

        if tags:
            # Backwards compatibility
            return self.render_listtagged(req, *tags, **kwargs)

        page = self._current_page(req)
        engine = TagEngine(self.env)

        showpages = kwargs.get('showpages', None) or kwargs.get('shownames', 'false')

        if 'tagspace' in kwargs:
            tagspaces = [kwargs['tagspace']]
        else:
            tagspaces = kwargs.get('tagspaces', []) or \
                        list(TagEngine(self.env).tagspaces)

        out = StringIO()
        out.write('<ul class="listtags">\n')
        tag_details = {}
        for tag, names in sorted(engine.get_tags(tagspaces=tagspaces, detailed=True).iteritems()):
            href, title = engine.get_tag_link(tag)
            htitle = wiki_to_oneliner(title, self.env)
            out.write('<li><a href="%s" title="%s">%s</a> %s <span class="tagcount">(%i)</span>' % (href, title, tag, htitle, len(names)))
            if showpages == 'true':
                out.write('\n')
                out.write(self.render_listtagged(req, tag, tagspaces=tagspaces))
                out.write('</li>\n')

        out.write('</ul>\n')

        return out.getvalue()
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:39,代码来源:macros.py


示例18: setUp

 def setUp(self):
     self.env = EnvironmentStub(default_data=True)
     from trac.log import logger_factory
     self.env.log =logger_factory(logtype='syslog', logfile=None, level='DEBUG', logid='Trac', format=None)
     
     self.env.path = '/'
     self.wiki_tag_rpc_engine = WikiTagRPCSystem(self.env)
     self.ticket_tag_rpc_engine = TicketTagRPCSystem(self.env)
     self.tag_engine = TagEngine(self.env)
     self.tag_engine.upgrade_environment(self.env.get_db_cnx())
     self.xml_rpc_system = XMLRPCSystem(self.env)
                      
     
     # Insert some test tickets
     from trac.ticket.model import Ticket
     for id in (1, 2, 3):
         ticket = Ticket(self.env)
         ticket['summary'] = 'Test ticket %i' % id
         ticket['description'] = 'Test ticket %i description' % id
         ticket.insert()
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:20,代码来源:test.py


示例19: _generate_blog

    def _generate_blog(self, req, *args, **kwargs):
        """Extract the blog pages and fill the HDF.

        *args is a list of tags to use to limit the blog scope
        **kwargs are any aditional keyword arguments that are needed
        """
        tallies = {}
        tags = TagEngine(self.env).tagspace.wiki
        try:
            union = kwargs['union']
        except KeyError:
            union = False
        # Formatting
        read_post = "[wiki:%s Read Post]"
        entries = {}
        if not len(args):
            tlist = [self.env.config.get('blog', 'default_tag', 'blog')]
        else:
            tlist = args
        if union:
            blog = tags.get_tagged_names(tlist, operation='union')
        else:
            blog = tags.get_tagged_names(tlist, operation='intersection')
        macropage = req.args.get('page', None)

        poststart, postend, default_times = self._get_time_range(req, **kwargs)
        mark_updated = self._choose_value('mark_updated', req, kwargs, 
                                          convert=bool_val)
        if not mark_updated and (not isinstance(mark_updated, bool)):
            mark_updated = bool_val(self.env.config.get('blog', 'mark_updated',
                                                         True))
        macro_bl = self.env.config.get('blog', 'macro_blacklist', '').split(',')
        macro_bl = [name.strip() for name in macro_bl if name.strip()]
        macro_bl.append('BlogShow')

        # Get the email addresses of all known users and validate the "poster"
        # BlogShow optional argument at the same time (avoids looping the user
        # list twice).
        is_poster = None
        limit_poster = self._choose_value('poster', req, kwargs, convert=None)
        email_map = {}
        for username, name, email in self.env.get_known_users():
            if email:
                email_map[username] = email
            if limit_poster != None:
                if username == limit_poster:
                    is_poster = username

                       
        num_posts = self._choose_value('num_posts', req, kwargs, convert=int)
        if num_posts and default_times:
            poststart = sys.maxint
            postend = 0
        for blog_entry in blog:
            if blog_entry == macropage:
                continue
            try:
                page = WikiPage(self.env, version=1, name=blog_entry)
                version, post_time, author, comment, ipnr = page.get_history(
                                                            ).next()
                # if we're limiting by poster, do so now so that the calendar
                # only shows the number of entries the specific poster made.
                if is_poster != None:
                    if is_poster != author:
                        continue

                self._add_to_tallies(tallies, post_time, blog_entry)
                page = WikiPage(self.env, name=blog_entry)
                version, modified, author, comment, ipnr = page.get_history(
                                                           ).next()
            except:
                self.log.debug("Error loading wiki page %s" % blog_entry, exc_info=True)
                continue
            if poststart >= post_time >= postend:       
                time_format = self.env.config.get('blog', 'date_format') \
                              or '%x %X'
                timeStr = format_datetime(post_time, format=time_format) 
                fulltext = page.text
                # remove comments in blog view:
                del_comments = re.compile('==== Comment.*\Z', re.DOTALL)
                fulltext = del_comments.sub('', fulltext)
                # remove the [[AddComment...]] tag, otherwise it would appeare
                # more than one and crew up the blog view:
                del_addcomment  = re.compile('\[\[AddComment.*\Z', re.DOTALL)
                fulltext = del_addcomment.sub('', fulltext)
                # limit length of preview:
                post_size = self._choose_value('post_size', req, kwargs, int)
                if not post_size and (not isinstance(post_size, int)):
                    post_size = int(self.env.config.get('blog', 'post_size', 
                                    1024))
                text = self._trim_page(fulltext, blog_entry, post_size)
                pagetags = [x for x in tags.get_name_tags(blog_entry) if x not in tlist]
                tagtags = []
                for i, t in enumerate(pagetags[:3]):
                    d = { 'link' : t,
                          'name' : t,
                          'last' : i == (len(pagetags[:3]) - 1),
                        }
                    tagtags.append(d)
                    continue
#.........这里部分代码省略.........
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:101,代码来源:web_ui.py


示例20: _do_actions

    def _do_actions(self, req, cursor, modes, component, version):
        for mode in modes:
            if mode == "get-file":
                req.perm.assert_permission("SCREENSHOTS_VIEW")

                # Get screenshot
                match = re.match(r"""^/screenshots/(\d+)/(small|medium|large)$""", req.path_info)
                if match:
                    id = match.group(1)
                    size = match.group(2)
                screenshot = self.api.get_screenshot(cursor, id)

                # Return screenshots image action.
                file = screenshot["%s_file" % (size,)]
                path = os.path.join(self.path, str(screenshot["id"]), file)
                self.log.debug("file: %s" % (file,))
                self.log.debug("path: %s" % (path,))
                type = mimetypes.guess_type(path)[0]
                req.send_file(path, type)

            elif mode == "add":
                req.perm.assert_permission("SCREENSHOTS_ADMIN")

            elif mode == "post-add":
                req.perm.assert_permission("SCREENSHOTS_ADMIN")

                # Get form values.
                new_name = Markup(req.args.get("name"))
                new_description = Markup(req.args.get("description"))
                new_author = req.authname
                file, filename = self._get_file_from_req(req)
                content = file.read()
                new_tags = req.args.get("tags")
                new_components = req.args.get("components")
                if not isinstance(new_components, list):
                    new_components = [new_components]
                new_versions = req.args.get("versions")
                if not isinstance(new_versions, list):
                    new_versions = [new_versions]

                # Check form values
                if not new_components or not new_versions:
                    raise TracError("You must select at least one component" " and version.")

                # Check correct file type.
                reg = re.compile(r"^(.*)[.](.*)$")
                result = reg.match(filename)
                if result:
                    if not result.group(2).lower() in self.ext.split(" "):
                        raise TracError("Unsupported uploaded file type.")
                else:
                    raise TracError("Unsupported uploaded file type.")

                # Prepare images filenames.
                large_filename = re.sub(reg, r"\1_large.\2", filename)
                medium_filename = re.sub(reg, r"\1_medium.\2", filename)
                small_filename = re.sub(reg, r"\1_small.\2", filename)

                # Add new screenshot.
                screenshot_time = int(time.time())
                self.api.add_screenshot(
                    cursor,
                    new_name,
                    new_description,
                    screenshot_time,
                    new_author,
                    new_tags,
                    large_filename,
                    medium_filename,
                    small_filename,
                )

                # Get inserted screenshot.
                screenshot = self.api.get_screenshot_by_time(cursor, screenshot_time)
                self.id = screenshot["id"]

                # Add components and versions to screenshot.
                for new_component in new_components:
                    self.api.add_component(cursor, screenshot["id"], new_component)
                for new_version in new_versions:
                    self.api.add_version(cursor, screenshot["id"], new_version)

                # Create screenshot tags.
                if is_tags:
                    tags = TagEngine(self.env).tagspace.screenshots
                    tag_names = new_components
                    tag_names.extend(new_versions)
                    tag_names.extend([screenshot["name"], screenshot["author"]])
                    if screenshot["tags"]:
                        tag_names.extend(screenshot["tags"].split(" "))
                    tags.replace_tags(req, screenshot["id"], tag_names)

                # Prepare file paths
                path = os.path.join(self.path, str(self.id))
                large_filepath = os.path.join(path, large_filename)
                medium_filepath = os.path.join(path, medium_filename)
                small_filepath = os.path.join(path, small_filename)
                self.log.debug("large_filepath: %s" % (large_filepath,))
                self.log.debug("medium_filepath: %s" % (medium_filepath,))
                self.log.debug("small_filepath: %s" % (small_filepath,))
#.........这里部分代码省略.........
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:101,代码来源:core.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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