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

Python datefmt.pretty_timedelta函数代码示例

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

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



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

示例1: get_work_log

    def get_work_log(self, pid, username=None, mode='all'):
        db = self.env.get_read_db()
        cursor = db.cursor()
        if mode == 'user':
            assert username is not None
            cursor.execute('SELECT wl.worker, wl.starttime, wl.endtime, wl.ticket, t.summary, t.status, wl.comment '
                           'FROM work_log wl '
                           'JOIN ticket t ON wl.ticket=t.id '
                           'WHERE t.project_id=%s AND wl.worker=%s '
                           'ORDER BY wl.lastchange DESC',
                           (pid, username))
        elif mode == 'latest':
            cursor.execute('''
                SELECT worker, starttime, endtime, ticket, summary, status, comment 
                FROM (
                    SELECT wl.worker, wl.starttime, wl.endtime, wl.ticket, wl.comment, wl.lastchange,
                    MAX(wl.lastchange) OVER (PARTITION BY wl.worker) latest,
                    t.summary, t.status
                    FROM work_log wl
                    JOIN ticket t ON wl.ticket=t.id AND project_id=%s
                ) wll
                WHERE lastchange=latest
                ORDER BY lastchange DESC, worker
               ''', (pid,))
        else:
            cursor.execute('SELECT wl.worker, wl.starttime, wl.endtime, wl.ticket, t.summary, t.status, wl.comment '
                           'FROM work_log wl '
                           'JOIN ticket t ON wl.ticket=t.id '
                           'WHERE t.project_id=%s '
                           'ORDER BY wl.lastchange DESC, wl.worker',
                           (pid,))

        rv = []
        for user,starttime,endtime,ticket,summary,status,comment in cursor:
            started = to_datetime(starttime)

            if endtime != 0:
                finished = to_datetime(endtime)
                delta = 'Worked for %s (between %s and %s)' % (
                         pretty_timedelta(started, finished),
                         format_datetime(started), format_datetime(finished))
            else:
                finished = 0
                delta = 'Started %s ago (%s)' % (
                         pretty_timedelta(started),
                         format_datetime(started))

            rv.append({'user': user,
                       'starttime': started,
                       'endtime': finished,
                       'delta': delta,
                       'ticket': ticket,
                       'summary': summary,
                       'status': status,
                       'comment': comment})
        return rv
        
开发者ID:lexqt,项目名称:EduTracTicketWorklog,代码行数:56,代码来源:manager.py


示例2: milestone_to_hdf

def milestone_to_hdf(env, db, req, milestone):
    hdf = {'name': milestone.name,
           'href': req.href.milestone(milestone.name)}
    if milestone.description:
        hdf['description'] = milestone.description
    if milestone.due:
        hdf['due'] = milestone.due
        hdf['due_date'] = format_date(milestone.due)
        hdf['due_delta'] = pretty_timedelta(milestone.due + timedelta(60))
        hdf['late'] = milestone.is_late
    if milestone.completed:
        hdf['completed'] = milestone.completed
        hdf['completed_date'] = format_datetime(milestone.completed)
        hdf['completed_delta'] = pretty_timedelta(milestone.completed)
    return hdf
开发者ID:jun66j5,项目名称:TraM,代码行数:15,代码来源:roadmap.py


示例3: _render_history

    def _render_history(self, req, db, page):
        """Extract the complete history for a given page and stores it in the
        HDF.

        This information is used to present a changelog/history for a given
        page.
        """
        req.perm.assert_permission('WIKI_VIEW')

        if not page.exists:
            raise TracError, "Page %s does not exist" % page.name

        self._set_title(req, page, u'历史')

        history = []
        for version, t, author, comment, ipnr in page.get_history():
            history.append({
                'url': req.href.wiki(page.name, version=version),
                'diff_url': req.href.wiki(page.name, version=version,
                                          action='diff'),
                'version': version,
                'time': format_datetime(t),
                'time_delta': pretty_timedelta(t),
                'author': author,
                'comment': wiki_to_oneliner(comment or '', self.env, db),
                'ipaddr': ipnr
            })
        req.hdf['wiki.history'] = history
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:28,代码来源:web_ui.py


示例4: render_timeline_event

 def render_timeline_event(self, context, field, event):
     name, url, result, message, started, completed = event[3]
     if field == 'title':
         return tag('Build "', tag.em(name), '" (%s)' % result.lower())
     elif field == 'description':
         return "%s duration %s" % \
                (message, pretty_timedelta(started, completed))
     elif field == 'url':
         return url
开发者ID:akaihola,项目名称:trachacks-hudsontracplugin,代码行数:9,代码来源:HudsonTracPlugin.py


示例5: _render_link

 def _render_link(self, context, name, label, extra=''):
     if not (name or extra):
         return tag()
     try:
         milestone = Milestone(self.env, name)
     except ResourceNotFound:
         milestone = None
     # Note: the above should really not be needed, `Milestone.exists`
     # should simply be false if the milestone doesn't exist in the db
     # (related to #4130)
     href = context.href.milestone(name)
     if milestone and milestone.exists:
         if 'MILESTONE_VIEW' in context.perm(milestone.resource):
             title = None
             if hasattr(context, 'req'):
                 if milestone.is_completed:
                     title = _(
                         'Completed %(duration)s ago (%(date)s)',
                         duration=pretty_timedelta(milestone.completed),
                         date=user_time(context.req, format_datetime,
                                        milestone.completed))
                 elif milestone.is_late:
                     title = _('%(duration)s late (%(date)s)',
                               duration=pretty_timedelta(milestone.due),
                               date=user_time(context.req, format_datetime,
                                              milestone.due))
                 elif milestone.due:
                     title = _('Due in %(duration)s (%(date)s)',
                               duration=pretty_timedelta(milestone.due),
                               date=user_time(context.req, format_datetime,
                                              milestone.due))
                 else:
                     title = _('No date set')
             closed = 'closed ' if milestone.is_completed else ''
             return tag.a(label, class_='%smilestone' % closed,
                          href=href + extra, title=title)
     elif 'MILESTONE_CREATE' in context.perm(self.realm, name):
         return tag.a(label, class_='missing milestone', href=href + extra,
                      rel='nofollow')
     return tag.a(label, class_='missing milestone')
开发者ID:spsoft-RockWang,项目名称:project-_trac,代码行数:40,代码来源:roadmap.py


示例6: _pretty_dateinfo

 def _pretty_dateinfo(date, format=None, dateonly=False):
     absolute = format_datetime(date, tzinfo=req.tz)
     relative = pretty_timedelta(date)
     if format == 'absolute':
         label = absolute
         # TRANSLATOR: Sync with same msgid in Trac 0.13, please.
         title = _("%(relativetime)s ago", relativetime=relative)
     else:
         if dateonly:
             label = relative
         else:
             label = _("%(relativetime)s ago", relativetime=relative)
         title = absolute
     return tag.span(label, title=title)
开发者ID:51reboot,项目名称:huangweiyi,代码行数:14,代码来源:util.py


示例7: attachment_to_hdf

def attachment_to_hdf(env, req, db, attachment):
    if not db:
        db = env.get_db_cnx()
    hdf = {
        'filename': attachment.filename,
        'description': wiki_to_oneliner(attachment.description, env, db),
        'author': attachment.author,
        'ipnr': attachment.ipnr,
        'size': pretty_size(attachment.size),
        'time': format_datetime(attachment.time),
        'age': pretty_timedelta(attachment.time),
        'href': attachment.href(req)
    }
    return hdf
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:14,代码来源:attachment.py


示例8: _format_reminder

    def _format_reminder(self, req, ticket, id, time, author, origin, description, delete_button=True):
        now = to_datetime(None)
        time = to_datetime(time)
        if now >= time:
            when = tag(tag.strong("Right now"), " (pending)")
        else:
            when = tag("In ", tag.strong(pretty_timedelta(time)), " (", format_date(time), ")")

        if description:
            context = Context.from_request(req, ticket.resource)
            desc = tag.div(format_to_oneliner(self.env, context, description), class_="description")
        else:
            desc = tag()

        return tag(self._reminder_delete_form(req, id) if delete_button else None, when, " - added by ", tag.em(Chrome(self.env).authorinfo(req, author)), " ", tag.span(pretty_timedelta(origin), title=format_datetime(origin, req.session.get('datefmt', 'iso8601'), req.tz)), " ago.", desc)
开发者ID:trac-hacks,项目名称:trac-ticketreminder,代码行数:15,代码来源:api.py


示例9: _render_view

    def _render_view(self, req, db, page):
        page_name = self._set_title(req, page, '')
        if page.name == 'WikiStart':
            req.hdf['title'] = ''

        version = req.args.get('version')
        if version:
            # Ask web spiders to not index old versions
            req.hdf['html.norobots'] = 1

        # Add registered converters
        for conversion in Mimeview(self.env).get_supported_conversions(
                                             'text/x-trac-wiki'):
            conversion_href = req.href.wiki(page.name, version=version,
                                            format=conversion[0])
            add_link(req, 'alternate', conversion_href, conversion[1],
                     conversion[3])

        latest_page = WikiPage(self.env, page.name)
        req.hdf['wiki'] = {'exists': page.exists,
                           'version': page.version,
                           'latest_version': latest_page.version,
                           'readonly': page.readonly}
        if page.exists:
            req.hdf['wiki'] = {
                'page_html': wiki_to_html(page.text, self.env, req),
                'history_href': req.href.wiki(page.name, action='history'),
                'last_change_href': req.href.wiki(page.name, action='diff',
                                                  version=page.version)
                }
            if version:
                req.hdf['wiki'] = {
                    'comment_html': wiki_to_oneliner(page.comment or '--',
                                                     self.env, db),
                    'author': page.author,
                    'age': pretty_timedelta(page.time)
                    }
        else:
            if not req.perm.has_permission('WIKI_CREATE'):
                raise HTTPNotFound('Page %s not found', page.name)
            req.hdf['wiki.page_html'] = html.P(u'创建 "%s" ' % page_name)

        # Show attachments
        req.hdf['wiki.attachments'] = attachments_to_hdf(self.env, req, db,
                                                         'wiki', page.name)
        if req.perm.has_permission('WIKI_MODIFY'):
            attach_href = req.href.attachment('wiki', page.name)
            req.hdf['wiki.attach_href'] = attach_href
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:48,代码来源:web_ui.py


示例10: attachment_to_hdf

def attachment_to_hdf(env, req, db, attachment):
    """
    This function have been removed from 0.11, this is copied from 0.10, then modified to 
    work with 0.11
    """
    if not db:
        db = env.get_db_cnx()
    hdf = {
        'filename': attachment.filename,
        'description': wiki_to_oneliner(attachment.description, env, db, req=req),
        'author': attachment.author,
        'ipnr': attachment.ipnr,
        'size': pretty_size(attachment.size),
        'time': format_datetime(attachment.date),
        'age': pretty_timedelta(attachment.date),
        'href': AttachmentModule(env).get_resource_url(attachment.resource, req.href)
    }
    return hdf
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:18,代码来源:web_ui.py


示例11: _process_log

 def _process_log(self, req):
     """Handle AJAX log requests"""
     try:
         rev = int(req.args['logrev'])
         repos = self.env.get_repository(req.authname)
         chgset = repos.get_changeset(rev)
         wikimsg = wiki_to_html(chgset.message, self.env, req, None, 
                                True, False)
         data = {
             'chgset': True,
             'revision': rev,
             'time': format_datetime(chgset.date),
             'age': pretty_timedelta(chgset.date, None, 3600),
             'author': chgset.author or 'anonymous',
             'message': wikimsg, 
         }
         return 'revtree_log.html', {'log': data}, 'application/xhtml+xml'
     except Exception, e:
         raise TracError, "Invalid revision log request: %s" % e
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:19,代码来源:web_ui.py


示例12: pretty_dateinfo

 def pretty_dateinfo(date, format=None, dateonly=False):
     if not date:
         return ''
     if format == 'date':
         absolute = user_time(req, format_date, date)
     else:
         absolute = user_time(req, format_datetime, date)
     now = datetime.now(localtz)
     relative = pretty_timedelta(date, now)
     if not format:
         format = req.session.get('dateinfo',
                      Chrome(self.env).default_dateinfo_format)
     if format == 'relative':
         if date > now:
             label = _("in %(relative)s", relative=relative) \
                     if not dateonly else relative
             title = _("on %(date)s at %(time)s",
                       date=user_time(req, format_date, date),
                       time=user_time(req, format_time, date))
             return tag.span(label, title=title)
         else:
             label = _("%(relative)s ago", relative=relative) \
                     if not dateonly else relative
             title = _("See timeline at %(absolutetime)s",
                       absolutetime=absolute)
     else:
         if dateonly:
             label = absolute
         elif req.lc_time == 'iso8601':
             label = _("at %(iso8601)s", iso8601=absolute)
         elif format == 'date':
             label = _("on %(date)s", date=absolute)
         else:
             label = _("on %(date)s at %(time)s",
                       date=user_time(req, format_date, date),
                       time=user_time(req, format_time, date))
         if date > now:
             title = _("in %(relative)s", relative=relative)
             return tag.span(label, title=title)
         title = _("See timeline %(relativetime)s ago",
                   relativetime=relative)
     return self.get_timeline_link(req, date, label,
                                   precision='second', title=title)
开发者ID:dafrito,项目名称:trac-mirror,代码行数:43,代码来源:web_ui.py


示例13: get_changes

def get_changes(env, repos, revs, full=None, req=None, format=None):
    db = env.get_db_cnx()
    changes = {}
    for rev in revs:
        try:
            changeset = repos.get_changeset(rev)
        except NoSuchChangeset:
            changes[rev] = {}
            continue

        wiki_format = env.config['changeset'].getbool('wiki_format_messages')
        message = changeset.message or '--'
        absurls = (format == 'rss')
        if wiki_format:
            shortlog = wiki_to_oneliner(message, env, db,
                                        shorten=True, absurls=absurls)
        else:
            shortlog = Markup.escape(shorten_line(message))

        if full:
            if wiki_format:
                message = wiki_to_html(message, env, req, db,
                                       absurls=absurls, escape_newlines=True)
            else:
                message = html.PRE(message)
        else:
            message = shortlog

        if format == 'rss':
            if isinstance(shortlog, Markup):
                shortlog = shortlog.plaintext(keeplinebreaks=False)
            message = unicode(message)

        changes[rev] = {
            'date_seconds': changeset.date,
            'date': format_datetime(changeset.date),
            'age': pretty_timedelta(changeset.date),
            'author': changeset.author or 'anonymous',
            'message': message, 'shortlog': shortlog,
        }
    return changes
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:41,代码来源:util.py


示例14: _process_log

 def _process_log(self, req):
     """Handle AJAX log requests"""
     try:
         rev = int(req.args["rev"])
         repos = self.env.get_repository(req.authname)
         chgset = repos.get_changeset(rev)
         wikimsg = wiki_to_html(chgset.message, self.env, req, None, True, False)
         # FIXME: check if there is a better way to discard ellipsis
         #        which are not valid in pure XML
         wikimsg = Markup(wikimsg.replace("...", ""))
         req.hdf["changeset"] = {
             "chgset": True,
             "revision": rev,
             "time": format_datetime(chgset.date),
             "age": pretty_timedelta(chgset.date, None, 3600),
             "author": chgset.author or "anonymous",
             "message": wikimsg,
         }
         return "revtree_log.cs", "application/xhtml+xml"
     except Exception, e:
         raise TracError, "Invalid revision log request: %s" % e
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:21,代码来源:web_ui.py


示例15: _process_log_request

    def _process_log_request(self, req):
        '''
        Process log request information.

        This method is invoked when cursor is over a RevTree changeset,
        returning corresponding revision log information.

        :param req: Trac request object
        :returns: template, template data, type of response
        '''

        try:
            rev = int(req.args['logrev'])
            repos = Repository.get_svn_repository(self.env)
            if not repos:
                raise TracError("Revtree only supports Subversion "
                                "repositories")
            chgset = repos.get_changeset(rev)
            wikimsg = wiki_to_html(to_unicode(chgset.message),
                                   self.env,
                                   req,
                                   None,
                                   True,
                                   False)
            data = {
                'chgset': True,
                'revision': rev,
                'time': format_datetime(chgset.date).replace('()', ''),
                'age': pretty_timedelta(chgset.date, None, 3600),
                'author': to_unicode(chgset.author) or u'anonymous',
                'message': wikimsg
            }

            return 'revtree_log.html', {'log': data}, 'application/xhtml+xml'
        except Exception as e:
            raise TracError("Invalid revision log request: %s" % e)
开发者ID:ebouaziz,项目名称:TracRevTreePlugin,代码行数:36,代码来源:web_ui.py


示例16: process_request

    def process_request(self, req):
        options = self._get_options()
        connector = self.get_connector()
        last_builds = dict()
        builders = req.args['builders'].split(',')

        for builder in builders:
            try:
                build = connector.get_build(builder, -1)
                if "finish" in build and build["finish"]:
                    build["duration"] = pretty_timedelta(build["finish"], build["start"])
                    build["finish"] = format_datetime(build['finish'], tzinfo=req.tz)
                build["start"] = format_datetime(build['start'], tzinfo=req.tz)
            except Exception as e:
                last_builds[builder] = str(e)
            else:
                last_builds[builder] = build

        content = json.dumps(last_builds)

        req.send_header('Content-Type', 'application/javascript')
        req.send_header('Content-Length', len(content))
        req.end_headers()
        req.write(content)
开发者ID:Tramort,项目名称:tracbuildbot,代码行数:24,代码来源:web_ui.py


示例17: _process_wiki


#.........这里部分代码省略.........
            data['permonth'] = '%.2f' % (edits * 30 * 24 * 60 * 60. / age) 
            data['perday'] = '%.2f' % (edits * 24 * 60 * 60. / age) 
            data['perhour'] = '%.2f' % (edits * 60 * 60. / age) 
        else:
            data['peryear'] = 0
            data['permonth'] = 0
            data['perday'] = 0
            data['perhour'] = 0

        cursor.execute("select name, author, count(*) from wiki " + where + " group by 1, 2")
        pages = cursor.fetchall()

        d = {}
        for name, author, count in pages:
            try:
                d[author][0] += count
                d[author][1].add(name)
            except KeyError:
                d[author] = [count, set([name])]
        total = float(sum(x[0] for x in d.values()))
        stats = []
        for k, v in sorted(d.items(), key=itemgetter(1), reverse=True):
            stats.append({'name': k, 
                          'url': req.href.stats("wiki", author=k),
                          'count': v[0],
                          'pages': len(v[1]),
                          'percent': '%.2f' % (100 * v[0] / total)})
        data['byauthor'] = stats

        cursor.execute("""
        select name, %s """ % SECONDS + """
        from wiki """ + where + """
        order by 2 asc
        """)
        history = cursor.fetchall()

        stats = []
        if not req.args.get('author', ''):
            d = {}
            total = set()
            for name, t in history:
                total.add(name)
                d[int(t * 1000)] = len(total)
            stats = []
            steps = max(len(d) / 10, 1)
            for k, v in sorted(d.iteritems(), key=itemgetter(0))[::steps]:
                stats.append({'x': k, 
                              'y': v,})
        data['history'] = stats

        d = {}
        for name, _, count in pages:
            try:
                d[name] += count
            except KeyError:
                d[name] = count
        total = float(sum(d.values()))
        stats = []
        for k, v in sorted(d.items(), key=itemgetter(1), reverse=True)[:10]:
            stats.append({'name': k, 
                          'url': req.href.wiki(k),
                          'count': v,
                          'percent': '%.2f' % (100 * v / total)})
        data['pages'] = stats

        cursor.execute("""
        select name, version, length(text)
        from wiki """ + where + """
        group by 1, 2, 3
        having version = max(version)
        order by 3 desc
        limit 10
        """)
        rows = cursor.fetchall()
        d = dict((name, int(size)) for name, _, size in rows)
        stats = []
        for k, v in sorted(d.items(), key=itemgetter(1), reverse=True):
            stats.append({'name': k, 
                          'url': req.href.wiki(k),
                          'size': v})
        data['largest'] = stats

        cursor.execute("""
        select name, version, author, %s """ % SECONDS + """
        from wiki """ + where + """
        order by 4 desc
        limit 10
        """)
        rows = cursor.fetchall()
        stats = []
        for name, version, author, t in rows:
            stats.append({'name': name, 
                          'author': author,
                          'url': req.href.wiki(name, version=version),
                          'url2': req.href.stats("wiki", author=author),
                          'time': pretty_timedelta(to_datetime(float(t))),})

        data['recent'] = stats

        return 'wiki.html', data, None
开发者ID:icco,项目名称:tracstats,代码行数:101,代码来源:web_ui.py


示例18: _process_code


#.........这里部分代码省略.........
            paths = len(set(x[2] for x in changes if x[4] == author))

            year, week = map(int, time.strftime('%Y %W').split())
            weeks = []
            while len(weeks) < 52:
                name = '%04d-%02d' % (year, week)
                try:
                    total = d[author][name]
                except KeyError:
                    total = 0
                weeks.append({'week': name,
                              'total': total})
                week -= 1
                if week < 0:
                    year -= 1
                    week = 52
            stats.append({'name': author, 
                          'url': req.href.stats("code", author=author),
                          'commits': commits,
                          'rate': '%.2f' % (rate and float(rate) or 0),
                          'changes': change,
                          'paths': paths,
                          'weeks': list(reversed(weeks)),})
        data['byauthors'] = stats

        stats = []
        for rev, t, author, msg, repos in reversed(revisions[-10:]):
            reponame = repositories.get(repos, '')
            stats.append({'name': msg,
                          'author' : author,
                          'rev': rev,
                          'url': req.href.changeset(rev, reponame),
                          'url2': req.href.stats("code", author=author),
                          'time': pretty_timedelta(to_datetime(float(t))),})
        data['recent'] = stats

        times = dict((rev, t) for rev, t, _, _, _ in revisions)

        stats = []
        if not req.args.get('author', ''):
            d = {}
            total = set()
            for rev, _, path, change_type, _ in sorted(changes, key=lambda x: (times[x[0]], x[1])):
                if change_type in ('A', 'C'):
                    total.add(path)
                elif change_type == 'D' and path in total:
                    total.remove(path)
                d[int(times[rev] * 1000)] = len(total)
            stats = []
            steps = max(len(d) / 50, 1)
            for k, v in sorted(d.iteritems(), key=itemgetter(0))[::steps]:
                stats.append({'x': k, 
                              'y': v,})
        data['totalfiles'] = stats

        d = {}
        total = 0
        for _, t, _, _, _ in sorted(revisions, key=lambda x: x[1]):
            total += 1
            d[int(t * 1000)] = total
        stats = []
        steps = max(len(d) / 50, 1)
        for k, v in sorted(d.iteritems(), key=itemgetter(0))[::steps]:
            stats.append({'x': k, 
                          'y': v,})
        data['totalcommits'] = stats
开发者ID:icco,项目名称:tracstats,代码行数:67,代码来源:web_ui.py


示例19: pretty_lock_time

 def pretty_lock_time(self, user, next = False):
     """Convenience method for formatting lock time to string."""
     t_lock = self.lock_time(user, next)
     return (t_lock > 0) and pretty_timedelta(to_datetime(None) - \
         timedelta(microseconds = t_lock)) or None
开发者ID:lkraav,项目名称:trachacks,代码行数:5,代码来源:guard.py


示例20: _save_attachement

    def _save_attachement(self, req, attachment):
        from trac.web import RequestDone
        from trac.attachment import AttachmentModule, InvalidAttachment
        from trac.resource import get_resource_url
        from trac.timeline.web_ui import TimelineModule
        import os
        import unicodedata
        from trac.util.datefmt import pretty_timedelta

        response = None
        try:
            upload = req.args["attachment"]
            if not hasattr(upload, "filename") or not upload.filename:
                raise TracError(_("No file uploaded"))
            if hasattr(upload.file, "fileno"):
                size = os.fstat(upload.file.fileno())[6]
            else:
                upload.file.seek(0, 2)  # seek to end of file
                size = upload.file.tell()
                upload.file.seek(0)
            if size == 0:
                raise TracError(_("Can't upload empty file"))

            # Maximum attachment size (in bytes)
            max_size = AttachmentModule(self.env).max_size
            if max_size >= 0 and size > max_size:
                raise TracError(_("Maximum attachment size: %(num)s bytes", num=max_size), _("Upload failed"))

            # We try to normalize the filename to unicode NFC if we can.
            # Files uploaded from OS X might be in NFD.
            filename = unicodedata.normalize("NFC", unicode(upload.filename, "utf-8"))
            filename = filename.replace("\\", "/").replace(":", "/")
            filename = os.path.basename(filename)
            if not filename:
                raise TracError(_("No file uploaded"))
            # Now the filename is known, update the attachment resource
            # attachment.filename = filename
            attachment.description = req.args.get("description", "")
            attachment.author = get_reporter_id(req, "author")
            attachment.ipnr = req.remote_addr

            # Validate attachment
            for manipulator in AttachmentModule(self.env).manipulators:
                for field, message in manipulator.validate_attachment(req, attachment):
                    if field:
                        raise InvalidAttachment(
                            _("Attachment field %(field)s is " "invalid: %(message)s", field=field, message=message)
                        )
                    else:
                        raise InvalidAttachment(_("Invalid attachment: %(message)s", message=message))

            if req.args.get("replace"):
                try:
                    old_attachment = Attachment(self.env, attachment.resource(id=filename))
                    if not (old_attachment.author and req.authname and old_attachment.author == req.authname):
                        req.perm(attachment.resource).require("ATTACHMENT_DELETE")
                    if not attachment.description.strip() and old_attachment.description:
                        attachment.description = old_attachment.description
                    old_attachment.delete()
                except TracError:
                    pass  # don't worry if there's nothing to replace
                attachment.filename = None
            attachment.insert(filename, upload.file, size)
            timeline = TimelineModule(self.env).get_timeline_link(
                req, attachment.date, pretty_timedelta(attachment.date), precision="second"
            )
            response = {
                "attachment": {
                    "href": get_resource_url(self.env, attachment.resource, req.href),
                    "realm": attachment.resource.parent.realm,
                    "objid": attachment.resource.parent.id,
                    "filename": filename,
                    "size": size,
                    "author": attachment.author,
                    "description": attachment.description,
                    "timeline": timeline.generate().render().replace("<", "&lt;").replace(">", "&gt;"),
                }
            }
        except (TracError, InvalidAttachment), e:
            response = {"error": e.message}
开发者ID:rcarmo,项目名称:IttecoTracPlugin,代码行数:80,代码来源:web_ui.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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